Compare commits

...
Author SHA1 Message Date
halleriteandGitHub a3bf7e88b4 fix(nemotron3): faithful Nano/Super/Ultra rendering + per-variant config split (#84)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-12 11:01:40 -07:00
halleriteandGitHub d80f36e287 feat(deepseek): split into separate DeepSeek-V3 and DeepSeek-R1 renderers (#81)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-09 17:03:22 -07:00
1dca3b9a2d fix(parsing): don't parse in-<think> tool calls as real calls (#78) (#80)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
* fix(parsing): don't parse in-<think> tool calls as real calls

Reasoning models (Qwen3-*-Thinking, Kimi-K2.5, R1-distill via the
DeepSeek-V3 renderer) routinely draft tool-call syntax *inside* their
<think>...</think> trace while planning. The qwen3, deepseek_v3, and
kimi_k2.5 parsers scanned the whole completion for tool-call delimiters
and only extracted reasoning afterward, so those in-think drafts were
mis-parsed. Symptoms differed by format but all corrupt the tool result:

- qwen3 / qwen3_vl: emits the draft *and* the real call -> phantom
  duplicate (the reported #78 case; same code executed twice).
- kimi_k2.5: the in-think section trips the "truncated reasoning" guard
  and *all* tool calls are dropped (returns zero).
- deepseek_v3: returns the *wrong* call (the draft) and loses reasoning.

Fix: extract reasoning first, then scan for tool calls only in the
post-</think> region — mirroring vLLM's DelegatingParser (reasoning
parser runs before the tool parser). Where </think> is a single special
token (Qwen3) we anchor on its id; where it's multi-token / context-
sensitive text (DeepSeek-V3, Kimi-K2.5) we locate the boundary by
decoding. content_ids still starts at 0 so reasoning extraction is
unchanged, and genuine parallel calls after </think> are preserved.

Audited all parsers: qwen3.5/glm/minimax/laguna/nemotron3 already strip
reasoning first; gpt_oss (channel-segregated) and llama_3 (no reasoning)
are safe; kimi_k2 (K2-Instruct) has no thinking path so is unaffected.

Validated against real Qwen3, Kimi-K2.5 and DeepSeek-V3 tokenizers.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* style: ruff format

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 00:26:25 +02:00
halleriteandGitHub e6dba5ad6c feat: add Llama-3 renderer for Llama-3.2-1B/3B-Instruct (#9)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-08 19:47:06 +02:00
halleriteandGitHub 596c15ffd9 feat(nemotron3): add Nemotron-3 Ultra chat-template variant (#77)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-04 16:46:36 +02:00
Kemal ErdemandGitHub 942449c37a Merge pull request #76 from PrimeIntellect-ai/security/cooldown-7d
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
security: extend cooldown exempt list with prime-pydantic-config
2026-05-31 00:30:01 +02:00
Kemal ErdemandClaude Opus 4.7 9f3b24c0ac chore(security): extend cooldown exempt list with prime-pydantic-config
renderers already had exclude-newer = "7 days" with a per-package
exemption for fastokens. This PR splits the inline table into a
[tool.uv.exclude-newer-package] section and adds the only other
PrimeIntellect-published package in renderers' dep closure:
prime-pydantic-config.

Only packages in this project's `uv tree` are exempted — the resolver
ignores entries for packages it never sees.

Pins `required-version = ">=0.11.1"` so older uvs fail loudly instead
of silently parsing "7 days" as an RFC 3339 date and proceeding
*without* the cooldown — see uv#17908.

Part 1 of 3 in a coordinated supply-chain hardening across PI repos.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 22:30:23 +02:00
halleriteandGitHub 35c2407e92 fix(tokenizer): apply config-build fallback to offset tokenizer too (#75)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-28 20:58:02 +02:00
Sebastian MüllerandGitHub a11f8d8193 feat(base): add message_tool_names field for per-message tool attribution (#74)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-28 20:49:47 +02:00
halleriteandGitHub 89ab3f0bed fix(tokenizer): fall back to direct fast-tokenizer load when model config build fails (#72)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-28 00:19:19 +02:00
halleriteandGitHub e729baa5af refactor(qwen3.5): hard-code enable_thinking default per model (#71)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-27 19:54:58 +02:00
halleriteandGitHub 74425da166 fix(examples): update multi-turn examples to current renderer API (#68)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-27 19:07:11 +02:00
halleriteandGitHub 1569dc980d fix(deps): lower openai-harmony floor to >=0.0.4 for SGLang compatibility (#69)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-27 19:01:20 +02:00
halleriteandGitHub 1d69232253 feat(glm): make next-message role marker trainable after assistant turns (#66)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-26 22:56:24 +02:00
39 changed files with 3355 additions and 348 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ next_prompt_ids = r.bridge_to_next_turn(
)
```
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `nemotron-3-ultra`, `gpt-oss`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
## API
+29 -10
View File
@@ -22,6 +22,7 @@ import json
import os
import sglang as sgl
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from transformers import AutoTokenizer
@@ -52,7 +53,9 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None):
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
return Qwen35Renderer(
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
@@ -62,8 +65,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -141,21 +145,33 @@ def main() -> None:
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -167,11 +183,14 @@ def main() -> None:
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
+29 -10
View File
@@ -44,6 +44,7 @@ from typing import Any
import httpx
from renderers.base import Renderer
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from transformers import AutoTokenizer
@@ -71,7 +72,9 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None) -> Renderer:
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
return Qwen35Renderer(
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
@@ -116,8 +119,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -164,21 +168,33 @@ async def run_one(
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages: list[dict[str, Any]] = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -190,11 +206,14 @@ async def run_one(
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
+29 -10
View File
@@ -22,6 +22,7 @@ import json
import os
import tinker
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from tinker import types
@@ -53,7 +54,9 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None):
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
return Qwen35Renderer(
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
@@ -63,8 +66,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -131,21 +135,33 @@ async def main() -> None:
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -157,11 +173,14 @@ async def main() -> None:
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
@@ -26,6 +26,7 @@ import os
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
@@ -55,7 +56,8 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None):
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking), tokenizer
config = Qwen35RendererConfig(enable_thinking=enable_thinking)
return Qwen35Renderer(tokenizer, config), tokenizer
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer), tokenizer
raise ValueError(f"unsupported demo model: {model}")
@@ -65,8 +67,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -139,21 +142,33 @@ def main() -> None:
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -165,11 +180,14 @@ def main() -> None:
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
+29 -10
View File
@@ -21,6 +21,7 @@ import gc
import json
import os
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from transformers import AutoTokenizer
@@ -52,7 +53,9 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None):
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
return Qwen35Renderer(
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
@@ -62,8 +65,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -134,21 +138,33 @@ def main() -> None:
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -160,11 +176,14 @@ def main() -> None:
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
+20 -2
View File
@@ -23,7 +23,14 @@ dependencies = [
# Used by GptOssRenderer to render and parse harmony tokens. Vendoring
# OpenAI's reference implementation keeps us byte-identical with vLLM
# (which also uses it) and saves us mirroring a 330-line Jinja template.
"openai-harmony>=0.0.8",
#
# Floor is ``>=0.0.4`` (not the latest 0.0.8) on purpose: every SGLang
# release through 0.5.12.post1 hard-pins ``openai-harmony==0.0.4``, so a
# higher floor makes ``renderers`` uninstallable alongside SGLang. The
# GptOssRenderer renders byte-identically on 0.0.4 (verified token-for-token
# against 0.0.8) and ``tests/test_gpt_oss_harmony_parity.py`` passes on it,
# so the older harmony is safe.
"openai-harmony>=0.0.4",
# Crusoe's Rust BPE tokenizer; ~10x faster encode vs HF's tokenizers.
# ``load_tokenizer`` patches it in by default for every supported model
# except a small denylist (DeepSeek-V3 family). The patch is bracketed
@@ -72,13 +79,24 @@ dev = [
]
[tool.uv]
# Enforce a uv version that supports the friendly-duration form
# (`"7 days"`) in the static pyproject parser. Older uvs silently parse
# the value as an RFC 3339 date, emit a TOML parse warning, and proceed
# *without* the cooldown — bypassing this security policy.
required-version = ">=0.11.1"
exclude-newer = "7 days"
[tool.uv.exclude-newer-package]
# fastokens 0.2.0 was published on 2026-05-17 and contains the
# ``unpatch_transformers`` fix (crusoecloud/fastokens#32) needed for
# MiniMax-M2's slow→fast tokenizer conversion path. Exempting it from
# the project-wide 7-day cutoff lets the lockfile pick it up immediately
# while the rest of the dependency graph stays gated.
exclude-newer-package = { fastokens = false, "prime-pydantic-config" = false }
fastokens = false
# PrimeIntellect-published packages in this project's dependency closure —
# fast-track so first-party releases can land same-day. Only packages that
# appear in `uv tree` are listed.
prime-pydantic-config = false
[tool.ty.environment]
python-version = "3.13"
+14
View File
@@ -33,6 +33,7 @@ from renderers.base import (
build_trajectory_step,
create_renderer,
create_renderer_pool,
extract_message_tool_names,
is_multimodal,
reject_assistant_in_extension,
trim_to_turn_close,
@@ -43,6 +44,7 @@ from renderers.configs import (
BaseRendererConfig,
config_from_name,
DefaultRendererConfig,
DeepSeekR1RendererConfig,
DeepSeekV3RendererConfig,
GLM45RendererConfig,
GLM51RendererConfig,
@@ -51,8 +53,10 @@ from renderers.configs import (
KimiK25RendererConfig,
KimiK2RendererConfig,
LagunaXS2RendererConfig,
Llama3RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen3RendererConfig,
@@ -72,6 +76,7 @@ from renderers.configs import (
# imports — ``renderers.base._populate_registry`` lazy-imports the
# concrete classes itself when a renderer is instantiated.
_LAZY_RENDERERS: dict[str, str] = {
"DeepSeekR1Renderer": "renderers.deepseek_r1",
"DeepSeekV3Renderer": "renderers.deepseek_v3",
"DefaultRenderer": "renderers.default",
"GLM45Renderer": "renderers.glm45",
@@ -81,8 +86,10 @@ _LAZY_RENDERERS: dict[str, str] = {
"KimiK25Renderer": "renderers.kimi_k25",
"KimiK2Renderer": "renderers.kimi_k2",
"LagunaXS2Renderer": "renderers.laguna_xs2",
"Llama3Renderer": "renderers.llama_3",
"MiniMaxM2Renderer": "renderers.minimax_m2",
"Nemotron3Renderer": "renderers.nemotron3",
"Nemotron3UltraRenderer": "renderers.nemotron3",
"Qwen35Renderer": "renderers.qwen35",
"Qwen36Renderer": "renderers.qwen36",
"Qwen3Renderer": "renderers.qwen3",
@@ -110,6 +117,8 @@ __all__ = [
"BaseRendererConfig",
"Content",
"ContentPart",
"DeepSeekR1Renderer",
"DeepSeekR1RendererConfig",
"DeepSeekV3Renderer",
"DeepSeekV3RendererConfig",
"DefaultRenderer",
@@ -129,6 +138,8 @@ __all__ = [
"KimiK2RendererConfig",
"LagunaXS2Renderer",
"LagunaXS2RendererConfig",
"Llama3Renderer",
"Llama3RendererConfig",
"MULTIMODAL_MODELS",
"Message",
"MiniMaxM2Renderer",
@@ -137,6 +148,8 @@ __all__ = [
"MultimodalRenderer",
"Nemotron3Renderer",
"Nemotron3RendererConfig",
"Nemotron3UltraRenderer",
"Nemotron3UltraRendererConfig",
"OverlongPromptError",
"ParsedResponse",
"ParsedToolCall",
@@ -168,6 +181,7 @@ __all__ = [
"config_from_name",
"create_renderer",
"create_renderer_pool",
"extract_message_tool_names",
"is_multimodal",
"reject_assistant_in_extension",
"trim_to_turn_close",
+232 -28
View File
@@ -6,6 +6,7 @@ import io
import logging
import queue
import threading
from collections.abc import Mapping
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import (
@@ -117,6 +118,68 @@ class Message(TypedDict, total=False):
reasoning_content: str
def extract_message_tool_names(messages: list[Message]) -> list[str | None]:
"""Per-message tool function names parallel to ``message_roles``.
Returns one entry per message: the function name for ``role="tool"``
messages, ``None`` for every other message. Length matches the
input list.
For tool messages the name is taken from ``msg["name"]`` when set
(caller-provided), otherwise recovered by joining
``msg["tool_call_id"]`` against any prior assistant's
``tool_calls[i].function.name`` in the same list. Tool messages
whose issuing assistant lives outside the provided list (e.g. on
a :meth:`Renderer.bridge_to_next_turn` call where ``new_messages``
covers only the new turn) resolve to ``None``.
Pure metadata: this never mutates the caller's messages and has
no effect on the rendered token stream. It runs independently of
the render path so the renderer can populate the field on
:class:`RenderedTokens` without breaking HF byte parity for tool
messages that carry no ``name``. Callers who *also* want the
function name to appear in the rendered scaffold (e.g. GPT-OSS
Harmony's ``functions.{name}`` prefix) must attach ``name`` to
their tool messages before calling :meth:`Renderer.render`
themselves — renderers don't synthesize ``name`` into the input,
only into this metadata field.
Trainers join this list with :attr:`RenderedTokens.message_indices`
to recover per-token tool attribution — the canonical use case is
SFT on tool response bodies while RL acts only on assistant tokens
(tool body tokens get a constant positive advantage so the model
learns to anticipate tool outputs without learning to emit
``<|tool_response>`` itself).
Per-message rather than per-token because the data is naturally
per-message — storing it per-token would duplicate the same
string across every body token of the same tool message.
"""
lookup: dict[str, str] = {}
for m in messages:
if not isinstance(m, Mapping) or m.get("role") != "assistant":
continue
for tc in m.get("tool_calls") or []:
if not isinstance(tc, Mapping):
continue
tc_id = tc.get("id")
fn = tc.get("function")
tc_name = fn.get("name") if isinstance(fn, Mapping) else None
if isinstance(tc_id, str) and isinstance(tc_name, str):
lookup[tc_id] = tc_name
out: list[str | None] = []
for m in messages:
if not isinstance(m, Mapping) or m.get("role") != "tool":
out.append(None)
continue
name = m.get("name")
if not (isinstance(name, str) and name):
tc_id = m.get("tool_call_id")
name = lookup.get(tc_id) if isinstance(tc_id, str) else None
out.append(name if isinstance(name, str) and name else None)
return out
# ---------------------------------------------------------------------------
# Renderer data types
# ---------------------------------------------------------------------------
@@ -208,6 +271,32 @@ class RenderedTokens:
renderer doesn't provide the signal. ``DefaultRenderer`` leaves it
empty for the same reason.
``message_tool_names`` is the per-message tool function name list,
parallel to ``message_roles`` (same length). For tool-role
messages it carries the function name — either taken from
``msg["name"]`` (caller-provided) or recovered by joining
``msg["tool_call_id"]`` against a prior assistant's
``tool_calls[i].function.name`` in the rendered slice. Every
other message is ``None``, as are tool messages whose issuing
assistant lives outside the rendered slice (e.g. on a
:meth:`Renderer.bridge_to_next_turn` call where ``new_messages``
covers only the new turn).
This is pure metadata, computed by :func:`extract_message_tool_names`
independently of the render path: populating it never touches the
rendered token stream, so HF chat-template byte parity is
preserved for tool messages carrying no ``name``. Callers who
*also* want the function name to appear in the rendered scaffold
(e.g. GPT-OSS Harmony's ``functions.{name}`` prefix) must attach
``name`` to their tool messages before calling
:meth:`Renderer.render` themselves.
Trainers join this with ``message_indices`` to build per-tool
selective loss masks (SFT on tool response bodies of a specific
tool while RL acts on assistant tokens). Empty
``message_tool_names`` (``[]``) means the renderer doesn't
provide the signal.
``multi_modal_data`` is populated by multimodal renderers (e.g.
``Qwen3VLRenderer``) when image / video content parts are present;
text-only renderers leave it as ``None``.
@@ -218,6 +307,7 @@ class RenderedTokens:
sampled_mask: list[bool] = field(default_factory=list)
is_content: list[bool] = field(default_factory=list)
message_roles: list[str] = field(default_factory=list)
message_tool_names: list[str | None] = field(default_factory=list)
multi_modal_data: "MultiModalData | None" = None
def tokens_per_message(
@@ -911,8 +1001,8 @@ MODEL_RENDERER_MAP: dict[str, str] = {
# ``enable_thinking=true`` (open ``<think>\n`` at the gen prompt);
# the smaller 0.8B / 2B variants flip the polarity (default
# ``enable_thinking=false``, empty ``<think>\n\n</think>\n\n``).
# ``Qwen35Renderer`` auto-detects polarity from the tokenizer's
# chat_template at construction, so all seven sizes are
# ``Qwen35Renderer`` hard-codes this polarity per model
# (``_ENABLE_THINKING_DEFAULTS``), so all seven sizes are
# token-for-token parity-tested against their own
# ``apply_chat_template`` — including with
# ``add_generation_prompt=True``.
@@ -940,16 +1030,33 @@ MODEL_RENDERER_MAP: dict[str, str] = {
# MiniMax.
"MiniMaxAI/MiniMax-M2": "minimax-m2",
"MiniMaxAI/MiniMax-M2.5": "minimax-m2",
# DeepSeek V3.
# DeepSeek V3 (non-reasoning).
"deepseek-ai/DeepSeek-V3": "deepseek-v3",
"deepseek-ai/DeepSeek-V3-Base": "deepseek-v3",
# DeepSeek R1 (reasoning).
"deepseek-ai/DeepSeek-R1": "deepseek-r1",
"deepseek-ai/DeepSeek-R1-0528": "deepseek-r1",
# Kimi K2 (K2.5 and K2.6 share the K2.5 template, distinct from K2).
"moonshotai/Kimi-K2-Instruct": "kimi-k2",
"moonshotai/Kimi-K2.5": "kimi-k2.5",
"moonshotai/Kimi-K2.6": "kimi-k2.5",
# Nemotron 3.
# Nemotron 3. Nano / Super share one chat-template variant (``nemotron-3``);
# the Ultra checkpoints use the Ultra variant (``nemotron-3-ultra``, distinct
# ``</think>`` glue). Both route to the same Nemotron3Renderer, which selects
# the variant from the resolved config's ``name``. BF16 and FP8 share the
# same tokenizer and template.
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "nemotron-3",
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "nemotron-3",
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16": "nemotron-3-ultra",
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8": "nemotron-3-ultra",
# Llama 3.2 (Instruct). Tested against the gated meta-llama repos and
# the unrestricted unsloth/... mirror, which ships a byte-identical
# chat template. ``Llama3Renderer`` defaults ``date_string`` to
# "26 Jul 2024" — matching the chat template's strftime fallback —
# so the renderer is reproducible. Pass ``date_string=...`` at
# construction to pin a different date.
"meta-llama/Llama-3.2-1B-Instruct": "llama-3",
"meta-llama/Llama-3.2-3B-Instruct": "llama-3",
# Poolside Laguna.
"poolside/Laguna-XS.2": "laguna-xs.2",
# GPT-OSS.
@@ -1058,6 +1165,8 @@ FASTOKENS_INCOMPATIBLE: frozenset[str] = frozenset(
# doesn't yet implement.
"deepseek-ai/DeepSeek-V3",
"deepseek-ai/DeepSeek-V3-Base",
"deepseek-ai/DeepSeek-R1",
"deepseek-ai/DeepSeek-R1-0528",
}
)
@@ -1089,7 +1198,6 @@ def _patched_load(model_name_or_path: str, **kwargs):
path is still discoverable in logs.
"""
import fastokens
from transformers import AutoTokenizer
global _FASTOKENS_ANNOUNCED
@@ -1098,18 +1206,76 @@ def _patched_load(model_name_or_path: str, **kwargs):
fastokens.patch_transformers()
if not _FASTOKENS_ANNOUNCED:
logger.info(
"fastokens enabled — tokenizers load through the Rust BPE "
"fast path (~10x encode speedup)."
"fastokens enabled — tokenizers load through the Rust BPE fast path (~10x encode speedup)."
)
_FASTOKENS_ANNOUNCED = True
try:
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
return _load_tokenizer_via_auto(model_name_or_path, **kwargs)
finally:
with _FASTOKENS_PATCH_LOCK:
with contextlib.redirect_stdout(io.StringIO()):
fastokens.unpatch_transformers()
def _load_fast_tokenizer_directly(
model_name_or_path: str, revision: str | None
) -> Any | None:
"""Load a self-contained fast tokenizer without building the model config.
``AutoTokenizer.from_pretrained`` eagerly constructs the *model* config to
resolve the tokenizer class — even for a plain ``PreTrainedTokenizerFast``.
That construction can raise on modeling-only concerns the tokenizer never
needs (e.g. RoPE parameter validation for configs that carry nested
``rope_parameters``). When the repo ships a complete ``tokenizer.json`` and
declares no custom tokenizer, the tokenizer is fully self-describing, so we
load it directly and skip the config detour.
Returns ``None`` when there's nothing safe to load this way — a custom
``auto_map`` tokenizer (which must run through ``AutoTokenizer`` with
``trust_remote_code``) or no fast tokenizer at all — so the caller can
surface its original error instead.
"""
from transformers import PreTrainedTokenizerFast
from transformers.models.auto.tokenization_auto import get_tokenizer_config
try:
if "auto_map" in get_tokenizer_config(model_name_or_path, revision=revision):
return None
return PreTrainedTokenizerFast.from_pretrained(
model_name_or_path, revision=revision
)
except Exception:
return None
def _load_tokenizer_via_auto(model_name_or_path: str, **kwargs) -> Any:
"""``AutoTokenizer.from_pretrained`` with a config-free fallback.
renderers needs the tokenizer, not the model. If ``AutoTokenizer`` fails
while building the model config it loads to resolve the tokenizer class,
retry by loading the repo's self-contained ``tokenizer.json`` directly. The
original error is re-raised if the repo has no such tokenizer.
"""
from transformers import AutoTokenizer
try:
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
except Exception as exc:
tok = _load_fast_tokenizer_directly(
model_name_or_path, revision=kwargs.get("revision")
)
if tok is None:
raise
logger.debug(
"AutoTokenizer.from_pretrained(%r) failed building the model config "
"(%s: %s); loaded the tokenizer directly from tokenizer.json.",
model_name_or_path,
type(exc).__name__,
str(exc)[:160],
)
return tok
def load_tokenizer(
model_name_or_path: str,
*,
@@ -1139,9 +1305,14 @@ def load_tokenizer(
fastokens raises during the patched load (e.g. an unknown
pre-tokenizer type), we automatically retry with the vanilla
backend and emit an INFO log.
"""
from transformers import AutoTokenizer
``AutoTokenizer.from_pretrained`` eagerly builds the model config to
resolve the tokenizer class. If that construction raises on a
modeling-only concern the tokenizer doesn't need (e.g. RoPE
validation for configs with nested ``rope_parameters``), we fall
back to loading the repo's self-contained ``tokenizer.json``
directly — see ``_load_tokenizer_via_auto``.
"""
kwargs: dict[str, Any] = {}
revision = TRUSTED_REVISIONS.get(model_name_or_path)
if revision is not None:
@@ -1150,7 +1321,7 @@ def load_tokenizer(
kwargs = {"trust_remote_code": False}
if not use_fastokens or model_name_or_path in FASTOKENS_INCOMPATIBLE:
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
return _load_tokenizer_via_auto(model_name_or_path, **kwargs)
try:
return _patched_load(model_name_or_path, **kwargs)
@@ -1163,22 +1334,24 @@ def load_tokenizer(
type(exc).__name__,
str(exc)[:160],
)
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
return _load_tokenizer_via_auto(model_name_or_path, **kwargs)
def _populate_registry():
if RENDERER_REGISTRY:
return
from renderers.default import DefaultRenderer
from renderers.deepseek_r1 import DeepSeekR1Renderer
from renderers.deepseek_v3 import DeepSeekV3Renderer
from renderers.default import DefaultRenderer
from renderers.glm5 import GLM5Renderer, GLM51Renderer
from renderers.glm45 import GLM45Renderer
from renderers.gpt_oss import GptOssRenderer
from renderers.kimi_k2 import KimiK2Renderer
from renderers.kimi_k25 import KimiK25Renderer
from renderers.laguna_xs2 import LagunaXS2Renderer
from renderers.llama_3 import Llama3Renderer
from renderers.minimax_m2 import MiniMaxM2Renderer
from renderers.nemotron3 import Nemotron3Renderer
from renderers.nemotron3 import Nemotron3Renderer, Nemotron3UltraRenderer
from renderers.qwen3 import Qwen3Renderer
from renderers.qwen3_vl import Qwen3VLRenderer
from renderers.qwen35 import Qwen35Renderer
@@ -1196,10 +1369,13 @@ def _populate_registry():
"glm-4.5": GLM45Renderer,
"minimax-m2": MiniMaxM2Renderer,
"deepseek-v3": DeepSeekV3Renderer,
"deepseek-r1": DeepSeekR1Renderer,
"kimi-k2": KimiK2Renderer,
"kimi-k2.5": KimiK25Renderer,
"laguna-xs.2": LagunaXS2Renderer,
"llama-3": Llama3Renderer,
"nemotron-3": Nemotron3Renderer,
"nemotron-3-ultra": Nemotron3UltraRenderer,
"gpt-oss": GptOssRenderer,
}
)
@@ -1271,8 +1447,7 @@ def create_renderer(
cls = RENDERER_REGISTRY.get(config.name)
if cls is None:
raise ValueError(
f"Unknown renderer {config.name!r}. "
f"Available: {', '.join(sorted(RENDERER_REGISTRY))}"
f"Unknown renderer {config.name!r}. Available: {', '.join(sorted(RENDERER_REGISTRY))}"
)
return cls(tokenizer, config)
@@ -1345,7 +1520,7 @@ def build_training_sample(
renderer: Renderer,
messages: list[Message],
*,
role_to_mask: Callable[[Message], bool],
role_to_mask: Callable[[Message], bool] | None = None,
tools: list[ToolSpec] | None = None,
content_sft_roles: "set[str] | frozenset[str] | None" = None,
) -> tuple[list[int], list[bool]]:
@@ -1354,15 +1529,31 @@ def build_training_sample(
Single render() call + message_indices → per-token mask.
Replaces build_incremental_token_mask (O(N) renders → O(1)).
When the renderer populates ``rendered.sampled_mask``, the loss mask
is the AND of role-based attribution and the sampled signal: only
tokens the model would have produced at inference are trainable.
This keeps SFT byte-aligned with the RL trajectory mask (where the
prompt / completion split achieves the same effect structurally).
When ``role_to_mask`` is omitted, ``loss_mask`` is the renderer's
``sampled_mask`` directly: every token the model would have
produced at inference is trainable, regardless of which message
it's attributed to. This is the recommended default for renderer
callers — the renderer owns the per-token "is this model output"
signal, so role-level filtering becomes a downstream constraint
rather than a precondition. (Some role markers — e.g. GLM
``<|user|>`` / ``<|observation|>`` after a tool-calling assistant
turn — *are* sampled by the model at inference and live inside the
next message's span; ``sampled_mask`` captures that, but a
naive role filter would mask them out.)
When ``role_to_mask`` is provided, ``loss_mask`` is the AND of the
role-based attribution and the sampled signal: only tokens the
model would have produced at inference AND attributed to a
trainable role pass through. Useful when the caller needs to
restrict training to a specific role (e.g. assistant-only) even on
a renderer whose ``sampled_mask`` already covers other roles.
Renderers that don't populate ``sampled_mask`` (empty list) fall
back to attribution-only masking — every token attributed to a
trainable role is trained on, including template-injected
``<|im_start|>role\\n`` openers.
``<|im_start|>role\\n`` openers. In this fallback mode
``role_to_mask`` is required; calling without it raises
``ValueError``.
``content_sft_roles`` opts in additional roles for "body-only"
supervision: for every message whose role is in this set, tokens
@@ -1393,6 +1584,13 @@ def build_training_sample(
else:
body_roles = frozenset()
if role_to_mask is None and not has_sampled_info:
raise ValueError(
"role_to_mask is required when the renderer does not populate "
"sampled_mask. Pass an explicit role filter (e.g. "
"lambda m: m['role'] == 'assistant') for this renderer."
)
loss_mask: list[bool] = []
for k, msg_idx in enumerate(rendered.message_indices):
if msg_idx < 0:
@@ -1408,6 +1606,11 @@ def build_training_sample(
continue
if has_sampled_info and not rendered.sampled_mask[k]:
loss_mask.append(False)
elif role_to_mask is None:
# sampled_mask alone gates the loss when no role filter is
# supplied. ``sampled_mask[k]`` is True here (handled by the
# branch above), so this token is trainable.
loss_mask.append(True)
else:
loss_mask.append(role_to_mask(msg))
return rendered.token_ids, loss_mask
@@ -1498,7 +1701,6 @@ def _get_offset_tokenizer(tokenizer):
cached = _offset_tokenizers.get(name_or_path)
if cached is not None:
return cached
from transformers import AutoTokenizer
kwargs: dict[str, Any] = {}
revision = TRUSTED_REVISIONS.get(name_or_path)
@@ -1508,10 +1710,12 @@ def _get_offset_tokenizer(tokenizer):
kwargs = {"trust_remote_code": False}
# Explicitly vanilla — we want HF's Rust tokenizer with offset
# tracking, not the fastokens shim. ``load_tokenizer`` would
# patch fastokens in by default; calling
# ``AutoTokenizer.from_pretrained`` directly here keeps the
# fastokens patch out of this code path entirely.
offset_tok = AutoTokenizer.from_pretrained(name_or_path, **kwargs)
# patch fastokens in by default; routing through
# ``_load_tokenizer_via_auto`` keeps the fastokens patch out
# of this code path while still applying the config-build
# fallback (RoPE-validation failures on nested
# ``rope_parameters``, etc.).
offset_tok = _load_tokenizer_via_auto(name_or_path, **kwargs)
if not getattr(offset_tok, "is_fast", False):
raise RuntimeError(
f"Vanilla tokenizer for {name_or_path!r} is not a fast "
+92 -13
View File
@@ -318,6 +318,31 @@ class LagunaXS2RendererConfig(BaseRendererConfig):
chat template's ``render_assistant_messages_raw`` gate."""
class Llama3RendererConfig(BaseRendererConfig):
"""Llama-3.x Instruct renderer config.
Llama-3 ships no reasoning channel, so the base ``preserve_*_thinking``
flags don't apply: ``Llama3Renderer`` raises ``NotImplementedError``
if either is set (matching ``DefaultRenderer``'s contract for the
same case). Both fields below mirror real ``apply_chat_template``
kwargs.
"""
name: Literal["llama-3"] = "llama-3"
date_string: str = "26 Jul 2024"
"""``Today Date`` value injected into the system preamble. Pinned to
the chat template's ``strftime`` fallback by default so output stays
deterministic; override per instance for production runs that want
today's date. Mirrors the chat template's ``date_string`` kwarg."""
tools_in_user_message: bool = True
"""When ``True`` (default), tool descriptions + JSON signatures inject
into the first user message; ``False`` routes them into the system
block instead. Mirrors the chat template's ``tools_in_user_message``
kwarg."""
class MiniMaxM2RendererConfig(BaseRendererConfig):
"""MiniMax M2 / M2.5 renderer config."""
@@ -329,7 +354,14 @@ class MiniMaxM2RendererConfig(BaseRendererConfig):
class Nemotron3RendererConfig(BaseRendererConfig):
"""Nemotron 3 renderer config."""
"""Nemotron-3 **Nano / Super** renderer config.
Nano and Super share one chat-template variant; the renderer routes both
through :class:`renderers.nemotron3.Nemotron3Renderer`. The Ultra variant
has its own template (different reasoning-block glue) and config —
:class:`Nemotron3UltraRendererConfig` — and is reached via the
``nemotron-3-ultra`` discriminator.
"""
name: Literal["nemotron-3"] = "nemotron-3"
@@ -344,26 +376,64 @@ class Nemotron3RendererConfig(BaseRendererConfig):
``preserve_all_thinking`` / ``preserve_thinking_between_tool_calls``
— see :class:`BaseRendererConfig` for the contract."""
low_effort: bool = False
"""When ``True``, append ``\\n\\n{reasoning effort: low}`` to the last user
message, nudging the model toward shorter reasoning. Mirrors the **Super**
chat template's ``low_effort`` kwarg. A no-op on **Nano** (its template
doesn't define it) — exactly as ``apply_chat_template`` ignores an undefined
template variable; the renderer distinguishes the two by model name (see
``renderers.nemotron3._is_super``)."""
class Nemotron3UltraRendererConfig(BaseRendererConfig):
"""Nemotron-3 **Ultra** renderer config — distinct discriminator so the
registry routes Ultra checkpoints to the Ultra template variant.
Ultra's template differs from Nano/Super: the reasoning block is glued as
``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around ``</think>``)
and truncated historical turns collapse to ``<think></think>{content}``
(no ``\\n``). It shares the :class:`renderers.nemotron3.Nemotron3Renderer`
implementation, which selects the variant from ``config.name``.
"""
name: Literal["nemotron-3-ultra"] = "nemotron-3-ultra"
enable_thinking: bool = True
"""See :class:`Nemotron3RendererConfig.enable_thinking`."""
truncate_history_thinking: bool = True
"""See :class:`Nemotron3RendererConfig.truncate_history_thinking`."""
medium_effort: bool = False
"""When ``True``, append ``\\n\\n{reasoning effort: efficient}`` to the last
user message. Mirrors the Ultra chat template's ``medium_effort`` kwarg."""
class DeepSeekV3RendererConfig(BaseRendererConfig):
"""DeepSeek V3 renderer config.
"""DeepSeek-V3 renderer config (non-reasoning).
``enable_thinking`` is renderer-internal here — DeepSeek-V3's chat
template does not reference any thinking variable, so passing it to
``apply_chat_template`` upstream is a no-op. The renderer uses it
to control the ``<think>`` prefill at the generation prompt (R1
distill convention).
DeepSeek-V3 has no thinking concept: the generation prompt is a bare
``<|Assistant|>`` and assistant content is emitted verbatim. For the
reasoning variant use :class:`DeepSeekR1RendererConfig`.
"""
name: Literal["deepseek-v3"] = "deepseek-v3"
enable_thinking: bool = True
"""Renderer convention for the R1-distill family: when ``True``,
prefill ``<think>`` at the generation prompt. The DeepSeek-V3 Jinja
template ignores this kwarg upstream; it's not a chat-template
kwarg in the strict sense."""
_internal_fields = frozenset({"enable_thinking"})
class DeepSeekR1RendererConfig(BaseRendererConfig):
"""DeepSeek-R1 renderer config (reasoning).
R1 always reasons — its chat template unconditionally prefills
``<think>\\n`` at the generation prompt and strips ``</think>`` from
historical assistant turns. There is therefore no ``enable_thinking``
knob (thinking is not optional), and ``preserve_*`` flags are no-ops
(history reasoning is always dropped); both stored for protocol
uniformity. Applies to full ``deepseek-ai/DeepSeek-R1`` / ``-R1-0528``
— NOT the R1-Distill-Qwen/Llama models, which use those base
tokenizers and route to the Qwen3 / Llama-3 renderers.
"""
name: Literal["deepseek-r1"] = "deepseek-r1"
RendererConfig = Annotated[
@@ -381,9 +451,12 @@ RendererConfig = Annotated[
KimiK2RendererConfig,
KimiK25RendererConfig,
LagunaXS2RendererConfig,
Llama3RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
DeepSeekV3RendererConfig,
DeepSeekR1RendererConfig,
],
Field(discriminator="name"),
]
@@ -415,9 +488,12 @@ _CONFIG_BY_NAME: dict[str, type[BaseRendererConfig]] = {
"kimi-k2": KimiK2RendererConfig,
"kimi-k2.5": KimiK25RendererConfig,
"laguna-xs.2": LagunaXS2RendererConfig,
"llama-3": Llama3RendererConfig,
"minimax-m2": MiniMaxM2RendererConfig,
"nemotron-3": Nemotron3RendererConfig,
"nemotron-3-ultra": Nemotron3UltraRendererConfig,
"deepseek-v3": DeepSeekV3RendererConfig,
"deepseek-r1": DeepSeekR1RendererConfig,
}
@@ -449,6 +525,7 @@ __all__ = [
"AutoRendererConfig",
"BaseRendererConfig",
"DefaultRendererConfig",
"DeepSeekR1RendererConfig",
"DeepSeekV3RendererConfig",
"GLM45RendererConfig",
"GLM51RendererConfig",
@@ -457,8 +534,10 @@ __all__ = [
"KimiK25RendererConfig",
"KimiK2RendererConfig",
"LagunaXS2RendererConfig",
"Llama3RendererConfig",
"MiniMaxM2RendererConfig",
"Nemotron3RendererConfig",
"Nemotron3UltraRendererConfig",
"Qwen35RendererConfig",
"Qwen36RendererConfig",
"Qwen3RendererConfig",
+58
View File
@@ -0,0 +1,58 @@
"""DeepSeek-R1 Renderer — the reasoning variant of the DeepSeek format.
R1 shares DeepSeek-V3's special tokens, message structure, and tool-call
wire format, so it subclasses :class:`renderers.deepseek_v3.DeepSeekV3Renderer`
and overrides only the two places its chat template diverges:
1. Generation prompt — R1 unconditionally prefills ``<think>\\n``
(``<|Assistant|><think>\\n``) to trigger reasoning, where V3 emits a bare
``<|Assistant|>``. Handled by ``_GEN_THINK_PREFILL``.
2. Historical assistant turns — R1 strips the reasoning trace, keeping only
the text after ``</think>`` (``content.split('</think>')[-1]``), where V3
emits content verbatim. Handled by ``_prepare_assistant_content``.
Everything else — system handling, tool-call / tool-output rendering,
special-token resolution, and ``parse_response`` (``parse_deepseek_v3``,
shared) — is inherited unchanged.
Scope: full ``deepseek-ai/DeepSeek-R1`` and ``-R1-0528``. The R1-Distill
models (``DeepSeek-R1-Distill-Qwen/Llama``) use their base models'
tokenizers and route to the Qwen3 / Llama-3 renderers, not this one.
"""
from __future__ import annotations
from renderers.base import Message
from renderers.configs import DeepSeekR1RendererConfig
from renderers.deepseek_v3 import DeepSeekV3Renderer
class DeepSeekR1Renderer(DeepSeekV3Renderer):
"""Deterministic message → token renderer for DeepSeek-R1 models."""
_config_cls: type = DeepSeekR1RendererConfig
_GEN_THINK_PREFILL: str = "<think>\n"
def _prepare_assistant_content(self, msg: Message) -> str:
"""Assistant content with the reasoning trace stripped, mirroring the
R1 template's ``content.split('</think>')[-1]`` on historical turns.
Structured ``thinking``/``text`` parts are reconstructed inline first
so the same ``</think>`` split applies. The separate
``reasoning_content`` field is ignored — the R1 chat template never
reads it, and history reasoning is dropped regardless.
"""
content = msg.get("content") or ""
if isinstance(content, list):
parts: list[str] = []
for p in content:
if not isinstance(p, dict):
continue
if p.get("type") == "thinking":
parts.append(f"<think>{p.get('thinking', '')}</think>")
elif p.get("type") == "text":
parts.append(p.get("text", ""))
content = "".join(parts)
if "</think>" in content:
content = content.split("</think>")[-1]
return content
+42 -32
View File
@@ -22,6 +22,7 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
trim_to_turn_close,
)
@@ -40,25 +41,30 @@ def _ds_token(name: str) -> str:
class DeepSeekV3Renderer:
"""Deterministic message → token renderer for DeepSeek V3 models.
"""Deterministic message → token renderer for DeepSeek-V3 models.
DeepSeek-V3's chat template does not consult any thinking-related
variable; the ``enable_thinking`` field on the typed config controls
the renderer's ``<think>\\n`` prefill at the generation prompt
(R1-distill convention) and is intentionally not forwarded to
``apply_chat_template`` upstream — that would be a no-op. The
template also always emits ``<think>{reasoning}</think>`` when
``reasoning_content`` is provided, so ``preserve_*`` flags are
no-ops here too; stored for protocol uniformity.
DeepSeek-V3 is non-reasoning: its chat template has no ``<think>``
concept — the generation prompt is a bare ``<|Assistant|>`` and past
assistant content is emitted verbatim. The reasoning variant
(``<think>``-prefilled prompt, history reasoning stripped) lives in
:class:`renderers.deepseek_r1.DeepSeekR1Renderer`, which subclasses
this one. ``preserve_*`` flags are no-ops here (no reasoning channel),
stored for protocol uniformity.
"""
#: Default typed config; the R1 subclass overrides this.
_config_cls: type = DeepSeekV3RendererConfig
#: Generation-prompt reasoning prefill. Empty for V3 (bare
#: ``<|Assistant|>``); the R1 subclass overrides to ``"<think>\n"``.
_GEN_THINK_PREFILL: str = ""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: DeepSeekV3RendererConfig | None = None,
):
self._tokenizer = tokenizer
self.config = config or DeepSeekV3RendererConfig()
self.config = config or type(self)._config_cls()
# ── BOS / EOS ────────────────────────────────────────────────
self._bos = self._get_special_token(f"begin{_US}of{_US}sentence")
@@ -238,8 +244,10 @@ class DeepSeekV3Renderer:
emit_special(
self._assistant_token, -1, is_sampled=False, is_content=False
)
if self.config.enable_thinking:
emit_text("<think>\n", -1, is_sampled=False, is_content=False)
if self._GEN_THINK_PREFILL:
emit_text(
self._GEN_THINK_PREFILL, -1, is_sampled=False, is_content=False
)
return RenderedTokens(
token_ids=tokens,
@@ -247,6 +255,7 @@ class DeepSeekV3Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -380,8 +389,8 @@ class DeepSeekV3Renderer:
last_role = new_messages[-1].get("role") if new_messages else None
if last_role != "tool":
emit_special(self._assistant_token, -1)
if self.config.enable_thinking:
emit_text("<think>\n", -1)
if self._GEN_THINK_PREFILL:
emit_text(self._GEN_THINK_PREFILL, -1)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
@@ -390,12 +399,30 @@ class DeepSeekV3Renderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
# ------------------------------------------------------------------
# Assistant rendering
# ------------------------------------------------------------------
def _prepare_assistant_content(self, msg: Message) -> str:
"""Assistant content as the V3 template would emit it: verbatim.
V3 is non-reasoning — its template emits ``message['content']`` as-is
and never reads ``reasoning_content``. A structured content list is
flattened to its ``text`` parts. The R1 subclass overrides this to
strip ``</think>`` from history.
"""
content = msg.get("content") or ""
if isinstance(content, list):
content = "".join(
p.get("text", "")
for p in content
if isinstance(p, dict) and p.get("type") == "text"
)
return content
def _render_assistant(
self,
msg: Message,
@@ -411,24 +438,7 @@ class DeepSeekV3Renderer:
# without a new <|Assistant|> token in that case.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
content = msg.get("content") or ""
# Support structured content (ThinkingPart / TextPart list).
if isinstance(content, list):
parts_text: list[str] = []
for p in content:
if not isinstance(p, dict):
continue
if p.get("type") == "thinking":
thinking = p.get("thinking", "")
parts_text.append(f"<think>{thinking}</think>")
elif p.get("type") == "text":
parts_text.append(p.get("text", ""))
content = "".join(parts_text)
# Also accept reasoning_content stored separately (OpenAI-style).
elif isinstance(msg.get("reasoning_content"), str) and msg["reasoning_content"]:
reasoning = msg["reasoning_content"]
content = f"<think>{reasoning}</think>{content}"
content = self._prepare_assistant_content(msg)
tool_calls = msg.get("tool_calls") or []
# ``<|Assistant|>`` is template-injected scaffolding — at
+2
View File
@@ -18,6 +18,7 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
extract_message_tool_names,
)
from renderers.configs import DefaultRendererConfig
from renderers.parsers import (
@@ -141,6 +142,7 @@ class DefaultRenderer:
token_ids=token_ids,
message_indices=message_indices,
message_roles=message_roles,
message_tool_names=extract_message_tool_names(messages),
)
def _apply(self, messages, *, tools=None, add_generation_prompt=False) -> list[int]:
+57 -15
View File
@@ -21,6 +21,7 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
)
@@ -184,6 +185,22 @@ class GLM45Renderer:
role = msg["role"]
content = self._visible_text(msg.get("content"))
# When the previous message is an assistant, this message's
# role-opening token (``<|user|>`` / ``<|observation|>``) is
# the inference-time stop signal that closes the assistant's
# turn (see ``get_stop_token_ids``). Mark it
# ``is_sampled=True`` so the loss-mask pipeline trains the
# model to emit it after ``</tool_call>`` (instead of
# continuing with another ``<tool_call>`` block). The token
# stays attributed to this message (msg_idx=i) and remains
# ``is_content=False`` — it's a role-marker / scaffold, not
# body bytes, so ``content_mask_for_roles({"tool"})`` and
# ``content_token_spans_by_role()`` correctly exclude it
# from "tool body" views. Byte stream is unchanged.
# ``system`` only appears at the start of a GLM conversation,
# so its opener is never the closer of an assistant turn.
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
if role == "system":
emit_special(self._system, i, is_sampled=False, is_content=False)
# ``\n`` is the scaffold separator after the role tag;
@@ -193,7 +210,12 @@ class GLM45Renderer:
)
elif role == "user":
emit_special(self._user, i, is_sampled=False, is_content=False)
emit_special(
self._user,
i,
is_sampled=closes_assistant_turn,
is_content=False,
)
# ``\n`` is scaffold; ``content`` is body; the optional
# ``/nothink`` suffix is scaffold the renderer injects
# when ``enable_thinking=False``.
@@ -244,6 +266,7 @@ class GLM45Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -362,6 +385,21 @@ class GLM45Renderer:
ext_sampled.append(is_sampled)
ext_content.append(is_content)
# The opener-token of the first new_message may also serve as
# the close of the previous assistant turn (when the model
# failed to sample the stop token itself and the bridge has to
# synthesize the boundary above). Unlike :meth:`render`, the
# bridge emits these with ``is_sampled=False, is_content=False``
# — they are template scaffolding for the *next* step's prompt,
# not tokens the model produced *in this* step. The RL loss
# operates on ``previous_completion_ids`` (what the model
# actually sampled this round); bridge tokens belong to the
# subsequent prompt and must not be counted as "model output"
# by downstream mask consumers. This deliberate disagreement
# with ``render()`` reflects the SFT vs RL semantics: render's
# masks describe what the model *should* produce given a
# complete conversation; bridge's masks describe what it
# *actually* produced this step.
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
@@ -409,6 +447,7 @@ class GLM45Renderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
@@ -531,21 +570,24 @@ class GLM45Renderer:
emit_text,
emit_text_segments,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False. The body bytes
# get ``is_content=True``; the ``\n<tool_response>\n`` /
# ``\n</tool_response>`` wraps and the ``<|observation|>`` role
# tag are scaffold so the SFT mask for tool body never trains
# the model to emit them. Single BPE pass over the joined text
# preserves boundary merges (the tool body's leading/trailing
# chars can merge with the wrap's ``\n``s if the tokenizer would
# do so; we route through ``emit_text_segments`` so the
# attribution is offset-driven and tokenizer-agnostic).
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
# Tool body bytes get ``is_content=True``; the wraps are
# scaffold. The ``<|observation|>`` role tag is scaffold too
# (``is_content=False`` so ``content_mask_for_roles({"tool"})``
# excludes it). When the previous message is an assistant it
# doubles as the inference stop signal for that assistant's
# turn — mark it ``is_sampled=True`` so SFT trains the model to
# emit it after ``</tool_call>``. The token stays attributed to
# this tool message; byte stream is unchanged.
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
closes_assistant_turn = prev_role == "assistant"
if not prev_is_tool:
emit_special(self._observation, msg_idx, is_sampled=False, is_content=False)
if prev_role != "tool":
emit_special(
self._observation,
msg_idx,
is_sampled=closes_assistant_turn,
is_content=False,
)
emit_text_segments(
[
+57 -10
View File
@@ -22,6 +22,7 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
)
@@ -207,12 +208,33 @@ class GLM5Renderer:
role = msg["role"]
content = self._visible_text(msg.get("content"))
# When the previous message is an assistant, this message's
# role-opening token (``<|user|>`` / ``<|observation|>``) is
# the inference-time stop signal that closes the assistant's
# turn (see ``get_stop_token_ids``). Mark it
# ``is_sampled=True`` so the loss-mask pipeline trains the
# model to emit it after ``</tool_call>`` (instead of
# continuing with another ``<tool_call>`` block). The token
# stays attributed to this message (msg_idx=i) and remains
# ``is_content=False`` — it's a role-marker / scaffold, not
# body bytes, so ``content_mask_for_roles({"tool"})`` and
# ``content_token_spans_by_role()`` correctly exclude it
# from "tool body" views. Byte stream is unchanged.
# ``system`` only appears at the start of a GLM conversation,
# so its opener is never the closer of an assistant turn.
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
if role == "system":
emit_special(self._system, i, is_sampled=False, is_content=False)
emit_text(content, i, is_sampled=False, is_content=True)
elif role == "user":
emit_special(self._user, i, is_sampled=False, is_content=False)
emit_special(
self._user,
i,
is_sampled=closes_assistant_turn,
is_content=False,
)
emit_text(content, i, is_sampled=False, is_content=True)
elif role == "assistant":
@@ -260,6 +282,7 @@ class GLM5Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -382,6 +405,21 @@ class GLM5Renderer:
ext_sampled.append(is_sampled)
ext_content.append(is_content)
# The opener-token of the first new_message may also serve as
# the close of the previous assistant turn (when the model
# failed to sample the stop token itself and the bridge has to
# synthesize the boundary above). Unlike :meth:`render`, the
# bridge emits these with ``is_sampled=False, is_content=False``
# — they are template scaffolding for the *next* step's prompt,
# not tokens the model produced *in this* step. The RL loss
# operates on ``previous_completion_ids`` (what the model
# actually sampled this round); bridge tokens belong to the
# subsequent prompt and must not be counted as "model output"
# by downstream mask consumers. This deliberate disagreement
# with ``render()`` reflects the SFT vs RL semantics: render's
# masks describe what the model *should* produce given a
# complete conversation; bridge's masks describe what it
# *actually* produced this step.
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
@@ -420,6 +458,7 @@ class GLM5Renderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
@@ -566,16 +605,24 @@ class GLM5Renderer:
emit_text,
emit_text_segments,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False. The tool body
# bytes get ``is_content=True``; the ``<|observation|>`` /
# ``<tool_response>`` wraps are scaffold so the SFT mask for
# tool body never trains the model to emit them.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
# Tool body bytes get ``is_content=True``; the wraps are
# scaffold. The ``<|observation|>`` role tag is scaffold too
# (``is_content=False`` so ``content_mask_for_roles({"tool"})``
# excludes it). When the previous message is an assistant it
# doubles as the inference stop signal for that assistant's
# turn — mark it ``is_sampled=True`` so SFT trains the model to
# emit it after ``</tool_call>``. The token stays attributed to
# this tool message; byte stream is unchanged.
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
closes_assistant_turn = prev_role == "assistant"
if not prev_is_tool:
emit_special(self._observation, msg_idx, is_sampled=False, is_content=False)
if prev_role != "tool":
emit_special(
self._observation,
msg_idx,
is_sampled=closes_assistant_turn,
is_content=False,
)
emit_special(
self._tool_response_tok, msg_idx, is_sampled=False, is_content=False
+3
View File
@@ -56,6 +56,7 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
@@ -465,6 +466,7 @@ class GptOssRenderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -594,6 +596,7 @@ class GptOssRenderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
# ── message conversion ───────────────────────────────────────────────────
+3
View File
@@ -23,6 +23,7 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
extract_message_tool_names,
reject_assistant_in_extension,
trim_to_turn_close,
)
@@ -305,6 +306,7 @@ class KimiK2Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in caller_messages],
message_tool_names=extract_message_tool_names(caller_messages),
)
def render_ids(
@@ -454,6 +456,7 @@ class KimiK2Renderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
+20 -3
View File
@@ -36,12 +36,13 @@ from renderers.base import (
RenderedTokens,
ToolCallParseStatus,
ToolSpec,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import KimiK25RendererConfig
from renderers.parsing import parse_kimi_k2_section
from renderers.parsing import _reasoning_end_token_index, parse_kimi_k2_section
from renderers.qwen3_vl import (
_image_hash,
_is_image_part,
@@ -451,6 +452,13 @@ def _parse_kimi_k2_response(
ids = ids[:i]
break
# Reasoning first: a tool-call section the model drafts *inside* its
# <think> trace must not be parsed as a real call (regression #78 — cf.
# parse_qwen3). K2.5 renders </think> as text, so locate the boundary by
# decoding; the section scan then starts past it. content_ids still begins
# at 0, so the </think> text-split below recovers reasoning unchanged.
reasoning_end = _reasoning_end_token_index(tokenizer, ids)
# Token-ID path — produces spans. Only run if every relevant special
# token resolved at init (i.e. is in the tokenizer's vocab).
tool_calls: list[ParsedToolCall] = []
@@ -470,6 +478,7 @@ def _parse_kimi_k2_response(
tool_call_begin_id=tool_call_begin_id,
tool_call_argument_begin_id=tool_call_argument_begin_id,
tool_call_end_id=tool_call_end_id,
scan_start=reasoning_end,
)
text = (
tokenizer.decode(content_ids, skip_special_tokens=False)
@@ -480,9 +489,13 @@ def _parse_kimi_k2_response(
text = tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
# Fallback path: model emitted literal-text section delimiters (singular
# variant) rather than special tokens. Spans unavailable here.
# variant) rather than special tokens. Spans unavailable here. Start the
# search past the first </think> so a literal section drafted inside the
# reasoning trace isn't matched as a real call (regression #78).
if not tool_calls:
tc_match = _TOOL_CALLS_SECTION_RE.search(text)
think_close = text.find("</think>")
search_from = think_close + len("</think>") if think_close != -1 else 0
tc_match = _TOOL_CALLS_SECTION_RE.search(text, search_from)
if tc_match:
text = text[: tc_match.start()]
tool_section = (
@@ -946,6 +959,7 @@ class KimiK25Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
multi_modal_data=mm_data,
)
@@ -1188,6 +1202,7 @@ class KimiK25Renderer:
merged_items.setdefault(modality, []).extend(vals)
bridge_roles = [m.get("role") or "" for m in new_messages]
bridge_tool_names = extract_message_tool_names(new_messages)
if not (merged_hashes or merged_placeholders or merged_items):
return RenderedTokens(
token_ids=tokens,
@@ -1195,6 +1210,7 @@ class KimiK25Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
)
mm_data = MultiModalData(
@@ -1208,6 +1224,7 @@ class KimiK25Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
multi_modal_data=mm_data,
)
+3
View File
@@ -36,6 +36,7 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
)
from renderers.configs import LagunaXS2RendererConfig
@@ -275,6 +276,7 @@ class LagunaXS2Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -426,6 +428,7 @@ class LagunaXS2Renderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
+516
View File
@@ -0,0 +1,516 @@
"""Llama-3 Renderer — hard-coded Python mirroring Meta's Llama-3 chat template.
Initial scope: Llama-3.2-1B-Instruct and Llama-3.2-3B-Instruct (and the
unrestricted ``unsloth/Llama-3.2-{1B,3B}-Instruct`` mirror, which ships a
byte-identical chat template). Other Llama-3.x sizes ship slightly
different templates and are NOT covered by this renderer until parity is
verified.
Notable differences from the Qwen / GLM family renderers:
* No ``<think>`` / reasoning channel — Llama-3 doesn't ship a
reasoning-content concept, so ``preserve_*_thinking`` flags don't
apply.
* ``<|begin_of_text|>`` (BOS) is emitted at the very start of every
render. The chat template never omits it.
* The system block is emitted **unconditionally** with a fixed
``Cutting Knowledge Date: December 2023\\nToday Date: <date>\\n\\n``
preamble — even when no system message is supplied. Empty system
message → block ends with ``\\n\\n<|eot_id|>``.
* Tools default to "first-user-message" mode (matching the chat
template's default ``tools_in_user_message=True``): tool descriptions
+ JSON signatures are injected into the first user message rather
than the system block. Set ``Llama3RendererConfig.tools_in_user_message
= False`` to flip to system-block mode.
* ``Llama3RendererConfig.date_string`` is pinned at ``"26 Jul 2024"`` by
default to match the chat template's ``strftime`` fallback (and keep
output deterministic). Override per instance for production runs that
want today's date.
* Tool calls: a single ``{"name": "...", "parameters": ...}`` JSON blob
inside the assistant body. The chat template explicitly raises if
``message.tool_calls | length != 1``; this renderer matches that.
* Tool responses: rendered with role ``ipython`` regardless of whether
the source message used ``role: "tool"`` or ``role: "ipython"``. The
chat template runs ``content | tojson`` on any mapping/iterable
content — and Jinja considers strings iterable, so plain string
contents get JSON-quoted. We mirror that exactly.
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.configs import Llama3RendererConfig
from renderers.parsing import parse_llama_3
# ---------------------------------------------------------------------------
# Constants — must match the Jinja chat template's literal strings exactly.
# ---------------------------------------------------------------------------
_CUTTING_KNOWLEDGE_DATE = "December 2023"
# Tools-in-system intro: emitted into the system block when tools is set
# AND tools_in_user_message=False. Note: the chat template puts these
# three string literals back-to-back with NO newline between the second
# and third, so there's no space before "Do not use variables.".
_TOOLS_IN_SYSTEM_INTRO = (
"You have access to the following functions. To call a function, "
"please respond with JSON for a function call."
'Respond in the format {"name": function name, "parameters": '
"dictionary of argument name and its value}."
"Do not use variables.\n\n"
)
# Tools-in-user intro: emitted into the first user message when tools is
# set AND tools_in_user_message=True (the default).
_TOOLS_IN_USER_INTRO = (
"Given the following functions, please respond with a JSON for a "
"function call with its proper arguments that best answers the given "
"prompt.\n\n"
'Respond in the format {"name": function name, "parameters": '
"dictionary of argument name and its value}."
"Do not use variables.\n\n"
)
class Llama3Renderer:
"""Deterministic message → token renderer for Llama-3.x Instruct models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: Llama3RendererConfig | None = None,
):
# ``preserve_*_thinking`` are accepted but no-ops: Llama-3 ships no
# reasoning_content channel, so there's never any past-assistant
# thinking to retain or drop. The flags are stored on ``self.config``
# for cross-renderer uniformity but never change the token stream —
# the same contract as Kimi-K2 / Qwen3-VL (see the never-preserves
# renderers in tests/test_preserve_thinking.py).
self._tokenizer = tokenizer
self.config = config or Llama3RendererConfig()
self._bos = self._token_id("<|begin_of_text|>")
self._start_header = self._token_id("<|start_header_id|>")
self._end_header = self._token_id("<|end_header_id|>")
self._eot = self._token_id("<|eot_id|>")
self._end_of_text = self._token_id("<|end_of_text|>")
# ``<|eom_id|>`` shows up in some Llama-3 tool-calling traces (the
# "ipython" / python-tag flow) but the standard 3.2 chat template
# closes turns with ``<|eot_id|>``. We still treat eom as a stop
# token so models that emit it terminate cleanly.
self._eom = self._token_id("<|eom_id|>")
def _token_id(self, token: str) -> int:
tid = self._tokenizer.convert_tokens_to_ids(token)
assert isinstance(tid, int) and tid != self._tokenizer.unk_token_id, (
f"Special token {token!r} not found in tokenizer vocabulary"
)
return tid
def _encode(self, text: str) -> list[int]:
if not text:
return []
return self._tokenizer.encode(text, add_special_tokens=False)
@staticmethod
def _content_str(content: Any) -> str:
"""Render content to a plain string. Handles ``str``, list-of-text-parts,
and ``None``. Matches the chat template's ``message.content | trim``
callers, which expect a string in."""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict) and "text" in item:
parts.append(item["text"])
else:
raise ValueError(f"Unexpected content item: {item}")
return "".join(parts)
raise TypeError(f"Unexpected content type: {type(content)}")
@staticmethod
def _tool_response_str(content: Any) -> str:
"""Mirror the chat template's tool-response branch:
``{% if message.content is mapping or message.content is iterable %}
{{ message.content | tojson }} {% else %} {{ message.content }}``.
In Jinja, **strings are iterable** — so plain-string tool contents
also go through ``tojson`` (i.e. ``json.dumps``), wrapping them in
quotes and escaping. Non-iterable scalars (numbers, bools, None)
fall through to literal stringification.
"""
if content is None:
return ""
if isinstance(content, (dict, list, str)):
return json.dumps(content, ensure_ascii=False)
return str(content)
# ------------------------------------------------------------------
# render
# ------------------------------------------------------------------
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> RenderedTokens:
if not messages:
raise ValueError("No messages provided.")
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
"""Tokenize concatenated wrap + body as one BPE pass; per-token
``is_content`` follows each token's source segment. Lets the
scaffold/body split stay attributed without splitting the
encode call (which could shift BPE merges at the boundary)."""
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
# ── 0. BOS ──────────────────────────────────────────────────
emit_special(self._bos, -1, is_sampled=False, is_content=False)
# ── 1. System block (always emitted) ────────────────────────
first_is_system = messages[0].get("role") == "system"
sys_idx = 0 if first_is_system else -1
sys_text = (
self._content_str(messages[0].get("content")).strip()
if first_is_system
else ""
)
emit_special(self._start_header, sys_idx, is_sampled=False, is_content=False)
emit_text("system", sys_idx, is_sampled=False, is_content=False)
emit_special(self._end_header, sys_idx, is_sampled=False, is_content=False)
# The Cutting Knowledge / Today Date preamble (and any tools-in-system
# block) is template scaffold; only the caller's system content is
# body. Route both through one BPE pass so the wrap/body boundary
# can't shift merges.
preamble = "\n\n"
if tools is not None:
preamble += "Environment: ipython\n"
preamble += f"Cutting Knowledge Date: {_CUTTING_KNOWLEDGE_DATE}\n"
preamble += f"Today Date: {self.config.date_string}\n\n"
if tools is not None and not self.config.tools_in_user_message:
preamble += _TOOLS_IN_SYSTEM_INTRO
for t in tools:
preamble += json.dumps(t, indent=4, ensure_ascii=False) + "\n\n"
sys_segments: list[tuple[str, bool]] = [(preamble, False)]
if sys_text:
sys_segments.append((sys_text, True))
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
emit_special(self._eot, sys_idx, is_sampled=False, is_content=False)
# ── 2. Body messages ────────────────────────────────────────
body_messages = messages[1:] if first_is_system else messages
offset = 1 if first_is_system else 0
i = 0
# 2a. tools_in_user_message mode pulls the first user message
# into a special block with the tools description prepended.
if tools is not None and self.config.tools_in_user_message:
if i >= len(body_messages):
raise ValueError(
"Cannot place tools in the first user message — no user "
"message was provided."
)
first_user = body_messages[i]
if first_user.get("role") != "user":
raise ValueError(
"tools_in_user_message=True requires the first non-system "
f"message to be 'user'; got {first_user.get('role')!r}."
)
user_idx = i + offset
emit_special(
self._start_header, user_idx, is_sampled=False, is_content=False
)
emit_text("user", user_idx, is_sampled=False, is_content=False)
emit_special(self._end_header, user_idx, is_sampled=False, is_content=False)
user_preamble = "\n\n" + _TOOLS_IN_USER_INTRO
for t in tools:
user_preamble += json.dumps(t, indent=4, ensure_ascii=False) + "\n\n"
user_content = self._content_str(first_user.get("content")).strip()
user_segments: list[tuple[str, bool]] = [(user_preamble, False)]
if user_content:
user_segments.append((user_content, True))
emit_text_segments(user_segments, user_idx, is_sampled=False)
emit_special(self._eot, user_idx, is_sampled=False, is_content=False)
i += 1
# 2b. Remaining messages — plain user/assistant/tool/assistant-with-tool-calls.
for j in range(i, len(body_messages)):
msg = body_messages[j]
msg_idx = j + offset
role = msg.get("role")
tool_calls = msg.get("tool_calls")
if role in ("tool", "ipython"):
# Tool responses are conversation history the model never
# samples; the response body is caller content, the wrap is
# scaffold.
emit_special(
self._start_header, msg_idx, is_sampled=False, is_content=False
)
emit_text("ipython", msg_idx, is_sampled=False, is_content=False)
emit_special(
self._end_header, msg_idx, is_sampled=False, is_content=False
)
tool_body = self._tool_response_str(msg.get("content"))
tool_segments: list[tuple[str, bool]] = [("\n\n", False)]
if tool_body:
tool_segments.append((tool_body, True))
emit_text_segments(tool_segments, msg_idx, is_sampled=False)
emit_special(self._eot, msg_idx, is_sampled=False, is_content=False)
elif tool_calls:
if len(tool_calls) != 1:
raise ValueError(
"Llama-3 chat template only supports a single tool call "
"per assistant message."
)
tc = tool_calls[0]
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
if isinstance(arguments, str):
args_str = arguments
else:
args_str = json.dumps(arguments, ensure_ascii=False)
emit_special(
self._start_header, msg_idx, is_sampled=False, is_content=False
)
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
emit_special(
self._end_header, msg_idx, is_sampled=False, is_content=False
)
# The ``\n\n`` after the header is gen-prompt scaffold the
# model never samples; the JSON tool-call body and the
# closing ``<|eot_id|>`` are the model's sampled emission.
emit_text("\n\n", msg_idx, is_sampled=False, is_content=False)
emit_text(
'{"name": "' + name + '", "parameters": ' + args_str + "}",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._eot, msg_idx, is_sampled=True, is_content=True)
elif role == "assistant":
content = self._content_str(msg.get("content")).strip()
emit_special(
self._start_header, msg_idx, is_sampled=False, is_content=False
)
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
emit_special(
self._end_header, msg_idx, is_sampled=False, is_content=False
)
# ``\n\n`` separator is scaffold (it's the generation prompt);
# the body and the closing ``<|eot_id|>`` are model-sampled.
emit_text("\n\n", msg_idx, is_sampled=False, is_content=False)
if content:
emit_text(content, msg_idx, is_sampled=True, is_content=True)
emit_special(self._eot, msg_idx, is_sampled=True, is_content=True)
else:
# user / non-leading system: caller content, never sampled.
content = self._content_str(msg.get("content")).strip()
emit_special(
self._start_header, msg_idx, is_sampled=False, is_content=False
)
emit_text(role or "", msg_idx, is_sampled=False, is_content=False)
emit_special(
self._end_header, msg_idx, is_sampled=False, is_content=False
)
segments: list[tuple[str, bool]] = [("\n\n", False)]
if content:
segments.append((content, True))
emit_text_segments(segments, msg_idx, is_sampled=False)
emit_special(self._eot, msg_idx, is_sampled=False, is_content=False)
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._start_header, -1, is_sampled=False, is_content=False)
emit_text("assistant", -1, is_sampled=False, is_content=False)
emit_special(self._end_header, -1, is_sampled=False, is_content=False)
emit_text("\n\n", -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> list[int]:
return self.render(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
return parse_llama_3(
self._tokenizer,
token_ids,
stop_ids={self._eot, self._end_of_text, self._eom},
)
def get_stop_token_ids(self) -> list[int]:
return [self._eot, self._end_of_text, self._eom]
# ------------------------------------------------------------------
# bridge_to_next_turn
# ------------------------------------------------------------------
def bridge_to_next_turn(
self,
previous_prompt_ids: list[int],
previous_completion_ids: list[int],
new_messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
) -> RenderedTokens | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._eot, self._end_of_text, self._eom},
synthesize_close=self._eot,
)
if previous_ids is None:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_content: list[bool] = []
# Every token the bridge emits is template scaffolding for the next
# prompt — none of it is model-sampled — so ``sampled_mask`` is
# uniformly ``False`` (applied over the whole sequence at return).
# ``is_content`` follows the same rules as :meth:`render` so a
# consumer can walk the trajectory and read each step's body mask.
def emit_special(token_id: int, msg_idx: int = -1) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_content.append(False)
def emit_text(text: str, msg_idx: int = -1) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_content.extend([False] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int = -1
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_content.append(is_content)
for i, msg in enumerate(new_messages):
role = msg.get("role")
if role in ("system", "user"):
content = self._content_str(msg.get("content")).strip()
emit_special(self._start_header, i)
emit_text(role, i)
emit_special(self._end_header, i)
segs: list[tuple[str, bool]] = [("\n\n", False)]
if content:
segs.append((content, True))
emit_text_segments(segs, i)
emit_special(self._eot, i)
elif role in ("tool", "ipython"):
tool_body = self._tool_response_str(msg.get("content"))
emit_special(self._start_header, i)
emit_text("ipython", i)
emit_special(self._end_header, i)
tool_segs: list[tuple[str, bool]] = [("\n\n", False)]
if tool_body:
tool_segs.append((tool_body, True))
emit_text_segments(tool_segs, i)
emit_special(self._eot, i)
else:
return None
# Generation prompt — matches the gen-prompt branch of ``render()``.
emit_special(self._start_header, -1)
emit_text("assistant", -1)
emit_special(self._end_header, -1)
emit_text("\n\n", -1)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
+3
View File
@@ -22,6 +22,7 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
@@ -278,6 +279,7 @@ class MiniMaxM2Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -459,6 +461,7 @@ class MiniMaxM2Renderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
+215 -148
View File
@@ -25,11 +25,12 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import Nemotron3RendererConfig
from renderers.configs import Nemotron3RendererConfig, Nemotron3UltraRendererConfig
from renderers.parsing import parse_qwen35
# ---------------------------------------------------------------------------
@@ -74,16 +75,64 @@ def _render_extra_keys(obj: dict[str, Any], handled_keys: set[str]) -> list[str]
return lines
# The Nemotron-3 family ships two chat-template variants. Nano / Super share
# one (renderer ``Nemotron3Renderer`` / config ``name="nemotron-3"``); Ultra
# differs in the reasoning-block glue — no ``\n`` around ``</think>`` — and is
# the ``Nemotron3UltraRenderer`` subclass (``name="nemotron-3-ultra"``). Which
# variant a checkpoint uses is carried by ``MODEL_RENDERER_MAP``, so the right
# renderer class is constructed and the variant is encoded by the class itself.
def _is_super(tokenizer) -> bool:
"""Does this checkpoint use the **Super** flavour of the shared Nano/Super
template — i.e. the one whose Jinja defines the ``low_effort`` kwarg?
Nano and Super share one config (``nemotron-3``), so the model name is the
only signal that separates them. Detected by substring; unknown / fine-tuned
checkpoints default to ``False`` so ``low_effort`` is a no-op there —
matching how the Nano template silently ignores it.
"""
return "super" in (getattr(tokenizer, "name_or_path", "") or "").lower()
class Nemotron3Renderer:
"""Deterministic message → token renderer for Nemotron 3 models."""
"""Deterministic message → token renderer for Nemotron-3 Nano / Super.
The Ultra variant (distinct ``</think>`` glue) is the
:class:`Nemotron3UltraRenderer` subclass below; both are registered under
their own discriminator and differ only by the class-level hooks here.
"""
# Variant hooks (overridden by ``Nemotron3UltraRenderer``): the default
# config to build when none is passed, and whether to use Ultra's
# reasoning-block glue.
_config_cls: type = Nemotron3RendererConfig
_ultra: bool = False
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: Nemotron3RendererConfig | None = None,
config: Nemotron3RendererConfig | Nemotron3UltraRendererConfig | None = None,
):
self._tokenizer = tokenizer
self.config = config or Nemotron3RendererConfig()
cfg = config or type(self)._config_cls()
self.config = cfg
# Resolve the per-variant reasoning-effort hint appended to the last
# user message. Ultra honours ``medium_effort``; Super honours
# ``low_effort``; Nano honours neither. The non-matching kwarg is
# silently ignored (empty hint), exactly as ``apply_chat_template``
# ignores a template variable the variant's Jinja never defines.
if self._ultra:
self._effort_hint = (
"\n\n{reasoning effort: efficient}"
if getattr(cfg, "medium_effort", False)
else ""
)
elif getattr(cfg, "low_effort", False) and _is_super(tokenizer):
self._effort_hint = "\n\n{reasoning effort: low}"
else:
self._effort_hint = ""
# Look up special token IDs from the tokenizer (not hardcoded).
# <|endoftext|> is optional: Nemotron-3 Nano / Super tokenizers ship
@@ -284,9 +333,12 @@ class Nemotron3Renderer:
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
# Build system content: user's system text first, then tools
# Build system content: user's system text first, then tools.
# The template emits ``system_message`` verbatim (no trim) and
# gates the ``\n\n`` separator on its raw length, so keep the
# caller's content unstripped.
if first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
sys_content = self._render_content(messages[0].get("content"))
else:
sys_content = ""
@@ -314,7 +366,7 @@ class Nemotron3Renderer:
elif first_is_system:
sys_idx = orig_idx(0)
sys_content = self._render_content(messages[0].get("content")).strip()
sys_content = self._render_content(messages[0].get("content"))
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
sys_segments2: list[tuple[str, bool]] = [("system\n", False)]
if sys_content:
@@ -323,21 +375,26 @@ class Nemotron3Renderer:
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
# Track the most-recent plain (non-tool-call) assistant so we can
# preserve its reasoning while stripping reasoning from earlier
# assistants — the Nemotron-3 template matches this pattern.
last_plain_assistant_idx = -1
# All Nemotron-3 variants (Nano / Super / Ultra) truncate historical
# thinking on every assistant turn *before the last user message* —
# the template rule ``truncate_history_thinking and loop.index0 <
# last_user_idx`` is byte-identical across the three chat templates.
# Compute the last-user index over the normalized ``messages`` list (a
# leading system never holds a user, so the relative comparison is
# unaffected).
last_user_idx_norm = -1
for j in range(len(messages) - 1, -1, -1):
if messages[j].get("role") == "assistant" and not messages[j].get(
"tool_calls"
):
last_plain_assistant_idx = j
if messages[j].get("role") == "user":
last_user_idx_norm = j
break
# ── 2. Iterate messages ─────────────────────────────────────
for i, msg in enumerate(messages):
role = msg["role"]
content = self._render_content(msg.get("content")).strip()
# Keep content unstripped: the template emits user / system / tool
# content verbatim, and assistant trimming happens inside
# ``_assistant_body`` exactly where the template applies it.
content = self._render_content(msg.get("content"))
msg_orig_idx = orig_idx(i)
if role == "system":
@@ -352,6 +409,12 @@ class Nemotron3Renderer:
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if content:
user_segments.append((content, True))
# Reasoning-effort hint rides on the LAST user message only,
# glued to the content so BPE sees them as one chunk (matching
# the template's ``content + '\n\n{reasoning effort: …}'``). It
# is template scaffold, not caller content → is_content=False.
if self._effort_hint and i == last_user_idx_norm:
user_segments.append((self._effort_hint, False))
emit_text_segments(user_segments, msg_orig_idx, is_sampled=False)
emit_special(
self._im_end, msg_orig_idx, is_sampled=False, is_content=False
@@ -359,23 +422,29 @@ class Nemotron3Renderer:
emit_text("\n", msg_orig_idx, is_sampled=False, is_content=False)
elif role == "assistant":
is_last_turn = i >= last_plain_assistant_idx
# Template: ``include_content = not (truncate_history_thinking
# and loop.index0 < last_user_idx)``. The renderer-internal
# preserve_* overrides only ever *extend* retention, so OR them
# in (a preserved turn keeps its thinking even when the
# template default would drop it).
preserve_thinking = msg_orig_idx >= 0 and should_preserve_past_thinking(
original_messages,
msg_orig_idx,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
include_content = (
not self.config.truncate_history_thinking
or i >= last_user_idx_norm
or preserve_thinking
)
self._render_assistant(
msg,
msg_orig_idx,
content,
is_last_turn=is_last_turn,
preserve_thinking=preserve_thinking,
include_content=include_content,
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
@@ -411,6 +480,7 @@ class Nemotron3Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in original_messages],
message_tool_names=extract_message_tool_names(original_messages),
)
def render_ids(
@@ -464,6 +534,11 @@ class Nemotron3Renderer:
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
# An active effort hint rides on the *last* user message. Appending
# a new turn can move which user is last, which would strand the
# hint on the frozen previous prompt — the append-only bridge can't
# rewrite it. Bail so the caller does a full, correct re-render.
or self._effort_hint
):
return None
@@ -533,7 +608,9 @@ class Nemotron3Renderer:
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._render_content(msg.get("content")).strip()
# Unstripped — the template emits user / system / tool content
# verbatim (see :meth:`render`).
content = self._render_content(msg.get("content"))
if role == "user":
emit_special(self._im_start, i)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
@@ -581,6 +658,7 @@ class Nemotron3Renderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
# ------------------------------------------------------------------
@@ -593,28 +671,10 @@ class Nemotron3Renderer:
msg_idx: int,
content: str,
*,
is_last_turn: bool,
preserve_thinking: bool = False,
include_content: bool,
emit_special,
emit_text,
emit_ids,
emit_text_segments,
) -> None:
# Extract reasoning_content
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
before_think_end, after_think_end = content.split("</think>", 1)
if "<think>" in before_think_end:
reasoning_content = before_think_end.split("<think>")[-1].lstrip("\n")
else:
reasoning_content = before_think_end.lstrip("\n")
reasoning_content = reasoning_content.rstrip("\n")
content = after_think_end.lstrip("\n")
reasoning_content = reasoning_content.strip()
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
# at inference the chat template emits these as the generation
# prompt and the model never samples them. Marking the role tag
@@ -624,116 +684,109 @@ class Nemotron3Renderer:
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
# Nemotron 3 keeps reasoning on the most-recent plain assistant but
# strips it from historical turns, which collapse to an empty
# <think></think> block. Empty <think></think> is also emitted when
# the turn has no reasoning at all. The trailing ``\n`` (when
# tool_calls follow) is glued to ``content`` in a single emit_text
# so BPE sees ``content\n`` as one chunk, matching how
# apply_chat_template tokenises the concatenated template string.
tool_calls = msg.get("tool_calls") or []
# A \n is always required between the text/think block and the first
# <tool_call>, whether the content is empty or not.
content_suffix = "\n" if tool_calls else ""
if reasoning_content and (
is_last_turn
or preserve_thinking
or not self.config.truncate_history_thinking
):
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
emit_text(
"\n" + reasoning_content + "\n",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
# Single \n separator (not \n\n like Qwen3.5)
emit_text(
"\n" + content + content_suffix,
msg_idx,
is_sampled=True,
is_content=True,
)
elif reasoning_content:
# Historical assistant whose reasoning got stripped — template
# keeps a single \n between the collapsed <think></think> and
# the content as a marker that reasoning existed.
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
emit_text(
"\n" + content + content_suffix,
msg_idx,
is_sampled=True,
is_content=True,
)
else:
# No reasoning ever — <think></think> glued directly to content.
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
emit_text(
content + content_suffix,
msg_idx,
is_sampled=True,
is_content=True,
)
# Tool calls (leading \n was glued to the content above; each
# iteration's trailing \n after </tool_call> handles the
# separator to the next block).
if tool_calls:
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
emit_text(
"\n<function=" + name + ">\n",
msg_idx,
is_sampled=True,
is_content=True,
)
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
if isinstance(arg_value, (dict, list)):
value_str = json.dumps(arg_value, ensure_ascii=False)
else:
value_str = str(arg_value)
emit_text(
"<parameter="
+ arg_name
+ ">\n"
+ value_str
+ "\n</parameter>\n",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_text("</function>\n", msg_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
)
# Trailing \n after </tool_call> (Nemotron 3 specific)
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
# Build the body (everything between ``assistant\n`` and ``<|im_end|>``)
# as a single string mirroring the chat template's own string algebra,
# then tokenise it in one pass. The ``<think>`` / ``</think>`` /
# ``<tool_call>`` / ``</tool_call>`` markers are added tokens, so the
# tokenizer isolates them — encoding the assembled body yields the same
# ids as ``apply_chat_template`` (which likewise encodes a rendered
# string). The whole body is sampled content; ``<|im_end|>`` is the
# model's stop signal (sampled), and the inter-turn ``\n`` is not.
body = self._assistant_body(msg, content, include_content=include_content)
if body:
emit_text(body, msg_idx, is_sampled=True, is_content=True)
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
def _assistant_body(
self, msg: Message, raw_content: str, *, include_content: bool
) -> str:
"""Assemble the assistant body string exactly as the chat template.
``include_content`` is the template's ``not (truncate_history_thinking
and loop.index0 < last_user_idx)`` (already OR-ed with the preserve_*
overrides by the caller): ``True`` keeps the full think+content block,
``False`` collapses historical thinking to an empty ``<think></think>``.
"""
ultra = self._ultra
# 1. Assemble ``content`` — wrap a ``reasoning_content`` field in
# <think> tags (raw, not stripped: interior whitespace is part of
# the reasoning), else prepend an empty <think></think> only when
# the content carries no inline think tags of its own (which are
# passed through verbatim, like the template).
reasoning = msg.get("reasoning_content")
if isinstance(reasoning, str) and reasoning.strip():
if ultra:
content = "<think>\n" + reasoning + "</think>" + raw_content
else:
content = "<think>\n" + reasoning + "\n</think>\n" + raw_content
else:
content = raw_content
if "<think>" not in content and "</think>" not in content:
content = "<think></think>" + content
tool_calls = msg.get("tool_calls") or []
if tool_calls:
parts: list[str] = []
if content.strip():
if include_content:
parts.append(content.strip() + "\n")
else:
# Drop historical thinking: keep only what follows the last
# </think> (or precedes a dangling <think>), then re-stamp
# an empty block. Nano/Super trim the remainder; Ultra glues
# it raw (its template omits the trailing ``| trim``).
c = content
if "</think>" in c:
c = c.split("</think>")[-1]
elif "<think>" in c:
c = c.split("<think>")[0]
c = "<think></think>" + (c if ultra else c.strip())
if c:
parts.append(c + "\n")
else:
# Non-string / empty content: bare collapsed think block, no \n.
parts.append("<think></think>")
for tc in tool_calls:
parts.append(self._format_tool_call(tc))
return "".join(parts)
# No tool calls.
if include_content:
return content.strip()
c = content
if "<think>" in c and "</think>" in c:
c = "<think></think>" + c.split("</think>")[-1]
return c.strip()
@staticmethod
def _format_tool_call(tc: dict[str, Any]) -> str:
"""Render one tool call as ``<tool_call>…</tool_call>\\n`` XML."""
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
parts = ["<tool_call>\n<function=" + name + ">\n"]
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
if isinstance(arg_value, (dict, list)):
value_str = json.dumps(arg_value, ensure_ascii=False)
else:
value_str = str(arg_value)
parts.append(
"<parameter=" + arg_name + ">\n" + value_str + "\n</parameter>\n"
)
parts.append("</function>\n</tool_call>\n")
return "".join(parts)
# ------------------------------------------------------------------
# Tool message rendering
# ------------------------------------------------------------------
@@ -778,3 +831,17 @@ class Nemotron3Renderer:
if not next_is_tool:
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
emit_text("\n", oi, is_sampled=False, is_content=False)
class Nemotron3UltraRenderer(Nemotron3Renderer):
"""Renderer for Nemotron-3 **Ultra**.
Identical to :class:`Nemotron3Renderer` except the reasoning block is glued
as ``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around
``</think>``) and truncated historical turns collapse to
``<think></think>{content}`` (no ``\\n``) — the difference is carried by the
``_ultra`` class hook. Honours the Ultra-only ``medium_effort`` kwarg.
"""
_config_cls = Nemotron3UltraRendererConfig
_ultra = True
+134 -3
View File
@@ -133,6 +133,39 @@ def _decode(tokenizer, ids: list[int]) -> str:
return tokenizer.decode(ids, skip_special_tokens=False)
def _reasoning_end_token_index(
tokenizer, ids: list[int], marker: str = "</think>"
) -> int:
"""Token index immediately past the first ``</think>`` in ``ids``.
Returns 0 when ``ids`` has no closed reasoning region — callers treat
that as "scan from the start" (preserves pre-existing behavior for
non-thinking / truncated-reasoning completions).
Used by parsers whose ``</think>`` is *not* a single special token
(DeepSeek-V3, Kimi-K2.5) — where it tokenizes to several pieces and is
context-sensitive (the closing ``>`` merges differently depending on the
next char), so a token-id or fixed-subsequence search isn't reliable. We
instead locate the boundary in decoded text via binary search over prefix
decodes, which holds as long as ``decode(ids[:k])`` is prefix-stable in
``k`` (true for the byte-level BPE tokenizers here; ``</think>`` is clean
ASCII that won't straddle a byte boundary). Single-token ``</think>``
parsers (Qwen3) anchor on the token id directly and don't need this.
"""
if not ids or marker not in _decode(tokenizer, ids):
return 0
# Smallest prefix length (in tokens) whose decode already contains the
# full marker — i.e. the index just past where </think> completes.
lo, hi = 1, len(ids)
while lo < hi:
mid = (lo + hi) // 2
if marker in _decode(tokenizer, ids[:mid]):
hi = mid
else:
lo = mid + 1
return lo
# ── Qwen3: <tool_call> JSON </tool_call> ────────────────────────────
@@ -143,11 +176,26 @@ def parse_qwen3(
stop_ids: set[int],
tool_call_id: int,
tool_call_end_id: int,
reasoning_end_id: int | None = None,
) -> ParsedResponse:
"""Parse Qwen3 completion tokens. Hermes-style JSON tool calls."""
ids = _strip_stop_tokens(token_ids, stop_ids)
tc_start = _find(ids, tool_call_id)
# Reasoning is resolved before tool calls. Thinking models (e.g.
# Qwen3-*-Thinking) routinely draft ``<tool_call>`` blocks *inside* their
# ``<think>...</think>`` trace while planning; those are reasoning, not
# real invocations. Anchoring the tool-call scan after the ``</think>``
# boundary keeps in-think drafts out of ``tool_calls`` (otherwise they
# surface as phantom/duplicate calls) and out of the reasoning/content
# split. Mirrors vLLM's DelegatingParser, which runs the reasoning parser
# first and tool-parses only the post-``</think>`` content.
# ``reasoning_end_id`` is the ``</think>`` token id; when it's absent
# (``None``) or the model never closed its reasoning, the scan falls back
# to the whole stream (prior behavior).
reasoning_end = _find(ids, reasoning_end_id) if reasoning_end_id is not None else -1
scan_start = reasoning_end + 1 if reasoning_end != -1 else 0
tc_start = _find(ids, tool_call_id, scan_start)
tool_calls: list[ParsedToolCall] = []
if tc_start != -1:
content_ids = ids[:tc_start]
@@ -685,7 +733,15 @@ def parse_deepseek_v3(
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
tc_section_start = _find(ids, tool_calls_begin_id)
# Reasoning first: skip past </think> before looking for the tool-call
# section, so a section the model drafts *inside* its <think> trace isn't
# parsed as a real call (regression #78 — cf. parse_qwen3). content_ids
# still starts at 0, so the </think> text-split below recovers reasoning.
# DeepSeek-V3 renders </think> as multi-token text, hence the decode-based
# boundary finder rather than a token-id anchor.
reasoning_end = _reasoning_end_token_index(tokenizer, ids)
tc_section_start = _find(ids, tool_calls_begin_id, reasoning_end)
tool_calls: list[ParsedToolCall] = []
if tc_section_start != -1:
content_ids = ids[:tc_section_start]
@@ -962,6 +1018,7 @@ def parse_kimi_k2_section(
tool_call_begin_id: int,
tool_call_argument_begin_id: int,
tool_call_end_id: int,
scan_start: int = 0,
) -> tuple[list[int], list[ParsedToolCall]]:
"""Split ``ids`` into ``(content_before_section, tool_calls)`` by finding
the Kimi-style tool-call section delimiters.
@@ -973,8 +1030,15 @@ def parse_kimi_k2_section(
of the section and a list of ``ParsedToolCall`` covering every attempted
block inside it; an unclosed section is still walked to whatever the model
emitted before EOS. Returns ``(ids, [])`` when no section is present.
``scan_start`` restricts the section search to ``ids[scan_start:]`` while
keeping ``content_ids = ids[:section_start]`` and all token spans relative
to the full ``ids``. Callers pass the post-``</think>`` index so a section
the model drafts inside its reasoning trace isn't parsed as a real call;
because ``content_ids`` still starts at 0, downstream text-based reasoning
extraction is unaffected (regression #78).
"""
section_start = _find_any(ids, tool_calls_section_begin_ids)
section_start = _find_any(ids, tool_calls_section_begin_ids, scan_start)
if section_start == -1:
return list(ids), []
content_ids = ids[:section_start]
@@ -1270,3 +1334,70 @@ def _gptoss_extract_after_token(
return None
after = _decode(tokenizer, header_ids[pos + 1 :]).strip()
return after.split()[0] if after else None
# ── Llama-3: single JSON tool call {"name": "...", "parameters": {...}} ─
def parse_llama_3(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
) -> ParsedResponse:
"""Parse Llama-3 completion tokens.
The Llama-3 chat template emits tool calls as a single JSON blob in
the assistant body — ``{"name": "...", "parameters": {...}}`` — with
no surrounding XML tags or special tokens. Plain replies are just
text. We detect the tool-call shape with a strict starts-with-``{``
+ parses-as-dict-with-name-key check; anything else is treated as
content. Llama-3 doesn't have a built-in reasoning channel, so
``reasoning_content`` is always ``None``.
Unlike the delimiter-based formats (Qwen/GLM), the tool call has no
special token to anchor on, so a leading assistant role-header
(``<|start_header_id|>assistant<|end_header_id|>\\n\\n``) would defeat
the starts-with-``{`` check. Callers that slice a completion without
dropping the generation prompt include that scaffold; we skip past the
final ``<|end_header_id|>`` so the body is what we parse. The sampled
stream in production carries no header, making this a no-op there.
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
# Skip a leading assistant role-header scaffold if present.
body_start = 0
end_header_id = tokenizer.convert_tokens_to_ids("<|end_header_id|>")
if isinstance(end_header_id, int):
eh_positions = _find_all(ids, end_header_id)
if eh_positions:
body_start = eh_positions[-1] + 1
body_ids = ids[body_start:]
text = _decode(tokenizer, body_ids).strip()
if text.startswith("{") and text.endswith("}"):
try:
parsed = json.loads(text)
except json.JSONDecodeError:
parsed = None
if isinstance(parsed, dict) and parsed.get("name"):
arguments = parsed.get("parameters", parsed.get("arguments", {}))
return ParsedResponse(
content="",
reasoning_content=None,
tool_calls=[
ParsedToolCall(
raw=text,
name=parsed["name"],
arguments=arguments,
token_span=(body_start, len(ids)),
status=ToolCallParseStatus.OK,
)
],
)
# Not a tool-call shape (plain reply, or a ``{...}`` body that didn't
# parse / lacked a name). Llama-3 has no delimiter to anchor a
# "malformed attempt" against, so it falls through to content rather
# than producing a non-OK ParsedToolCall.
return ParsedResponse(content=text, reasoning_content=None)
+5
View File
@@ -19,6 +19,7 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
@@ -61,6 +62,7 @@ class Qwen3Renderer:
self._tool_call_end = self._token_id("</tool_call>")
self._tool_response = self._token_id("<tool_response>")
self._tool_response_end = self._token_id("</tool_response>")
self._think_end = self._token_id("</think>")
def _token_id(self, token: str) -> int:
tid = self._tokenizer.convert_tokens_to_ids(token)
@@ -247,6 +249,7 @@ class Qwen3Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -274,6 +277,7 @@ class Qwen3Renderer:
stop_ids={self._im_end, self._endoftext},
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
reasoning_end_id=self._think_end,
)
def get_stop_token_ids(self) -> list[int]:
@@ -403,6 +407,7 @@ class Qwen3Renderer:
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
+44 -34
View File
@@ -27,6 +27,7 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
@@ -66,39 +67,44 @@ _TOOLS_INSTRUCTIONS = (
)
def _detect_enable_thinking_default(tokenizer: PreTrainedTokenizer) -> bool:
"""Probe the tokenizer's chat template to learn its ``enable_thinking``
default polarity at the generation-prompt boundary.
# Per-model ``enable_thinking`` default, applied when the renderer config
# leaves it ``None``. The Qwen3.5 family ships two chat-template variants
# that differ only in the polarity of the gated thinking branch:
#
# * Big sizes (4B / 9B / 35B-A3B / 122B-A10B / 397B-A17B) default
# ``enable_thinking=true`` — an open ``<think>\n`` at the gen prompt.
# * Small sizes (0.8B / 2B) flip it — default ``false``, emitting the
# empty ``<think>\n\n</think>\n\n`` block.
#
# These are hard-coded (keyed by ``tokenizer.name_or_path``) rather than
# probed from the live ``chat_template``: probing meant calling
# ``apply_chat_template`` at construction, which pulls ``transformers`` onto
# the hot path and breaks bring-your-own-tokenizer use. The values are the
# ground truth pinned by ``tests/test_qwen35_size_coverage.py`` — both the
# polarity assertions and byte-parity against each size's own
# ``apply_chat_template``.
_ENABLE_THINKING_DEFAULTS: dict[str, bool] = {
"Qwen/Qwen3.5-0.8B": False,
"Qwen/Qwen3.5-2B": False,
"Qwen/Qwen3.5-4B": True,
"Qwen/Qwen3.5-9B": True,
"Qwen/Qwen3.5-35B-A3B": True,
"Qwen/Qwen3.5-122B-A10B": True,
"Qwen/Qwen3.5-397B-A17B": True,
# Qwen3.6 extends the Qwen3.5 template; same big-size polarity.
"Qwen/Qwen3.6-35B-A3B": True,
}
The Qwen3.5 family ships two template variants that differ only in the
polarity of the gated branch:
* Big sizes (4B / 9B / 35B-A3B / 122B-A10B / 397B-A17B) emit an open
``<think>\\n`` by default and the empty ``<think>\\n\\n</think>\\n\\n``
block when ``enable_thinking`` is explicitly false.
* Small sizes (0.8B / 2B) flip the polarity — they emit the empty
block by default and the open ``<think>\\n`` only when
``enable_thinking`` is explicitly true.
def _default_enable_thinking(tokenizer) -> bool:
"""Hard-coded ``enable_thinking`` default for ``tokenizer``'s model.
A one-shot ``apply_chat_template`` call with no flag and a minimal
user message reveals which variant is in use: the empty-block tail
ends with ``</think>``, the open-think tail does not. Failing the
probe (no chat_template, exotic config) falls back to the big-model
default of True, which matches every entry in
``MODEL_RENDERER_MAP`` that routes to ``qwen3.5`` without explicit
polarity awareness.
Falls back to ``True`` (the big-model default, and the majority of the
family) for unknown / fine-tuned checkpoints whose ``name_or_path`` isn't
in ``_ENABLE_THINKING_DEFAULTS``; pass an explicit ``enable_thinking=`` to
a small-size fine-tune that needs ``False``.
"""
try:
out = tokenizer.apply_chat_template(
[{"role": "user", "content": "x"}],
tokenize=False,
add_generation_prompt=True,
)
except Exception:
return True
if not isinstance(out, str):
return True
return not out.rstrip().endswith("</think>")
return _ENABLE_THINKING_DEFAULTS.get(getattr(tokenizer, "name_or_path", ""), True)
class Qwen35Renderer:
@@ -116,13 +122,13 @@ class Qwen35Renderer:
self._tokenizer = tokenizer
self._processor = processor
cfg = config or type(self)._config_cls()
# ``enable_thinking=None`` defers to the tokenizer's chat-template
# default (Instruct → off, Thinking → on). Materialise here so
# downstream reads see a concrete bool; rebind the config with
# the resolved value so introspection sees the same.
# ``enable_thinking=None`` defers to the model's known default (see
# ``_ENABLE_THINKING_DEFAULTS``). Materialise here so downstream reads
# see a concrete bool; rebind the config with the resolved value so
# introspection sees the same.
if cfg.enable_thinking is None:
cfg = cfg.model_copy(
update={"enable_thinking": _detect_enable_thinking_default(tokenizer)}
update={"enable_thinking": _default_enable_thinking(tokenizer)}
)
self.config = cfg
@@ -560,6 +566,7 @@ class Qwen35Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
multi_modal_data=mm_data,
)
@@ -836,6 +843,7 @@ class Qwen35Renderer:
merged_items.setdefault(modality, []).extend(vals)
bridge_roles = [m.get("role") or "" for m in new_messages]
bridge_tool_names = extract_message_tool_names(new_messages)
if not (merged_hashes or merged_placeholders or merged_items):
return RenderedTokens(
token_ids=tokens,
@@ -843,6 +851,7 @@ class Qwen35Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
)
mm_data = MultiModalData(
@@ -856,6 +865,7 @@ class Qwen35Renderer:
sampled_mask=sampled,
is_content=content_mask,
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
multi_modal_data=mm_data,
)
+5
View File
@@ -43,6 +43,7 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
trim_to_turn_close,
)
@@ -324,6 +325,7 @@ class Qwen3VLRenderer:
self._tool_call_end = self._token_id("</tool_call>")
self._tool_response = self._token_id("<tool_response>")
self._tool_response_end = self._token_id("</tool_response>")
self._think_end = self._token_id("</think>")
self._vision_start = self._token_id("<|vision_start|>")
self._vision_end = self._token_id("<|vision_end|>")
self._image_pad = self._token_id("<|image_pad|>")
@@ -604,6 +606,7 @@ class Qwen3VLRenderer:
sampled_mask=em.sampled,
is_content=em.is_content,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
multi_modal_data=mm_data,
)
@@ -632,6 +635,7 @@ class Qwen3VLRenderer:
stop_ids={self._im_end, self._endoftext},
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
reasoning_end_id=self._think_end,
)
def get_stop_token_ids(self) -> list[int]:
@@ -839,6 +843,7 @@ class Qwen3VLRenderer:
sampled_mask=em.sampled,
is_content=em.is_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
multi_modal_data=mm_data,
)
+45
View File
@@ -33,7 +33,25 @@ RENDERER_MODELS = [
("moonshotai/Kimi-K2.6", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
# Ultra resolves to the `nemotron-3-ultra` config variant via the model
# name (auto → MODEL_RENDERER_MAP → nemotron-3-ultra).
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
("poolside/Laguna-XS.2", "auto"),
# DeepSeek-V3/R1 are intentionally NOT in this shared barrage: their
# chat templates can't render the barrage's tool-call fixtures (the
# templates require ``tool['type']`` and a string-serialized
# ``arguments``, and V3 only renders tool_calls when content is None —
# so ``apply_chat_template`` raises or drops the calls on the shared
# shapes), and the is_content body-recovery checks hit a Metaspace
# subset-decode artifact. The renderer is correct in all these cases;
# there's just no byte-output to parity-check against. Split-specific
# parity (V3 bare prompt vs R1 <think>+history-strip) is covered in
# tests/test_deepseek_r1.py.
# Llama-3 loads via the unrestricted unsloth mirror (byte-identical
# chat template) so CI needs no Meta-gated HF token. Pinned to the
# explicit "llama-3" config because the mirror name isn't in
# MODEL_RENDERER_MAP (so "auto" would fall back to DefaultRenderer).
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
("openai/gpt-oss-20b", "gpt-oss"),
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
]
@@ -103,3 +121,30 @@ def _skip_gpt_oss_for_hf_parity_tests(request):
f"{model_name}: renderer matches openai-harmony / vLLM, not HF "
"apply_chat_template — see test_gpt_oss_harmony_parity.py"
)
# Llama-3's chat template fills the "Today Date:" line via ``strftime_now``,
# so ``apply_chat_template`` with no explicit ``date_string`` bakes in the
# real wall-clock date — non-deterministic and not byte-stable against a
# renderer pinned to "26 Jul 2024". Generic HF-parity tests can't pass a
# kwarg, so they're skipped here; deterministic byte-parity (with the date
# passed on both sides) is covered in test_llama_3.py.
_LLAMA_HF_PARITY_TEST_FILES = {
"test_render_ids.py",
"test_build_helpers.py",
}
@pytest.fixture(autouse=True)
def _skip_llama_for_hf_parity_tests(request):
callspec = getattr(request.node, "callspec", None)
model_name = callspec.params.get("model_name") if callspec else None
if model_name != "unsloth/Llama-3.2-1B-Instruct":
return
test_file = os.path.basename(str(request.node.fspath))
if test_file in _LLAMA_HF_PARITY_TEST_FILES:
pytest.skip(
f"{model_name}: template uses strftime_now for the date line, so "
"generic apply_chat_template parity is non-deterministic — "
"deterministic byte-parity is covered in test_llama_3.py"
)
+1
View File
@@ -33,6 +33,7 @@ _BRIDGE_MODELS = [
("moonshotai/Kimi-K2-Instruct", "auto"),
("moonshotai/Kimi-K2.5", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
("openai/gpt-oss-20b", "gpt-oss"),
]
+152
View File
@@ -0,0 +1,152 @@
"""DeepSeek-R1 renderer: the reasoning variant of the DeepSeek format.
General byte-parity vs ``apply_chat_template`` is covered by the conftest
barrage (``test_render_ids`` now includes both DeepSeek models). These tests
pin the behaviors that distinguish R1 from V3: the ``<think>`` generation
prompt and the stripping of ``</think>`` from historical assistant turns.
"""
from functools import lru_cache
import pytest
from renderers import (
DeepSeekR1Renderer,
DeepSeekV3Renderer,
create_renderer,
)
from renderers.base import load_tokenizer
@lru_cache
def _r1():
tok = load_tokenizer("deepseek-ai/DeepSeek-R1")
return tok, create_renderer(tok)
@lru_cache
def _v3():
tok = load_tokenizer("deepseek-ai/DeepSeek-V3")
return tok, create_renderer(tok)
# Baseline render_ids == apply_chat_template parity. Tool-cycle shapes are
# intentionally excluded: the DeepSeek template renders tool_calls only when
# content is None (a pre-existing renderer↔template gap, tracked separately),
# which is orthogonal to the V3/R1 reasoning split this module covers.
_PARITY_SHAPES = [
(
"single_turn",
[
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
],
{},
),
(
"multi_turn",
[
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
],
{},
),
(
"reasoning_content_field",
[
{"role": "user", "content": "x"},
{"role": "assistant", "reasoning_content": "r", "content": "4"},
],
{},
),
(
"gen_prompt",
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
],
{"add_generation_prompt": True},
),
(
"inline_think_history",
[
{"role": "user", "content": "q"},
{"role": "assistant", "content": "<think>reasoning</think>answer"},
{"role": "user", "content": "q2"},
],
{},
),
]
@pytest.mark.parametrize("loader", [_v3, _r1], ids=["v3", "r1"])
@pytest.mark.parametrize(
"shape_id,messages,kwargs", _PARITY_SHAPES, ids=[s[0] for s in _PARITY_SHAPES]
)
def test_render_ids_matches_apply_chat_template(loader, shape_id, messages, kwargs):
tok, renderer = loader()
got = renderer.render_ids(messages, **kwargs)
expected = list(
tok.apply_chat_template(messages, tokenize=True, return_dict=False, **kwargs)
)
assert got == expected
def test_auto_detection_picks_the_right_renderer():
_, r1 = _r1()
_, v3 = _v3()
assert isinstance(r1, DeepSeekR1Renderer)
assert isinstance(v3, DeepSeekV3Renderer)
def test_generation_prompt_differs():
"""R1 prefills ``<think>`` to trigger reasoning; V3 does not."""
msgs = [{"role": "user", "content": "hi"}]
tr1, r1 = _r1()
tv3, v3 = _v3()
r1_text = tr1.decode(r1.render_ids(msgs, add_generation_prompt=True))
v3_text = tv3.decode(v3.render_ids(msgs, add_generation_prompt=True))
# R1 prefills <think> to trigger reasoning; V3 emits a bare assistant
# turn. (Exact byte parity vs apply_chat_template is the gen_prompt case
# in the parity matrix above; here we just pin the V3/R1 distinction —
# decode trims the trailing "\n" so we don't match on it.)
assert "<think>" in r1_text and r1_text.rstrip().endswith("<think>")
assert "<think>" not in v3_text
def test_r1_strips_reasoning_from_history():
"""A historical assistant turn carrying an inline ``<think>…</think>``
trace renders only the post-``</think>`` answer, byte-identical to the R1
chat template's ``content.split('</think>')[-1]``.
"""
tok, r1 = _r1()
msgs = [
{"role": "user", "content": "q"},
{"role": "assistant", "content": "<think>private reasoning</think>The answer."},
{"role": "user", "content": "q2"},
]
got = r1.render_ids(msgs)
expected = list(tok.apply_chat_template(msgs, tokenize=True, return_dict=False))
assert got == expected
# Reasoning must not survive into the rendered history.
assert "private reasoning" not in tok.decode(got)
def test_v3_emits_content_verbatim_ignoring_reasoning():
"""V3 (non-reasoning) ignores ``reasoning_content`` — matching its
template, which only reads ``content``."""
tok, v3 = _v3()
msgs = [
{"role": "user", "content": "x"},
{"role": "assistant", "reasoning_content": "should be ignored", "content": "4"},
]
got = v3.render_ids(msgs)
expected = list(tok.apply_chat_template(msgs, tokenize=True, return_dict=False))
assert got == expected
assert "should be ignored" not in tok.decode(got)
+407
View File
@@ -0,0 +1,407 @@
"""Llama-3 renderer coverage.
Covers ``Llama3Renderer`` and the ``meta-llama/Llama-3.2-{1B,3B}-Instruct``
entries in ``MODEL_RENDERER_MAP``. Tokenizers are loaded via the
unrestricted ``unsloth/Llama-3.2-{1B,3B}-Instruct`` mirrors (verified
byte-identical chat templates) so CI doesn't need an HF token with Meta
license access.
"""
from __future__ import annotations
import pytest
from renderers import Llama3Renderer, Llama3RendererConfig, create_renderer
from renderers.base import (
MODEL_RENDERER_MAP,
ParsedResponse,
ToolCallParseStatus,
load_tokenizer,
)
# Pinned date for byte-parity tests. Matches the chat template's
# strftime fallback so we don't have to override on the apply side.
_PINNED_DATE = "26 Jul 2024"
_MODEL_PAIRS = [
# (canonical meta-llama id used by MODEL_RENDERER_MAP, unrestricted
# mirror used to actually load the tokenizer in tests)
("meta-llama/Llama-3.2-1B-Instruct", "unsloth/Llama-3.2-1B-Instruct"),
("meta-llama/Llama-3.2-3B-Instruct", "unsloth/Llama-3.2-3B-Instruct"),
]
@pytest.fixture(scope="module", params=_MODEL_PAIRS, ids=[m for m, _ in _MODEL_PAIRS])
def llama_pair(request):
canonical, mirror = request.param
tok = load_tokenizer(mirror)
renderer = Llama3Renderer(tok, Llama3RendererConfig(date_string=_PINNED_DATE))
return canonical, mirror, tok, renderer
# ---------------------------------------------------------------------------
# MODEL_RENDERER_MAP shape
# ---------------------------------------------------------------------------
def test_canonical_meta_llama_paths_route_to_llama_3():
for canonical, _ in _MODEL_PAIRS:
assert MODEL_RENDERER_MAP.get(canonical) == "llama-3", (
f"{canonical}: expected to route to 'llama-3'"
)
def test_create_renderer_via_explicit_config(llama_pair):
"""``Llama3RendererConfig`` resolves to Llama3Renderer in the registry."""
_, _, tok, _ = llama_pair
r = create_renderer(tok, Llama3RendererConfig())
assert isinstance(r, Llama3Renderer)
# ---------------------------------------------------------------------------
# Constructor contract
# ---------------------------------------------------------------------------
def test_default_date_matches_chat_template_strftime_fallback(llama_pair):
"""Default ``date_string`` is ``"26 Jul 2024"`` so output stays
deterministic without an explicit override."""
_, _, tok, _ = llama_pair
r = Llama3Renderer(tok)
assert r.config.date_string == _PINNED_DATE
def test_preserve_thinking_flags_are_noops(llama_pair):
"""Llama-3 has no reasoning channel, so the ``preserve_*_thinking``
flags are accepted but never change the token stream — the same
never-preserves contract as Kimi-K2 / Qwen3-VL. (Cross-renderer
coverage lives in tests/test_preserve_thinking.py.)"""
_, _, tok, _ = llama_pair
msgs = [
{"role": "user", "content": "Hi."},
{
"role": "assistant",
"reasoning_content": "internal musings",
"content": "Hello!",
},
]
base = Llama3Renderer(tok).render_ids(msgs)
for flag in ("preserve_all_thinking", "preserve_thinking_between_tool_calls"):
r = Llama3Renderer(tok, Llama3RendererConfig(**{flag: True}))
assert r.config.__getattribute__(flag) is True
assert r.render_ids(msgs) == base, f"{flag} must be a no-op for Llama-3"
# ---------------------------------------------------------------------------
# Byte parity vs apply_chat_template
# ---------------------------------------------------------------------------
def _expected(tok, messages, **kwargs):
kwargs.setdefault("add_generation_prompt", False)
kwargs.setdefault("date_string", _PINNED_DATE)
return list(
tok.apply_chat_template(messages, tokenize=True, return_dict=False, **kwargs)
)
def test_parity_minimal_user(llama_pair):
_, _, tok, r = llama_pair
msgs = [{"role": "user", "content": "Hi."}]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_system_and_user(llama_pair):
_, _, tok, r = llama_pair
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_system_user_assistant(llama_pair):
_, _, tok, r = llama_pair
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
{"role": "assistant", "content": "Hello!"},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_no_system_with_gen_prompt(llama_pair):
_, _, tok, r = llama_pair
msgs = [{"role": "user", "content": "Hi."}]
assert r.render_ids(msgs, add_generation_prompt=True) == _expected(
tok, msgs, add_generation_prompt=True
)
def test_parity_multi_turn(llama_pair):
_, _, tok, r = llama_pair
msgs = [
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_trims_whitespace(llama_pair):
_, _, tok, r = llama_pair
msgs = [
{"role": "user", "content": " hello "},
{"role": "assistant", "content": "\n\nworld\n"},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_custom_date(llama_pair):
"""``date_string`` constructor override changes both sides identically."""
_, _, tok, _ = llama_pair
r = Llama3Renderer(tok, Llama3RendererConfig(date_string="01 Jan 2026"))
msgs = [{"role": "user", "content": "Hi."}]
expected = list(
tok.apply_chat_template(
msgs, tokenize=True, return_dict=False, date_string="01 Jan 2026"
)
)
assert r.render_ids(msgs) == expected
def test_parity_tools_in_user_default(llama_pair):
_, _, tok, r = llama_pair
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
},
},
}
]
msgs = [
{"role": "system", "content": "Be terse."},
{"role": "user", "content": "Weather?"},
]
assert r.render_ids(msgs, tools=tools) == _expected(tok, msgs, tools=tools)
def test_parity_tools_in_system_mode(llama_pair):
"""When constructed with ``tools_in_user_message=False``, the renderer
matches ``apply_chat_template(... tools_in_user_message=False)``."""
_, _, tok, _ = llama_pair
r = Llama3Renderer(
tok,
Llama3RendererConfig(date_string=_PINNED_DATE, tools_in_user_message=False),
)
tools = [
{
"type": "function",
"function": {"name": "get_weather", "parameters": {}},
}
]
msgs = [
{"role": "system", "content": "Be terse."},
{"role": "user", "content": "Weather?"},
]
expected = list(
tok.apply_chat_template(
msgs,
tokenize=True,
return_dict=False,
tools=tools,
tools_in_user_message=False,
date_string=_PINNED_DATE,
)
)
assert r.render_ids(msgs, tools=tools) == expected
def test_parity_tool_call_round_trip(llama_pair):
"""Assistant tool_calls + tool response + final assistant — covers
the JSON tool-call body emission and the ``ipython`` response role."""
_, _, tok, r = llama_pair
msgs = [
{"role": "user", "content": "Weather?"},
{
"role": "assistant",
"tool_calls": [
{
"type": "function",
"function": {
"name": "get_weather",
"arguments": {"city": "NYC"},
},
}
],
},
{"role": "tool", "content": '{"temp": 72}'},
{"role": "assistant", "content": "It's 72."},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_tool_response_dict_content(llama_pair):
"""Tool response with mapping content goes through ``tojson`` in the
template; the renderer's ``_tool_response_str`` mirrors that."""
_, _, tok, r = llama_pair
msgs = [
{"role": "user", "content": "x"},
{
"role": "assistant",
"tool_calls": [{"function": {"name": "f", "arguments": {}}}],
},
{"role": "tool", "content": {"k": "v", "n": 42}},
{"role": "assistant", "content": "ok"},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_render_raises_on_multiple_tool_calls(llama_pair):
"""Llama-3 chat template explicitly raises on >1 tool call per turn —
the renderer mirrors that contract."""
_, _, _, r = llama_pair
msgs = [
{"role": "user", "content": "x"},
{
"role": "assistant",
"tool_calls": [
{"function": {"name": "f", "arguments": {}}},
{"function": {"name": "g", "arguments": {}}},
],
},
]
with pytest.raises(ValueError, match="single tool call"):
r.render_ids(msgs)
# ---------------------------------------------------------------------------
# parse_response
# ---------------------------------------------------------------------------
def _tokens_for(tok, text: str) -> list[int]:
return tok.encode(text, add_special_tokens=False)
def test_parse_response_plain_content(llama_pair):
_, _, tok, r = llama_pair
ids = _tokens_for(tok, "Hello, world!") + [r._eot]
out = r.parse_response(ids)
assert isinstance(out, ParsedResponse)
assert out.content == "Hello, world!"
assert out.tool_calls == []
assert out.reasoning_content is None
def test_parse_response_tool_call(llama_pair):
_, _, tok, r = llama_pair
body = '{"name": "get_weather", "parameters": {"city": "NYC"}}'
ids = _tokens_for(tok, body) + [r._eot]
out = r.parse_response(ids)
assert out.content == ""
assert len(out.tool_calls) == 1
tc = out.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "get_weather"
assert tc.arguments == {"city": "NYC"}
def test_parse_response_malformed_tool_call_falls_through_to_content(llama_pair):
"""A body that LOOKS like a tool call but doesn't parse should land
in content rather than dropping silently."""
_, _, tok, r = llama_pair
body = '{"name": "x", broken'
ids = _tokens_for(tok, body) + [r._eot]
out = r.parse_response(ids)
assert out.tool_calls == []
assert "{" in out.content
# ---------------------------------------------------------------------------
# Bridge contract
# ---------------------------------------------------------------------------
def _simulate_prior_turn(r):
prior = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
]
asst = [{"role": "assistant", "content": "Hello!"}]
prev_prompt = r.render_ids(prior, add_generation_prompt=True)
full = r.render_ids(prior + asst, add_generation_prompt=False)
prev_completion = list(full[len(prev_prompt) :])
stop = set(r.get_stop_token_ids())
last = -1
for i in range(len(prev_completion) - 1, -1, -1):
if prev_completion[i] in stop:
last = i
break
if last >= 0:
prev_completion = prev_completion[: last + 1]
return prev_prompt, prev_completion
def test_bridge_extends_prev_verbatim_on_clean_stop(llama_pair):
_, _, _, r = llama_pair
prev_prompt, prev_completion = _simulate_prior_turn(r)
new_messages = [{"role": "user", "content": "What's 2+2?"}]
bridged = r.bridge_to_next_turn(prev_prompt, prev_completion, new_messages)
assert bridged is not None
prev = prev_prompt + prev_completion
assert bridged.token_ids[: len(prev)] == prev
assert len(bridged.token_ids) > len(prev)
def test_bridge_matches_fresh_render_on_clean_stop(llama_pair):
"""The whole point of the bridge: it must produce the same tokens as
a fresh render of the full message list — except sampled tokens are
kept verbatim rather than re-rendered."""
_, _, _, r = llama_pair
prior = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
]
asst = [{"role": "assistant", "content": "Hello!"}]
new_messages = [{"role": "user", "content": "What's 2+2?"}]
prev_prompt, prev_completion = _simulate_prior_turn(r)
bridged = r.bridge_to_next_turn(prev_prompt, prev_completion, new_messages)
fresh = r.render_ids(prior + asst + new_messages, add_generation_prompt=True)
assert bridged.token_ids == fresh
def test_bridge_rejects_assistant_in_extension(llama_pair):
_, _, _, r = llama_pair
prev_prompt, prev_completion = _simulate_prior_turn(r)
bridged = r.bridge_to_next_turn(
prev_prompt,
prev_completion,
[{"role": "assistant", "content": "forbidden"}],
)
assert bridged is None
def test_bridge_synthesises_close_on_truncation(llama_pair):
_, _, _, r = llama_pair
prev_prompt, prev_completion = _simulate_prior_turn(r)
trunc = prev_completion[:-1]
if not trunc:
pytest.skip("simulated prior had no completion tokens to truncate")
bridged = r.bridge_to_next_turn(
prev_prompt, trunc, [{"role": "user", "content": "ping"}]
)
assert bridged is not None
base = prev_prompt + trunc
assert bridged.token_ids[: len(base)] == base
assert len(bridged.token_ids) > len(base)
+2
View File
@@ -46,6 +46,8 @@ def test_fastokens_incompatible_is_explicit_set():
{
"deepseek-ai/DeepSeek-V3",
"deepseek-ai/DeepSeek-V3-Base",
"deepseek-ai/DeepSeek-R1",
"deepseek-ai/DeepSeek-R1-0528",
}
)
+97
View File
@@ -0,0 +1,97 @@
"""Tests for ``RenderedTokens.message_tool_names`` and its populating helper.
``message_tool_names`` is a per-message sidecar parallel to
``message_roles``: for each tool-role message in the rendered slice
it carries the tool function name, ``None`` everywhere else. The name
comes from ``msg["name"]`` when set, otherwise from a
``tool_call_id`` join against any prior assistant's ``tool_calls`` in
the same slice. Pure metadata — does not affect the rendered token
stream, does not mutate the caller's messages.
Unit tests below cover the join's case matrix without a tokenizer.
The single integration test runs every renderer in the conftest
matrix to catch any of the ~25 ``RenderedTokens(...)`` construction
sites that might fail to wire the field through.
"""
from __future__ import annotations
from renderers.base import extract_message_tool_names
def test_extract_empty():
assert extract_message_tool_names([]) == []
def test_extract_caller_provided_name_wins():
"""``msg['name']`` set by the caller is used verbatim — no join attempted."""
messages = [
{"role": "tool", "tool_call_id": "c1", "name": "caller_set", "content": "x"},
]
assert extract_message_tool_names(messages) == ["caller_set"]
def test_extract_resolves_from_prior_assistant():
"""Tool message without ``name``: recovered via tool_call_id → assistant.tool_calls."""
messages = [
{"role": "user", "content": "go"},
{
"role": "assistant",
"tool_calls": [{"id": "c1", "function": {"name": "screenshot"}}],
},
{"role": "tool", "tool_call_id": "c1", "content": "ok"},
]
assert extract_message_tool_names(messages) == [None, None, "screenshot"]
def test_extract_orphan_tool_message_is_none():
"""``tool_call_id`` matching no in-slice assistant resolves to ``None``
(bridge case: the issuing assistant lives in the prior portion that
``new_messages`` doesn't cover).
"""
messages = [{"role": "tool", "tool_call_id": "orphan", "content": "x"}]
assert extract_message_tool_names(messages) == [None]
def test_extract_does_not_mutate_caller():
"""Caller's tool message must not gain a ``name`` field after extraction —
the helper produces a sidecar list, not a mutated view of the input.
"""
messages = [
{
"role": "assistant",
"tool_calls": [{"id": "c1", "function": {"name": "f"}}],
},
{"role": "tool", "tool_call_id": "c1", "content": "x"},
]
extract_message_tool_names(messages)
assert "name" not in messages[1]
def test_renderer_populates_message_tool_names(model_name, renderer):
"""Every renderer wires ``message_tool_names`` through ``RenderedTokens``.
Catches missed wire-up at any of the ~25 ``RenderedTokens(...)``
construction sites across concrete renderers. The input is
spec-conformant (tool message carries ``tool_call_id`` but no
``name``) so the resolution path exercises the internal join.
"""
messages = [
{"role": "user", "content": "go"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c1",
"type": "function",
"function": {"name": "screenshot", "arguments": {}},
}
],
},
{"role": "tool", "tool_call_id": "c1", "content": "ok"},
]
rt = renderer.render(messages)
assert rt.message_tool_names == [None, None, "screenshot"], (
f"{model_name}: got {rt.message_tool_names}"
)
+676
View File
@@ -0,0 +1,676 @@
"""Exhaustive token-for-token parity for the Nemotron-3 renderer.
The shared barrage in ``test_render_ids.py`` covers the common message
shapes against every model. This file pins the Nemotron-3-specific template
branches that the shared matrix can't reach — they'd fail on other models or
exercise behaviour unique to the Nemotron-3 chat template:
* reasoning + empty / ``None`` content with and without tool calls (the
template trims the assembled ``<think>…</think>{content}`` block and appends
exactly one separator — a stray ``\\n`` here is the most common agentic
regression);
* the historical-thinking truncation boundary, which is ``loop.index0 <
last_user_idx`` in **all three** variants (Nano / Super / Ultra) — so an
in-flight tool cycle (assistant turns after the last user message) keeps its
reasoning by default;
* inline ``<think>…</think>`` tags carried in ``content`` rendering verbatim
(the template only reformats reasoning supplied via ``reasoning_content``);
* verbatim (unstripped) user / system / tool content and ``reasoning_content``;
* the ``enable_thinking`` / ``truncate_history_thinking`` template kwargs;
* the per-variant reasoning-effort kwargs: ``low_effort`` (Super) and
``medium_effort`` (Ultra), each a no-op on the variants that don't define it.
Every assertion compares ``renderer.render_ids(...)`` to
``tokenizer.apply_chat_template(..., tokenize=True)`` — a pass means the
renderer is byte-for-byte faithful for that case. Tokenizers are loaded from
the local HF cache (offline); no network.
The variants split across two configs: ``nemotron-3`` (Nano / Super, with
``low_effort``) and ``nemotron-3-ultra`` (Ultra, with ``medium_effort``). The
helper resolves the right config class per model from ``MODEL_RENDERER_MAP``.
"""
from __future__ import annotations
from functools import lru_cache
import pytest
from renderers import create_renderer
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
from renderers.configs import _config_class_for
# BF16 / FP8 share a tokenizer; only the BF16 checkpoints are cached for tests.
NANO = "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"
SUPER = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
ULTRA = "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16"
MODELS = [NANO, SUPER, ULTRA]
@lru_cache
def _tok(model: str):
return load_tokenizer(model)
def _config_cls(model: str):
"""The typed-config class the model resolves to (``nemotron-3`` for
Nano/Super, ``nemotron-3-ultra`` for Ultra)."""
return _config_class_for(MODEL_RENDERER_MAP[model])
def _renderer(model: str, **flags):
# Build with the model's own variant config so the renderer picks the right
# ``</think>`` glue (and only valid kwargs are accepted).
return create_renderer(_tok(model), _config_cls(model)(**flags))
def _expected(
model: str, messages, *, tools=None, add_generation_prompt=False, **kwargs
):
out = _tok(model).apply_chat_template(
messages,
tools=tools,
tokenize=True,
return_dict=False,
add_generation_prompt=add_generation_prompt,
**kwargs,
)
if isinstance(out, str): # some tokenizers return str even with tokenize=True
return list(_tok(model).encode(out, add_special_tokens=False))
return list(out)
def _assert_parity(
model, messages, *, tools=None, add_generation_prompt=False, **template_kwargs
):
"""Renderer ids == apply_chat_template ids for ``model``.
``template_kwargs`` (e.g. ``enable_thinking``, ``truncate_history_thinking``)
are forwarded to both the renderer config and ``apply_chat_template`` so the
two sides stay aligned.
"""
renderer = _renderer(model, **template_kwargs)
got = renderer.render_ids(
messages, tools=tools, add_generation_prompt=add_generation_prompt
)
exp = _expected(
model,
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
**template_kwargs,
)
assert got == exp, (
f"{model}: render_ids diverged from apply_chat_template\n"
f" exp …{_tok(model).decode(exp[-40:])!r}\n"
f" got …{_tok(model).decode(got[-40:])!r}"
)
pytestmark = pytest.mark.parametrize("model", MODELS, ids=["nano", "super", "ultra"])
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "The city name"}
},
"required": ["city"],
},
},
}
]
# ── Reasoning + tool calls: the trim / separator boundary ─────────────
def test_reasoning_empty_content_tool_call(model):
"""reason → tool call, no prose. Must be ``</think>\\n<tool_call>`` (one
newline), not ``</think>\\n\\n<tool_call>``."""
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "I should call the weather tool.",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
],
tools=TOOLS,
)
def test_reasoning_none_content_tool_call(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "Call the tool.",
"content": None,
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
],
tools=TOOLS,
)
def test_reasoning_content_tool_call(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "Think first.",
"content": "Let me check.",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
],
tools=TOOLS,
)
def test_reasoning_empty_content_no_tool_call(model):
"""reason → empty answer, no tool call: ``</think>`` glued to ``<|im_end|>``."""
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{"role": "assistant", "reasoning_content": "thinking", "content": ""},
],
)
def test_multiple_tool_calls_with_reasoning(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris and London?"},
{
"role": "assistant",
"reasoning_content": "Two cities — two calls.",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
},
{
"function": {
"name": "get_weather",
"arguments": {"city": "London"},
}
},
],
},
],
tools=TOOLS,
)
def test_tool_call_with_nested_object_args(model):
_assert_parity(
model,
[
{"role": "user", "content": "go"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {
"city": "Paris",
"opts": {"unit": "c", "days": [1, 2]},
},
}
}
],
},
],
tools=TOOLS,
)
# ── Historical-thinking truncation boundary (last_user_idx) ───────────
def test_inflight_tool_cycle_keeps_reasoning(model):
"""Assistant turns after the last user message (the in-flight tool cycle)
keep their reasoning by default — boundary is ``loop.index0 <
last_user_idx`` in every variant."""
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "Call the tool first.",
"content": "calling",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": '{"temp": 20}'},
{
"role": "assistant",
"reasoning_content": "Now I can answer.",
"content": "It is 20 degrees.",
},
],
tools=TOOLS,
)
def test_history_truncation_drops_older_reasoning(model):
"""A reasoning turn before the last user message is collapsed to an empty
think block (tool-call branch trims the remainder on Nano/Super)."""
_assert_parity(
model,
[
{"role": "user", "content": "Q1"},
{
"role": "assistant",
"reasoning_content": "reasoning before tool",
"content": "calling",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": '{"temp": 20}'},
{"role": "assistant", "reasoning_content": "after", "content": "Done."},
{"role": "user", "content": "Q2"},
{"role": "assistant", "reasoning_content": "final", "content": "A2"},
],
tools=TOOLS,
)
def test_two_block_tool_conversation(model):
_assert_parity(
model,
[
{"role": "system", "content": "be brief"},
{"role": "user", "content": "first"},
{
"role": "assistant",
"reasoning_content": "R2",
"content": "calling.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "a"}}}
],
},
{"role": "tool", "content": "result-a"},
{"role": "assistant", "reasoning_content": "R4", "content": "answer-1"},
{"role": "user", "content": "second"},
{
"role": "assistant",
"reasoning_content": "R6",
"content": "calling.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "b"}}}
],
},
{"role": "tool", "content": "result-b"},
{"role": "assistant", "reasoning_content": "R8", "content": "answer-2"},
],
tools=TOOLS,
)
def test_plain_multi_turn_reasoning_truncation(model):
_assert_parity(
model,
[
{"role": "user", "content": "Q1"},
{
"role": "assistant",
"reasoning_content": "long reasoning one",
"content": "A1",
},
{"role": "user", "content": "Q2"},
{
"role": "assistant",
"reasoning_content": "long reasoning two",
"content": "A2",
},
],
)
@pytest.mark.parametrize("truncate", [True, False])
def test_truncate_history_thinking_kwarg(model, truncate):
"""``truncate_history_thinking=False`` keeps reasoning on every past turn."""
_assert_parity(
model,
[
{"role": "user", "content": "Q1"},
{
"role": "assistant",
"reasoning_content": "first reasoning",
"content": "A1",
},
{"role": "user", "content": "Q2"},
{
"role": "assistant",
"reasoning_content": "second reasoning",
"content": "A2",
},
],
truncate_history_thinking=truncate,
)
# ── Inline <think> tags carried in content (no reasoning_content field) ─
def test_inline_think_tags_final_turn_verbatim(model):
"""Inline ``<think>…</think>`` in the final assistant ``content`` renders
verbatim — the renderer must not parse + reformat it."""
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "<think>secret</think>visible"},
],
)
def test_inline_think_tags_history_turn(model):
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{
"role": "assistant",
"content": "<think>secret reasoning</think>visible answer",
},
{"role": "user", "content": "again"},
{"role": "assistant", "content": "second"},
],
)
# ── Verbatim (unstripped) content ─────────────────────────────────────
def test_system_content_whitespace_verbatim(model):
_assert_parity(
model,
[
{"role": "system", "content": " padded system "},
{"role": "user", "content": "hi"},
],
)
def test_user_content_whitespace_verbatim(model):
_assert_parity(
model,
[
{"role": "user", "content": " padded user "},
{"role": "assistant", "content": "ok"},
],
)
def test_assistant_content_whitespace(model):
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{"role": "assistant", "content": " spaced answer "},
],
)
def test_reasoning_content_whitespace_verbatim(model):
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{
"role": "assistant",
"reasoning_content": " padded reason ",
"content": "answer",
},
],
)
def test_tool_content_whitespace_verbatim(model):
_assert_parity(
model,
[
{"role": "user", "content": "go"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": " spaced tool result "},
{"role": "assistant", "content": "done"},
],
tools=TOOLS,
)
def test_system_whitespace_with_tools(model):
_assert_parity(
model,
[
{"role": "system", "content": " weather bot "},
{"role": "user", "content": "Weather?"},
],
tools=TOOLS,
)
# ── Generation prompt / thinking toggle ───────────────────────────────
@pytest.mark.parametrize("enable_thinking", [True, False])
def test_generation_prompt_thinking_toggle(model, enable_thinking):
_assert_parity(
model,
[{"role": "user", "content": "hi"}],
add_generation_prompt=True,
enable_thinking=enable_thinking,
)
def test_generation_prompt_after_tool_response(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": '{"temp": 20}'},
],
tools=TOOLS,
add_generation_prompt=True,
)
# ── Whole-conversation cycles, no reasoning ───────────────────────────
def test_full_tool_cycle_no_reasoning(model):
_assert_parity(
model,
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "Let me check.",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": '{"temp": 20, "condition": "sunny"}'},
{"role": "assistant", "content": "It is 20 degrees and sunny."},
],
tools=TOOLS,
)
def test_consecutive_tool_responses(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris and London?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
},
{
"function": {
"name": "get_weather",
"arguments": {"city": "London"},
}
},
],
},
{"role": "tool", "content": '{"temp": 20}'},
{"role": "tool", "content": '{"temp": 15}'},
{"role": "assistant", "content": "Paris: 20, London: 15."},
],
tools=TOOLS,
)
def test_no_system_no_tools_injects_empty_system(model):
_assert_parity(
model,
[
{"role": "user", "content": "Hello!"},
{"role": "assistant", "content": "Hi there!"},
],
)
# ── Reasoning-effort kwargs (variant-specific) ────────────────────────
_EFFORT_SHAPES = [
# gen-prompt shape: hint rides on the (only) user message.
([{"role": "user", "content": "solve it"}], {"add_generation_prompt": True}),
# multi-turn: hint must land on the LAST user message, not the first.
(
[
{"role": "user", "content": "first"},
{"role": "assistant", "content": "ok"},
{"role": "user", "content": "second"},
],
{"add_generation_prompt": True},
),
]
@pytest.mark.parametrize("flag", [True, False])
@pytest.mark.parametrize(
"shape,extra", _EFFORT_SHAPES, ids=["gen_prompt", "multi_turn"]
)
def test_low_effort_kwarg(model, flag, shape, extra):
"""``low_effort`` appends ``\\n\\n{reasoning effort: low}`` to the last user
message on **Super**; it's a no-op on **Nano** (its template never defines
it). Ultra's config has no such field, so it's skipped."""
if model == ULTRA:
pytest.skip("low_effort is a nemotron-3 (Nano/Super) kwarg")
_assert_parity(model, shape, low_effort=flag, **extra)
@pytest.mark.parametrize("flag", [True, False])
@pytest.mark.parametrize(
"shape,extra", _EFFORT_SHAPES, ids=["gen_prompt", "multi_turn"]
)
def test_medium_effort_kwarg(model, flag, shape, extra):
"""``medium_effort`` appends ``\\n\\n{reasoning effort: efficient}`` on
**Ultra**. Nano/Super configs have no such field, so they're skipped."""
if model != ULTRA:
pytest.skip("medium_effort is a nemotron-3-ultra kwarg")
_assert_parity(model, shape, medium_effort=flag, **extra)
def test_effort_kwarg_lives_on_the_right_variant(model):
"""Each effort kwarg is declared only on the variant whose template defines
it — the discriminated union rejects the wrong combination at config load."""
fields = _config_cls(model).template_field_names()
if model == ULTRA:
assert "medium_effort" in fields and "low_effort" not in fields
else:
assert "low_effort" in fields and "medium_effort" not in fields
+104
View File
@@ -0,0 +1,104 @@
"""Offline wiring tests for the Nemotron-3 variant split.
Assert the model→renderer mapping, the per-variant typed-config surface, and
the name-based ``low_effort`` gating WITHOUT loading any tokenizer (no
network). This pins the wiring the parity matrix can't reach — in particular
the FP8 Ultra entry, which no test loads a tokenizer for — so it can't
silently rot.
The two variants:
* ``nemotron-3`` — Nano / Super, shared template. Config exposes ``low_effort``
(honoured on Super, a no-op on Nano).
* ``nemotron-3-ultra`` — Ultra, distinct ``</think>`` glue. Config exposes
``medium_effort``.
Both route to the one ``Nemotron3Renderer`` class, which selects the variant
from ``config.name``.
"""
from types import SimpleNamespace
from renderers.base import MODEL_RENDERER_MAP, RENDERER_REGISTRY, _populate_registry
from renderers.configs import (
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
_config_class_for,
)
from renderers.nemotron3 import Nemotron3Renderer, Nemotron3UltraRenderer, _is_super
_ULTRA_REPOS = [
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8",
]
_NANO_SUPER_REPOS = [
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
]
def _fake_tok(name):
return SimpleNamespace(name_or_path=name)
def test_models_map_to_their_variant():
for repo in _ULTRA_REPOS:
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3-ultra", repo
for repo in _NANO_SUPER_REPOS:
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3", repo
def test_each_discriminator_maps_to_its_config_and_renderer_class():
# Config discriminator → config class.
assert _config_class_for("nemotron-3") is Nemotron3RendererConfig
assert _config_class_for("nemotron-3-ultra") is Nemotron3UltraRendererConfig
# Registry → renderer class (Ultra is a sibling subclass, matching the
# GLM-5/5.1 and Qwen3.5/3.6 house style — not one class under two names).
_populate_registry()
assert RENDERER_REGISTRY["nemotron-3"] is Nemotron3Renderer
assert RENDERER_REGISTRY["nemotron-3-ultra"] is Nemotron3UltraRenderer
assert issubclass(Nemotron3UltraRenderer, Nemotron3Renderer)
def test_variant_is_encoded_by_the_class():
# The ``</think>`` glue is selected by the class hook, not config.name —
# so the right renderer class must be constructed (create_renderer routes
# config.name → class). Default config also follows the class.
assert Nemotron3Renderer._ultra is False
assert Nemotron3UltraRenderer._ultra is True
assert Nemotron3Renderer._config_cls is Nemotron3RendererConfig
assert Nemotron3UltraRenderer._config_cls is Nemotron3UltraRendererConfig
def test_template_fields_per_variant():
# ``low_effort`` lives only on the Nano/Super config; ``medium_effort``
# only on Ultra. Both ARE chat-template kwargs (unlike the removed ``ultra``
# selector), so they appear in the template-field surface.
assert Nemotron3RendererConfig.template_field_names() == frozenset(
{"enable_thinking", "truncate_history_thinking", "low_effort"}
)
assert Nemotron3UltraRendererConfig.template_field_names() == frozenset(
{"enable_thinking", "truncate_history_thinking", "medium_effort"}
)
def test_configs_reject_the_other_variants_effort_kwarg():
# Discriminated-union honesty: a bad combination fails at config-load.
import pytest
from pydantic import ValidationError
with pytest.raises(ValidationError):
Nemotron3RendererConfig(medium_effort=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
Nemotron3UltraRendererConfig(low_effort=True) # type: ignore[call-arg]
# And the removed ``ultra`` selector is gone entirely.
with pytest.raises(ValidationError):
Nemotron3RendererConfig(ultra=True) # type: ignore[call-arg]
def test_is_super_name_detection():
assert _is_super(_fake_tok("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"))
assert not _is_super(_fake_tok("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"))
# Unknown / local-path checkpoints default to False → low_effort no-op.
assert not _is_super(_fake_tok("/home/user/local-ckpt"))
assert not _is_super(SimpleNamespace()) # no name_or_path attr
+139
View File
@@ -98,6 +98,69 @@ def test_qwen3_vl_malformed_tool_call_surfaces_as_invalid_json():
assert tc.token_span is not None
@lru_cache
def _qwen3():
tokenizer = load_tokenizer("Qwen/Qwen3-0.6B")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
def test_qwen3_in_think_tool_call_is_not_a_real_call():
"""A ``<tool_call>`` the model drafts *inside* its ``<think>`` trace must
stay reasoning — only the call emitted after ``</think>`` counts.
Regression for #78: Thinking models (e.g. Qwen3-*-Thinking-2507) draft
tool-call syntax while planning. Because ``<tool_call>`` is a real vocab
token, the parser used to scan the whole stream and emit the in-think
draft *and* the genuine post-``</think>`` call as two tool calls — a
phantom duplicate that made callers execute the same code twice. The scan
is now anchored after ``</think>``, mirroring vLLM's reasoning-then-tools
ordering.
"""
tokenizer, renderer = _qwen3()
text = (
"<think>\nLet me draft the call:\n"
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
"</tool_call>\nYes, that looks right.\n</think>\n"
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
"</tool_call>"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "execute_code"
assert tc.arguments == {"code": "print(1)"}
# The drafted call stays in the reasoning trace, not content.
assert parsed.reasoning_content is not None
assert "<tool_call>" in parsed.reasoning_content
assert parsed.content == ""
def test_qwen3_distinct_parallel_calls_after_think_are_preserved():
"""The fix must not over-correct: two *genuine* parallel calls emitted
after ``</think>`` are still both returned (no dedup), preserving the
faithful-transcription contract for real invocations.
"""
tokenizer, renderer = _qwen3()
text = (
"<think>\nplan\n</think>\n"
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
"</tool_call>\n"
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(2)"}}\n'
"</tool_call>"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert len(parsed.tool_calls) == 2
assert [tc.arguments for tc in parsed.tool_calls] == [
{"code": "print(1)"},
{"code": "print(2)"},
]
assert parsed.reasoning_content == "plan"
@lru_cache
def _kimi_k25():
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
@@ -135,3 +198,79 @@ def test_kimi_k25_tool_call_carries_token_span():
assert 0 <= start < end <= len(token_ids), (
f"span {tc.token_span} out of range for {len(token_ids)} input tokens"
)
def test_kimi_k25_in_think_section_is_not_a_real_call():
"""A tool-call section the model drafts inside its ``<think>`` trace must
not be parsed — only the section after ``</think>`` counts.
Regression for #78. K2.5's failure mode differed from Qwen3's: the
in-think section tripped the "truncated reasoning" guard and the parser
*dropped every tool call* (returned zero), losing the genuine call. The
scan is now anchored past ``</think>``.
"""
tokenizer, renderer = _kimi_k25()
section = (
"<|tool_calls_section_begin|>"
"<|tool_call_begin|>functions.execute_code:0"
'<|tool_call_argument_begin|>{"code": "print(1)"}'
"<|tool_call_end|><|tool_calls_section_end|>"
)
text = f"<think>\nLet me draft:\n{section}\nlooks right.\n</think>\nGo.\n{section}"
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "execute_code"
assert tc.arguments == {"code": "print(1)"}
# The drafted section stays in the reasoning trace.
assert parsed.reasoning_content is not None
assert "<|tool_calls_section_begin|>" in parsed.reasoning_content
assert parsed.content == "Go."
@lru_cache
def _deepseek_v3():
tokenizer = load_tokenizer("deepseek-ai/DeepSeek-V3")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
def test_deepseek_v3_in_think_section_is_not_a_real_call():
"""A tool-call section drafted inside ``<think>`` must not be parsed —
only the section after ``</think>`` counts.
Regression for #78. DeepSeek-V3's failure mode: it returned the *wrong*
call (the in-think draft) and lost reasoning, because ``</think>`` is
multi-token text there and the scan wasn't anchored past it.
"""
tokenizer, renderer = _deepseek_v3()
def section(name: str) -> str:
return (
"<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>"
f'{name}\n```json\n{{"code": "print(1)"}}\n```'
"<|tool▁call▁end|><|tool▁calls▁end|>"
)
text = (
f"<think>\nLet me draft:\n{section('draft_tool')}\nlooks right.\n</think>\n"
f"Go.\n{section('real_tool')}"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
# Assert the *post-``</think>``* section was chosen, not the in-think draft.
# (Use ``startswith`` rather than ``== "real_tool"``: under transformers
# 5.x the DeepSeek tokenizer's decode drops the ``\n`` between name and the
# ```json fence, so ``_parse_deepseek_tool_calls`` folds the fence into the
# name — a pre-existing, #78-unrelated quirk. What matters here is *which*
# section won.)
assert tc.name is not None and tc.name.startswith("real_tool")
assert "draft_tool" not in tc.name
# The drafted section stays in the reasoning trace, not content.
assert parsed.reasoning_content is not None
assert "draft_tool" in parsed.reasoning_content
assert parsed.content == "Go."
+6
View File
@@ -51,6 +51,9 @@ NO_OP_MODELS = {
"Qwen/Qwen3-VL-8B-Instruct",
"Qwen/Qwen3-VL-30B-A3B-Instruct",
"poolside/Laguna-XS.2",
# Llama-3 has no reasoning channel at all — preserve flags can't add
# or drop anything, so they're pure no-ops.
"unsloth/Llama-3.2-1B-Instruct",
}
@@ -319,6 +322,9 @@ NEVER_PRESERVES_MODELS = {
"Qwen/Qwen3-VL-4B-Instruct",
"Qwen/Qwen3-VL-8B-Instruct",
"Qwen/Qwen3-VL-30B-A3B-Instruct",
# Llama-3 ships no <think> rendering path, so reasoning_content never
# surfaces in the output regardless of the preserve flags.
"unsloth/Llama-3.2-1B-Instruct",
}
+32 -9
View File
@@ -5,9 +5,8 @@ Seven Qwen3.5 sizes route to ``Qwen35Renderer``. The 4B / 9B / 35B-A3B /
``enable_thinking=true``); the smaller 0.8B / 2B sizes ship the polarity-
flipped variant (default ``enable_thinking=false`` → empty
``<think>\\n\\n</think>\\n\\n`` at the gen-prompt boundary). The renderer
detects polarity from the tokenizer's chat_template at construction, so
both variants render byte-identical to their own
``apply_chat_template``.
hard-codes this polarity per model (``_ENABLE_THINKING_DEFAULTS``), so
both variants render byte-identical to their own ``apply_chat_template``.
These tests lock in (a) the exact set of Qwen3.5 sizes in the map and
(b) byte parity for every one of them across representative
@@ -57,7 +56,7 @@ def test_no_other_qwen35_sizes_silently_added():
# ---------------------------------------------------------------------------
# Polarity auto-detection: 0.8B / 2B flip ``enable_thinking`` default.
# Polarity defaults: 0.8B / 2B flip ``enable_thinking`` default.
# ---------------------------------------------------------------------------
@@ -73,10 +72,10 @@ def test_no_other_qwen35_sizes_silently_added():
("Qwen/Qwen3.5-397B-A17B", True),
],
)
def test_qwen35_enable_thinking_polarity_autodetected(qwen35_model, expected_default):
"""The renderer's ``_enable_thinking`` resolves to the chat template's
own default when no explicit flag is passed — so big / small sizes
each match their own template at the gen-prompt boundary."""
def test_qwen35_enable_thinking_polarity_default(qwen35_model, expected_default):
"""With no explicit flag, the renderer resolves ``enable_thinking`` from
the hard-coded per-model default — so big / small sizes each match their
own template at the gen-prompt boundary."""
tok = load_tokenizer(qwen35_model)
renderer = create_renderer(tok, Qwen35RendererConfig())
assert isinstance(renderer, Qwen35Renderer)
@@ -86,6 +85,30 @@ def test_qwen35_enable_thinking_polarity_autodetected(qwen35_model, expected_def
)
def test_construction_does_not_call_apply_chat_template():
"""The ``enable_thinking`` default is hard-coded per model, so building a
``Qwen35Renderer`` must not probe ``apply_chat_template`` — a
bring-your-own tokenizer with no chat-template support still works."""
class _Stub:
name_or_path = "Qwen/Qwen3.5-0.8B"
unk_token_id = -1
def convert_tokens_to_ids(self, token):
# Any stable non-unk id per token; the renderer only needs the
# special tokens to resolve to distinct, in-vocab ids.
return abs(hash(token)) % 1_000_000 + 1
def apply_chat_template(self, *args, **kwargs):
raise AssertionError(
"apply_chat_template must not be called at construction"
)
renderer = Qwen35Renderer(_Stub())
# 0.8B is a small size → thinking defaults off, from the hard-coded table.
assert renderer.config.enable_thinking is False
# ---------------------------------------------------------------------------
# Byte parity for each in-map Qwen3.5 size.
# ---------------------------------------------------------------------------
@@ -146,7 +169,7 @@ def test_qwen35_size_parity_with_apply_chat_template(
"""Each in-map Qwen3.5 size renders byte-identical to its own
``apply_chat_template`` output. Locks in the property that lets us
share ``Qwen35Renderer`` across all seven sizes — the polarity
flip on 0.8B / 2B is absorbed by the constructor's auto-detect."""
flip on 0.8B / 2B is absorbed by the per-model default."""
tok = load_tokenizer(qwen35_model)
renderer = create_renderer(tok, Qwen35RendererConfig())
assert isinstance(renderer, Qwen35Renderer)
+14
View File
@@ -54,7 +54,15 @@ _RENDERER_MODELS = [
("moonshotai/Kimi-K2.5", "auto"),
("moonshotai/Kimi-K2.6", "auto"),
("deepseek-ai/DeepSeek-V3", "auto"),
("deepseek-ai/DeepSeek-R1", "auto"),
# Nano + Super share the ``nemotron-3`` config (incl. ``low_effort``, which
# fires only on Super); both are exercised so the kwarg is checked where it
# no-ops (Nano) AND where it appends (Super).
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
# Ultra: auto-resolves to the ``nemotron-3-ultra`` config via the model
# name; parity asserted against the Ultra apply_chat_template (``medium_effort``).
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
("poolside/Laguna-XS.2", "auto"),
("openai/gpt-oss-20b", "gpt-oss"),
]
@@ -81,6 +89,12 @@ _KWARG_VALUES: dict[str, list[Any]] = {
# ``truncate_history_thinking=False`` keeps reasoning on historical
# assistants instead of collapsing to ``<think></think>``.
"truncate_history_thinking": [True, False],
# Nemotron-3 reasoning-effort hints appended to the last user message.
# ``low_effort`` is a Super (``nemotron-3``) kwarg; ``medium_effort`` an
# Ultra (``nemotron-3-ultra``) kwarg. On the variant that doesn't define
# the kwarg the template — and the renderer — no-op it.
"low_effort": [True, False],
"medium_effort": [True, False],
# MiniMax-M2 — fallback persona string when no system message is
# supplied. Two arbitrary values to verify the renderer threads the
# exact bytes through (whitespace included).
+10
View File
@@ -43,7 +43,11 @@ _ROUNDTRIP_MODELS = [
("moonshotai/Kimi-K2.6", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
# Ultra: parse must recover content after a </think> glued directly to it
# (no separating newline) — the Ultra-specific glue stresses the round-trip.
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
("poolside/Laguna-XS.2", "auto"),
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
("openai/gpt-oss-20b", "gpt-oss"),
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
]
@@ -207,6 +211,12 @@ def test_roundtrip_multiple_tool_calls(
"""Parsers that loop over ``<tool_call>…</tool_call>`` blocks can
silently drop the second one; this test catches that."""
_maybe_skip_tool_calls(rt_renderer_name)
if rt_renderer_name == "llama-3":
pytest.skip(
"Llama-3's chat template forbids >1 tool call per assistant "
"message (the renderer raises, mirroring the template); the "
"single-call path is covered by test_roundtrip_single_tool_call."
)
msg = {
"role": "assistant",