feat(base): add RenderedTokens.sampled_mask for SFT/RL parity (#33)

This commit is contained in:
hallerite
2026-05-14 19:17:30 +02:00
committed by GitHub
parent 562db77eff
commit 01aeb004b8
14 changed files with 1144 additions and 537 deletions
+35 -3
View File
@@ -148,8 +148,26 @@ class RenderedTokens:
"""Result of rendering messages to tokens.
Each token carries an index into the original message list so callers can
build per-token loss masks without re-rendering. Tokens from structural
scaffolding (generation prompt, im_start/im_end wrapping) carry index -1.
build per-token loss masks without re-rendering. Tokens from structural
scaffolding the renderer adds outside any single message (e.g. the
trailing generation prompt) carry index ``-1``.
``sampled_mask`` is a separate per-token signal: ``True`` if the model
would have produced this token at inference time (i.e. it appears in
the sampled completion), ``False`` if it is template-injected
scaffolding the model never emits (``<|im_start|>role\\n`` openers,
inter-turn ``\\n`` separators, system / user / tool content from
conversation history, etc.). This is distinct from
``message_indices``: a token can belong to an assistant message
(``message_indices[k] >= 0``) and still be scaffolding the template
adds around the model's actual completion. SFT loss masks should AND
both: train on tokens whose role is trainable AND that the model
would actually sample.
Empty ``sampled_mask`` (``[]``) means the renderer doesn't provide
this signal — consumers should fall back to attribution-only
masking. ``DefaultRenderer`` leaves it empty because the Jinja
template is opaque; hand-coded renderers populate it.
``multi_modal_data`` is populated by multimodal renderers (e.g.
``Qwen3VLRenderer``) when image / video content parts are present;
@@ -158,6 +176,7 @@ class RenderedTokens:
token_ids: list[int] = field(default_factory=list)
message_indices: list[int] = field(default_factory=list)
sampled_mask: list[bool] = field(default_factory=list)
multi_modal_data: "MultiModalData | None" = None
@@ -947,12 +966,25 @@ 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).
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.
"""
rendered = renderer.render(messages, tools=tools)
has_sampled_info = len(rendered.sampled_mask) == len(rendered.token_ids)
loss_mask: list[bool] = []
for msg_idx in rendered.message_indices:
for k, msg_idx in enumerate(rendered.message_indices):
if msg_idx < 0:
loss_mask.append(False)
elif has_sampled_info and not rendered.sampled_mask[k]:
loss_mask.append(False)
else:
loss_mask.append(role_to_mask(messages[msg_idx]))
return rendered.token_ids, loss_mask
+59 -31
View File
@@ -113,20 +113,23 @@ class DeepSeekV3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
# ── 1. BOS token ─────────────────────────────────────────────
emit_special(self._bos, -1)
emit_special(self._bos, -1, is_sampled=False)
# ── 2. Collect system messages at the start ───────────────────
# All leading system messages are concatenated with "\n\n" and emitted
@@ -148,7 +151,7 @@ class DeepSeekV3Renderer:
if sys_parts:
# Attribute the concatenated system text to the first system message (index 0).
emit_text("\n\n".join(sys_parts), 0)
emit_text("\n\n".join(sys_parts), 0, is_sampled=False)
# ── 3. Render non-system messages ─────────────────────────────
num_messages = len(messages)
@@ -163,8 +166,8 @@ class DeepSeekV3Renderer:
content = "".join(
p.get("text", "") for p in content if isinstance(p, dict)
)
emit_special(self._user_token, i)
emit_text(str(content), i)
emit_special(self._user_token, i, is_sampled=False)
emit_text(str(content), i, is_sampled=False)
elif role == "user":
content = msg.get("content") or ""
@@ -177,8 +180,8 @@ class DeepSeekV3Renderer:
else ""
for p in content
)
emit_special(self._user_token, i)
emit_text(str(content), i)
emit_special(self._user_token, i, is_sampled=False)
emit_text(str(content), i, is_sampled=False)
elif role == "assistant":
self._render_assistant(
@@ -202,11 +205,13 @@ class DeepSeekV3Renderer:
# Don't add <|Assistant|> after tool outputs — content flows directly.
last_role = messages[-1]["role"] if messages else None
if last_role != "tool":
emit_special(self._assistant_token, -1)
emit_special(self._assistant_token, -1, is_sampled=False)
if self._enable_thinking:
emit_text("<think>\n", -1)
emit_text("<think>\n", -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
@@ -267,10 +272,20 @@ class DeepSeekV3Renderer:
ext: list[int] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.extend(self._encode(text))
for i, msg in enumerate(new_messages):
@@ -354,17 +369,24 @@ class DeepSeekV3Renderer:
tool_calls = msg.get("tool_calls") or []
# ``<|Assistant|>`` is template-injected scaffolding — at
# inference the chat template emits it as the generation prompt
# and the model never samples it. Marking it ``is_sampled=False``
# keeps the SFT loss mask aligned with what the model would
# actually have produced. When the previous message is a tool
# response, the template skips this token entirely (content
# flows directly out of ``<|tool▁outputs▁end|>``).
if not prev_is_tool:
emit_special(self._assistant_token, msg_idx)
emit_special(self._assistant_token, msg_idx, is_sampled=False)
if not tool_calls:
emit_text(content, msg_idx)
emit_text(content, msg_idx, is_sampled=True)
else:
# Emit any pre-tool-call content first.
emit_text(content, msg_idx)
emit_text(content, msg_idx, is_sampled=True)
# Tool call section.
emit_special(self._tool_calls_begin, msg_idx)
emit_special(self._tool_calls_begin, msg_idx, is_sampled=True)
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
@@ -376,14 +398,17 @@ class DeepSeekV3Renderer:
)
# Format: <|tool▁call▁begin|>function<|tool▁sep|>{name}\n```json\n{args}\n```<|tool▁call▁end|>
# tool_sep is a special token; type ("function") and name+args are plain text.
emit_special(self._tool_call_begin, msg_idx)
emit_text("function", msg_idx)
emit_special(self._tool_sep, msg_idx)
emit_text(f"{name}\n```json\n{args_str}\n```", msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_end, msg_idx)
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text("function", msg_idx, is_sampled=True)
emit_special(self._tool_sep, msg_idx, is_sampled=True)
emit_text(f"{name}\n```json\n{args_str}\n```", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_end, msg_idx, is_sampled=True)
emit_special(self._eos, msg_idx)
# ``<|end▁of▁sentence|>`` is the model's stop signal — it
# samples this to end its turn, so it is part of the sampled
# stream.
emit_special(self._eos, msg_idx, is_sampled=True)
# ------------------------------------------------------------------
# Tool (tool-response) rendering
@@ -397,6 +422,9 @@ class DeepSeekV3Renderer:
emit_special,
emit_text,
) -> 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.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
@@ -407,11 +435,11 @@ class DeepSeekV3Renderer:
content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
if not prev_is_tool:
emit_special(self._tool_outputs_begin, msg_idx)
emit_special(self._tool_outputs_begin, msg_idx, is_sampled=False)
emit_special(self._tool_output_begin, msg_idx)
emit_text(str(content), msg_idx)
emit_special(self._tool_output_end, msg_idx)
emit_special(self._tool_output_begin, msg_idx, is_sampled=False)
emit_text(str(content), msg_idx, is_sampled=False)
emit_special(self._tool_output_end, msg_idx, is_sampled=False)
if not next_is_tool:
emit_special(self._tool_outputs_end, msg_idx)
emit_special(self._tool_outputs_end, msg_idx, is_sampled=False)
+81 -42
View File
@@ -127,28 +127,31 @@ class GLM45Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
# ── Prefix ──────────────────────────────────────────────────
emit_special(self._gmask, -1)
emit_special(self._sop, -1)
emit_special(self._gmask, -1, is_sampled=False)
emit_special(self._sop, -1, is_sampled=False)
# ── Tools in system prompt ──────────────────────────────────
if tools:
emit_special(self._system, -1)
emit_special(self._system, -1, is_sampled=False)
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
tool_text += _TOOLS_FOOTER
emit_text(tool_text, -1)
emit_text(tool_text, -1, is_sampled=False)
# ── Compute last_user_index ─────────────────────────────────
last_ui = self._last_user_index(messages)
@@ -159,15 +162,15 @@ class GLM45Renderer:
content = self._visible_text(msg.get("content"))
if role == "system":
emit_special(self._system, i)
emit_text("\n" + content, i)
emit_special(self._system, i, is_sampled=False)
emit_text("\n" + content, i, is_sampled=False)
elif role == "user":
emit_special(self._user, i)
emit_special(self._user, i, is_sampled=False)
user_text = "\n" + content
if not self._enable_thinking and not content.endswith("/nothink"):
user_text += "/nothink"
emit_text(user_text, i)
emit_text(user_text, i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -193,13 +196,15 @@ class GLM45Renderer:
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._assistant, -1)
emit_special(self._assistant, -1, is_sampled=False)
if not self._enable_thinking:
emit_text("\n", -1)
emit_special(self._think, -1)
emit_special(self._think_end, -1)
emit_text("\n", -1, is_sampled=False)
emit_special(self._think, -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
@@ -267,10 +272,20 @@ class GLM45Renderer:
ext: list[int] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.extend(self._encode(text))
for i, msg in enumerate(new_messages):
@@ -328,24 +343,37 @@ class GLM45Renderer:
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._assistant, msg_idx)
# ``<|assistant|>\n`` is template-injected scaffolding — at
# inference the chat template emits these as the generation
# prompt and the model never samples them. Everything after
# (think block + content + tool calls) is the model-sampled
# portion.
#
# GLM-4.5 does NOT emit an explicit per-turn close token inside
# the assistant message; the next message's role marker
# (``<|user|>`` / ``<|observation|>`` / ``<|endoftext|>``) acts
# as the stop signal at inference, and those tokens are
# attributed to the *next* message (or are absent on the final
# turn). So no sampled stop-signal token lives inside this
# assistant span — content / think / tool_calls carry the
# is_sampled=True signal.
emit_special(self._assistant, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
if (msg_idx > last_user_index or preserve_thinking) and reasoning_content:
emit_text("\n", msg_idx)
emit_special(self._think, msg_idx)
emit_text(reasoning_content.strip(), msg_idx)
emit_special(self._think_end, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_text(reasoning_content.strip(), msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
else:
emit_text("\n", msg_idx)
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
# Tool calls — keep content + \n contiguous to preserve BPE merges
tool_calls = msg.get("tool_calls") or []
if content.strip() and tool_calls:
emit_text("\n" + content.strip() + "\n", msg_idx)
emit_text("\n" + content.strip() + "\n", msg_idx, is_sampled=True)
elif content.strip():
emit_text("\n" + content.strip(), msg_idx)
emit_text("\n" + content.strip(), msg_idx, is_sampled=True)
for tc in tool_calls:
func = tc.get("function") or tc
@@ -353,9 +381,9 @@ class GLM45Renderer:
arguments = func.get("arguments", {})
if not content.strip():
emit_text("\n", msg_idx)
emit_special(self._tool_call_tok, msg_idx)
emit_text(name + "\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_tok, msg_idx, is_sampled=True)
emit_text(name + "\n", msg_idx, is_sampled=True)
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
@@ -365,18 +393,22 @@ class GLM45Renderer:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
emit_special(self._arg_key, msg_idx)
emit_text(arg_name, msg_idx)
emit_special(self._arg_key_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._arg_value, msg_idx)
emit_special(self._arg_key, msg_idx, is_sampled=True)
emit_text(arg_name, msg_idx, is_sampled=True)
emit_special(self._arg_key_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._arg_value, msg_idx, is_sampled=True)
if isinstance(arg_value, str):
emit_text(arg_value, msg_idx)
emit_text(arg_value, msg_idx, is_sampled=True)
else:
emit_text(json.dumps(arg_value, ensure_ascii=False), msg_idx)
emit_special(self._arg_value_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._tool_call_end_tok, msg_idx)
emit_text(
json.dumps(arg_value, ensure_ascii=False),
msg_idx,
is_sampled=True,
)
emit_special(self._arg_value_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, msg_idx, is_sampled=True)
def _render_tool(
self,
@@ -387,9 +419,16 @@ class GLM45Renderer:
emit_special,
emit_text,
) -> 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.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
if not prev_is_tool:
emit_special(self._observation, msg_idx)
emit_special(self._observation, msg_idx, is_sampled=False)
emit_text("\n<tool_response>\n" + content + "\n</tool_response>", msg_idx)
emit_text(
"\n<tool_response>\n" + content + "\n</tool_response>",
msg_idx,
is_sampled=False,
)
+82 -39
View File
@@ -142,28 +142,33 @@ class GLM5Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
# ── Prefix ──────────────────────────────────────────────────
emit_special(self._gmask, -1)
emit_special(self._sop, -1)
# ``[gMASK]<sop>`` is unconditional template scaffolding at the
# very start of the stream — the model never samples these.
emit_special(self._gmask, -1, is_sampled=False)
emit_special(self._sop, -1, is_sampled=False)
# ── Tools in system prompt ──────────────────────────────────
if tools:
emit_special(self._system, -1)
emit_special(self._system, -1, is_sampled=False)
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += self._format_tool_spec(tool) + "\n"
tool_text += _TOOLS_FOOTER
emit_text(tool_text, -1)
emit_text(tool_text, -1, is_sampled=False)
# ── Compute last_user_index ─────────────────────────────────
last_ui = self._last_user_index(messages)
@@ -174,12 +179,12 @@ class GLM5Renderer:
content = self._visible_text(msg.get("content"))
if role == "system":
emit_special(self._system, i)
emit_text(content, i)
emit_special(self._system, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
elif role == "user":
emit_special(self._user, i)
emit_text(content, i)
emit_special(self._user, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -204,14 +209,19 @@ class GLM5Renderer:
)
# ── Generation prompt ───────────────────────────────────────
# Gen prompt tokens are what the chat template prepends before
# sampling starts — the model continues from these, never emits
# them. Always is_sampled=False.
if add_generation_prompt:
emit_special(self._assistant, -1)
emit_special(self._assistant, -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1)
emit_special(self._think, -1, is_sampled=False)
else:
emit_special(self._think_end, -1)
emit_special(self._think_end, -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
@@ -283,10 +293,20 @@ class GLM5Renderer:
ext: list[int] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_assistant`` /
# ``_render_tool`` and ignore it; the returned ``RenderedTokens``
# leaves ``sampled_mask`` empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.extend(self._encode(text))
for i, msg in enumerate(new_messages):
@@ -345,7 +365,12 @@ class GLM5Renderer:
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._assistant, msg_idx)
# ``<|assistant|>`` is template-injected: the chat template emits
# it as the generation prompt at inference, and the model never
# samples it. Same for the ``<think>`` open / standalone
# ``</think>`` separator that the template wraps around the
# assistant body — see the per-branch comments below.
emit_special(self._assistant, msg_idx, is_sampled=False)
# Chat-template default: keep ``<think>`` only on the in-flight cycle
# (post-last-user). Past-cycle assistants drop their reasoning.
@@ -358,19 +383,30 @@ class GLM5Renderer:
) and reasoning_content
if include_thinking:
emit_special(self._think, msg_idx)
emit_text(reasoning_content.strip(), msg_idx)
emit_special(self._think_end, msg_idx)
# ``<think>`` matches the gen-prompt's trailing token at
# inference (gen prompt = ``<|assistant|><think>``), so it's
# template-injected scaffolding. The reasoning text and the
# closing ``</think>`` are what the model actually samples.
emit_special(self._think, msg_idx, is_sampled=False)
emit_text(reasoning_content.strip(), msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
elif self.empty_think_on_last_assistant and msg_idx > last_user_index:
# GLM-5.1: wrap the last assistant with an empty <think></think>
# even without reasoning, matching the Jinja template.
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
# even without reasoning, matching the Jinja template. With
# ``enable_thinking=True`` the gen prompt already includes
# ``<think>``; the model then samples ``</think>`` to close an
# empty think block. So ``<think>`` is scaffolding,
# ``</think>`` is sampled.
emit_special(self._think, msg_idx, is_sampled=False)
emit_special(self._think_end, msg_idx, is_sampled=True)
else:
emit_special(self._think_end, msg_idx)
# Lone ``</think>`` separator the template injects when no
# reasoning is rendered (historical assistants, GLM-5 default
# with no thinking). Not sampled.
emit_special(self._think_end, msg_idx, is_sampled=False)
if content.strip():
emit_text(content.strip(), msg_idx)
emit_text(content.strip(), msg_idx, is_sampled=True)
# Tool calls (directly after content, no newlines)
tool_calls = msg.get("tool_calls") or []
@@ -379,8 +415,8 @@ class GLM5Renderer:
name = func.get("name", "")
arguments = func.get("arguments", {})
emit_special(self._tool_call_tok, msg_idx)
emit_text(name, msg_idx)
emit_special(self._tool_call_tok, msg_idx, is_sampled=True)
emit_text(name, msg_idx, is_sampled=True)
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
@@ -390,16 +426,20 @@ class GLM5Renderer:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
emit_special(self._arg_key, msg_idx)
emit_text(arg_name, msg_idx)
emit_special(self._arg_key_end, msg_idx)
emit_special(self._arg_value, msg_idx)
emit_special(self._arg_key, msg_idx, is_sampled=True)
emit_text(arg_name, msg_idx, is_sampled=True)
emit_special(self._arg_key_end, msg_idx, is_sampled=True)
emit_special(self._arg_value, msg_idx, is_sampled=True)
if isinstance(arg_value, str):
emit_text(arg_value, msg_idx)
emit_text(arg_value, msg_idx, is_sampled=True)
else:
emit_text(json.dumps(arg_value, ensure_ascii=False), msg_idx)
emit_special(self._arg_value_end, msg_idx)
emit_special(self._tool_call_end_tok, msg_idx)
emit_text(
json.dumps(arg_value, ensure_ascii=False),
msg_idx,
is_sampled=True,
)
emit_special(self._arg_value_end, msg_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, msg_idx, is_sampled=True)
def _render_tool(
self,
@@ -410,14 +450,17 @@ class GLM5Renderer:
emit_special,
emit_text,
) -> 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.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
if not prev_is_tool:
emit_special(self._observation, msg_idx)
emit_special(self._observation, msg_idx, is_sampled=False)
emit_special(self._tool_response_tok, msg_idx)
emit_text(content, msg_idx)
emit_special(self._tool_response_end_tok, msg_idx)
emit_special(self._tool_response_tok, msg_idx, is_sampled=False)
emit_text(content, msg_idx, is_sampled=False)
emit_special(self._tool_response_end_tok, msg_idx, is_sampled=False)
class GLM51Renderer(GLM5Renderer):
+53 -11
View File
@@ -198,10 +198,45 @@ class GptOssRenderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit(ids: list[int], msg_idx: int) -> None:
def emit(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_harmony_message(
hm_ids: list[int], msg_idx: int, *, is_assistant: bool
) -> None:
"""Emit one harmony-rendered message, splitting its tokens into
template scaffolding vs model-sampled content.
Harmony per-message layout:
<|start|> role [' to=' recipient] [<|channel|> name] <|message|>
<body...>
<|end|> | <|return|> | <|call|>
Everything up to and including ``<|message|>`` is the
generation-prompt header the template injects before the
model starts sampling. For assistant turns the body and the
terminator (``<|end|>`` / ``<|return|>`` / ``<|call|>``) are
what the model actually produces, so they are
``is_sampled=True``. For non-assistant turns (user, system,
developer, tool) the whole message is conversation history
the model never samples — every token is
``is_sampled=False``.
"""
try:
msg_marker = hm_ids.index(self._message)
except ValueError:
# Defensive: a harmony message without <|message|> is
# malformed. Treat the whole thing as scaffolding.
emit(hm_ids, msg_idx, is_sampled=False)
return
header = hm_ids[: msg_marker + 1]
body = hm_ids[msg_marker + 1 :]
emit(header, msg_idx, is_sampled=False)
emit(body, msg_idx, is_sampled=is_assistant)
# ── Build harmony prefix (system + developer) ───────────────────
# When tools are present, harmony's conversation-level renderer
@@ -248,15 +283,17 @@ class GptOssRenderer:
# Attribute the whole prefix block to first_system_idx if the
# caller supplied a system message (so its content has *some*
# caller-relative attribution); otherwise to -1 (pure scaffolding).
# The whole prefix is pure template scaffolding — never sampled.
prefix_origin = first_system_idx if first_system_idx is not None else -1
emit(prefix_tokens, prefix_origin)
emit(prefix_tokens, prefix_origin, is_sampled=False)
# ── Iterate the rest of the messages ────────────────────────────
last_idx = len(messages) - 1
for i, msg in enumerate(messages):
if i == first_system_idx:
continue # already emitted as developer
preserve_thinking = msg.get("role") == "assistant" and (
is_assistant = msg.get("role") == "assistant"
preserve_thinking = is_assistant and (
should_preserve_past_thinking(
messages,
i,
@@ -267,13 +304,15 @@ class GptOssRenderer:
for hm in self._to_harmony_messages(
msg, preserve_thinking=preserve_thinking
):
emit(self._enc.render(hm), i)
emit_harmony_message(self._enc.render(hm), i, is_assistant=is_assistant)
# When the conversation ends on an assistant final-channel turn,
# ``apply_chat_template`` (and ``render_conversation_for_training``)
# close it with ``<|return|>`` instead of ``<|end|>`` to mark the
# final assistant turn as terminal. Per-message rendering always
# uses ``<|end|>``, so patch it here when applicable.
# uses ``<|end|>``, so patch it here when applicable. The sampled
# bit on the terminator slot stays True — both ``<|end|>`` and
# ``<|return|>`` are stop signals the model emits.
if (
not add_generation_prompt
and last_idx >= 0
@@ -285,14 +324,17 @@ class GptOssRenderer:
tokens[-1] = self._return
# ── Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
# Pure template scaffolding the model continues from — never sampled.
if add_generation_prompt:
emit([self._start], -1)
emit(self._encode("assistant"), -1)
emit([self._channel], -1)
emit(self._encode("analysis"), -1)
emit([self._message], -1)
emit([self._start], -1, is_sampled=False)
emit(self._encode("assistant"), -1, is_sampled=False)
emit([self._channel], -1, is_sampled=False)
emit(self._encode("analysis"), -1, is_sampled=False)
emit([self._message], -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
+89 -63
View File
@@ -165,17 +165,20 @@ class KimiK2Renderer:
token_ids: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
token_ids.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
token_ids.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
# Compute last non-tool-call assistant index to determine thinking preservation
last_plain_assistant_idx = -1
@@ -205,29 +208,29 @@ class KimiK2Renderer:
oi = orig_idx(i)
if role == "system":
emit_special(self._im_system, oi)
emit_text("system", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
emit_special(self._im_system, oi, is_sampled=False)
emit_text("system", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
# Jinja emits a literal newline only after the auto-injected
# system's <|im_end|> (see _ensure_system_message's contract).
if i == auto_system_idx:
emit_text("\n", oi)
emit_text("\n", oi, is_sampled=False)
elif role == "tool_declare":
emit_special(self._im_system, oi)
emit_text("tool_declare", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
emit_special(self._im_system, oi, is_sampled=False)
emit_text("tool_declare", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
elif role == "user":
emit_special(self._im_user, oi)
emit_text("user", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
emit_special(self._im_user, oi, is_sampled=False)
emit_text("user", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
elif role == "assistant":
# Kimi strips reasoning from historical assistant turns and
@@ -251,20 +254,24 @@ class KimiK2Renderer:
)
else:
# Unknown role: use system-style formatting
emit_special(self._im_system, oi)
emit_text(role, oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
# Unknown role: use system-style formatting. Not a sampled
# assistant turn — every token is template-injected from the
# caller's POV, so is_sampled=False across the whole emission.
emit_special(self._im_system, oi, is_sampled=False)
emit_text(role, oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
# Generation prompt
if add_generation_prompt:
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
return RenderedTokens(token_ids=token_ids, message_indices=indices)
return RenderedTokens(
token_ids=token_ids, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
@@ -325,10 +332,19 @@ class KimiK2Renderer:
ext: list[int] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the caller
# blanket-masks it via ``prompt_mask=[False]*N``, so we don't track
# sampled_mask here. Local helpers accept the kwarg for signature
# compatibility with ``_render_tool`` and ignore it; the returned
# ``RenderedTokens`` leaves ``sampled_mask`` empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.extend(self._encode(text))
for i, msg in enumerate(new_messages):
@@ -349,17 +365,17 @@ class KimiK2Renderer:
content = "".join(parts)
if role == "user":
emit_special(self._im_user, i)
emit_text("user", i)
emit_special(self._im_middle, i)
emit_text(content, i)
emit_special(self._im_end, i)
emit_special(self._im_user, i, is_sampled=False)
emit_text("user", i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
elif role == "system":
emit_special(self._im_system, i)
emit_text("system", i)
emit_special(self._im_middle, i)
emit_text(content, i)
emit_special(self._im_end, i)
emit_special(self._im_system, i, is_sampled=False)
emit_text("system", i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
elif role == "tool":
self._render_tool(
msg, i, content, emit_special=emit_special, emit_text=emit_text
@@ -368,9 +384,9 @@ class KimiK2Renderer:
return None
# Generation prompt.
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
return RenderedTokens(token_ids=previous_ids + ext)
@@ -384,9 +400,14 @@ class KimiK2Renderer:
emit_special,
emit_text,
) -> None:
emit_special(self._im_assistant, msg_idx)
emit_text("assistant", msg_idx)
emit_special(self._im_middle, msg_idx)
# ``<|im_assistant|>assistant<|im_middle|>`` 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 as ``is_sampled=False`` keeps the SFT loss mask aligned
# with what the model would actually have produced.
emit_special(self._im_assistant, msg_idx, is_sampled=False)
emit_text("assistant", msg_idx, is_sampled=False)
emit_special(self._im_middle, msg_idx, is_sampled=False)
# Kimi K2's Jinja template has no reasoning-content support: the
# assistant turn renders its ``content`` verbatim, including any
@@ -394,12 +415,12 @@ class KimiK2Renderer:
# ``reasoning_content`` field is dropped (the template never reads
# it). ``is_last_turn`` is unused here for the same reason.
_ = is_last_turn
emit_text(content, msg_idx)
emit_text(content, msg_idx, is_sampled=True)
# Tool calls
tool_calls = msg.get("tool_calls") or []
if tool_calls:
emit_special(self._tool_calls_section_begin, msg_idx)
emit_special(self._tool_calls_section_begin, msg_idx, is_sampled=True)
for tc in tool_calls:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
@@ -413,14 +434,16 @@ class KimiK2Renderer:
# caller to provide an id in ``functions.{name}:{idx}`` form
# (that's where the Kimi parser recovers the function name).
tc_id = tc.get("id") or ""
emit_special(self._tool_call_begin, msg_idx)
emit_text(tc_id, msg_idx)
emit_special(self._tool_call_argument_begin, msg_idx)
emit_text(args_str, msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_section_end, msg_idx)
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text(tc_id, msg_idx, is_sampled=True)
emit_special(self._tool_call_argument_begin, msg_idx, is_sampled=True)
emit_text(args_str, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_section_end, msg_idx, is_sampled=True)
emit_special(self._im_end, msg_idx)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream.
emit_special(self._im_end, msg_idx, is_sampled=True)
def _render_tool(
self,
@@ -431,12 +454,15 @@ class KimiK2Renderer:
emit_special,
emit_text,
) -> 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.
name = msg.get("name") or "tool"
tool_call_id = msg.get("tool_call_id") or ""
emit_special(self._im_system, msg_idx)
emit_text(name, msg_idx)
emit_special(self._im_middle, msg_idx)
emit_text(f"## Return of {tool_call_id}\n", msg_idx)
emit_text(content, msg_idx)
emit_special(self._im_end, msg_idx)
emit_special(self._im_system, msg_idx, is_sampled=False)
emit_text(name, msg_idx, is_sampled=False)
emit_special(self._im_middle, msg_idx, is_sampled=False)
emit_text(f"## Return of {tool_call_id}\n", msg_idx, is_sampled=False)
emit_text(content, msg_idx, is_sampled=False)
emit_special(self._im_end, msg_idx, is_sampled=False)
+92 -50
View File
@@ -748,22 +748,25 @@ class KimiK25Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
mm_hashes: dict[str, list[str]] = {}
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
mm_items: dict[str, list[dict[str, Any]]] = {}
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_image(part: dict[str, Any], msg_idx: int) -> None:
def emit_image(part: dict[str, Any], msg_idx: int, *, is_sampled: bool) -> None:
"""Emit Kimi K2.5's image wrap and accumulate ``mm_data``.
Template-equivalent expansion per image:
@@ -778,13 +781,13 @@ class KimiK25Renderer:
text, or the ``<|im_end|>`` close).
"""
_, out, _num_patches, h = self._process_image(part)
emit_special(self._media_begin, msg_idx)
emit_text("image", msg_idx)
emit_special(self._media_content, msg_idx)
emit_special(self._media_begin, msg_idx, is_sampled=is_sampled)
emit_text("image", msg_idx, is_sampled=is_sampled)
emit_special(self._media_content, msg_idx, is_sampled=is_sampled)
offset = len(tokens)
emit_special(self._media_pad, msg_idx)
emit_special(self._media_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._media_pad, msg_idx, is_sampled=is_sampled)
emit_special(self._media_end, msg_idx, is_sampled=is_sampled)
emit_text("\n", msg_idx, is_sampled=is_sampled)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=1)
@@ -806,26 +809,29 @@ class KimiK25Renderer:
# fires when tools are present. Match that with our own TS encoder.
if tools:
tools_ts = _encode_tools_typescript(tools)
emit_special(self._im_system, -1)
emit_text("tool_declare", -1)
emit_special(self._im_middle, -1)
emit_text(tools_ts, -1)
emit_special(self._im_end, -1)
emit_special(self._im_system, -1, is_sampled=False)
emit_text("tool_declare", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
emit_text(tools_ts, -1, is_sampled=False)
emit_special(self._im_end, -1, is_sampled=False)
# ── Iterate messages ─────────────────────────────────────────
for i, msg in enumerate(messages):
role = msg.get("role", "")
# set_roles: role tag + role_name + <|im_middle|>
# set_roles: role tag + role_name + <|im_middle|> — these are
# template-injected scaffolding the model never samples (the
# generation prompt emits them at inference for assistants;
# user / system / tool roles are conversation history).
if role == "user":
emit_special(self._im_user, i)
emit_special(self._im_user, i, is_sampled=False)
elif role == "assistant":
emit_special(self._im_assistant, i)
emit_special(self._im_assistant, i, is_sampled=False)
else:
emit_special(self._im_system, i)
emit_special(self._im_system, i, is_sampled=False)
role_name = msg.get("name") or role
emit_text(role_name, i)
emit_special(self._im_middle, i)
emit_text(role_name, i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
# Body
if role == "assistant":
@@ -844,6 +850,13 @@ class KimiK25Renderer:
emit_special=emit_special,
emit_text=emit_text,
)
# ``<|im_end|>`` is the model's stop signal — it samples
# this to end its turn, so it is part of the sampled
# stream. Kimi K2.5 has no inter-turn ``\n`` separator
# (unlike Qwen3), so the turn-close token is the last
# sampled token.
emit_special(self._im_end, i, is_sampled=True)
continue
elif role == "tool":
self._render_tool_body(
msg,
@@ -854,7 +867,9 @@ class KimiK25Renderer:
emit_image=emit_image,
)
elif msg.get("content") is not None:
# User / other content branches — images allowed.
# User / other content branches — images allowed. All
# non-assistant content is conversation history, never
# sampled by the model.
self._emit_content(
msg.get("content"),
i,
@@ -862,21 +877,22 @@ class KimiK25Renderer:
emit_text,
emit_ids,
emit_image=emit_image,
is_sampled=False,
)
emit_special(self._im_end, i)
emit_special(self._im_end, i, is_sampled=False)
# ── Generation prompt ────────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
if self._enable_thinking:
# Prefill open <think> tag to trigger thinking mode
emit_text("<think>", -1)
emit_text("<think>", -1, is_sampled=False)
else:
# Empty <think></think> to disable thinking
emit_text("<think></think>", -1)
emit_text("<think></think>", -1, is_sampled=False)
mm_data: MultiModalData | None = None
if mm_hashes or mm_placeholders or mm_items:
@@ -889,6 +905,7 @@ class KimiK25Renderer:
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
multi_modal_data=mm_data,
)
@@ -984,16 +1001,30 @@ class KimiK25Renderer:
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the caller
# blanket-masks it via ``prompt_mask=[False]*N``, so we don't track
# sampled_mask here. Local helpers accept the kwarg for signature
# compatibility with ``_render_tool_body`` / ``_emit_content`` and
# ignore it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
tokens.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
tokens.extend(self._encode(text))
def emit_ids(ids: list[int], _msg_idx: int = -1) -> None:
def emit_ids(
ids: list[int], _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
tokens.extend(ids)
def emit_image(part: dict[str, Any], _msg_idx: int = -1) -> None:
def emit_image(
part: dict[str, Any], _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
_, out, _num_patches, h = self._process_image(part)
emit_special(self._media_begin)
emit_text("image")
@@ -1045,6 +1076,7 @@ class KimiK25Renderer:
emit_text,
emit_ids,
emit_image=emit_image,
is_sampled=False,
)
emit_special(self._im_end, i)
@@ -1108,6 +1140,7 @@ class KimiK25Renderer:
emit_ids,
*,
emit_image=None,
is_sampled: bool,
) -> None:
"""Emit message content, handling strings, multipart lists, and (when
``emit_image`` is supplied) image parts.
@@ -1126,7 +1159,7 @@ class KimiK25Renderer:
if content is None:
return
if isinstance(content, str):
emit_text(content, msg_idx)
emit_text(content, msg_idx, is_sampled=is_sampled)
return
if isinstance(content, list):
for part in content:
@@ -1139,19 +1172,21 @@ class KimiK25Renderer:
if emit_image is None:
# Silently drop — caller didn't opt into multimodal.
continue
emit_image(part, msg_idx)
emit_image(part, msg_idx, is_sampled=is_sampled)
continue
if is_video:
raise NotImplementedError(
"Video parts are not yet supported by KimiK25Renderer."
)
if ptype == "text":
emit_text(part.get("text", ""), msg_idx)
emit_text(part.get("text", ""), msg_idx, is_sampled=is_sampled)
elif ptype == "thinking":
# Thinking parts in non-assistant roles are rendered as text
thinking = part.get("thinking", "")
if thinking:
emit_text(f"<think>{thinking}</think>", msg_idx)
emit_text(
f"<think>{thinking}</think>", msg_idx, is_sampled=is_sampled
)
# Other part types are silently skipped
def _render_assistant_body(
@@ -1209,17 +1244,20 @@ class KimiK25Renderer:
else:
text_content = content or ""
# Hist/suffix split: hist drops reasoning, suffix keeps it.
# Override flag preserves reasoning on hist when caller asks for it.
# Assistant body is model-sampled content: ``<think>...</think>``
# block, text content, and any tool_calls section all live in
# the sampled stream. The closing ``<|im_end|>`` is emitted by
# ``render`` (also is_sampled=True; it's the model's stop
# signal).
if is_suffix or (preserve_thinking and reasoning_content):
emit_text(f"<think>{reasoning_content}</think>", msg_idx)
emit_text(f"<think>{reasoning_content}</think>", msg_idx, is_sampled=True)
else:
emit_text("<think></think>", msg_idx)
emit_text(text_content, msg_idx)
emit_text("<think></think>", msg_idx, is_sampled=True)
emit_text(text_content, msg_idx, is_sampled=True)
tool_calls = msg.get("tool_calls") or []
if tool_calls:
emit_special(self._tool_calls_section_begin, msg_idx)
emit_special(self._tool_calls_section_begin, msg_idx, is_sampled=True)
for tc in tool_calls:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
@@ -1233,12 +1271,12 @@ class KimiK25Renderer:
# ``functions.{name}:{idx}`` form (Kimi's parser recovers
# the function name from that field).
tool_id = tc.get("id") or ""
emit_special(self._tool_call_begin, msg_idx)
emit_text(tool_id, msg_idx)
emit_special(self._tool_call_argument_begin, msg_idx)
emit_text(args_str, msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_section_end, msg_idx)
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text(tool_id, msg_idx, is_sampled=True)
emit_special(self._tool_call_argument_begin, msg_idx, is_sampled=True)
emit_text(args_str, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_section_end, msg_idx, is_sampled=True)
def _render_tool_body(
self,
@@ -1262,8 +1300,11 @@ class KimiK25Renderer:
``<|media_begin|>image<|media_content|><|media_pad|><|media_end|>``
inline. Without it those parts are silently dropped.
"""
# 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.
tool_call_id = msg.get("tool_call_id") or ""
emit_text(f"## Return of {tool_call_id}\n", msg_idx)
emit_text(f"## Return of {tool_call_id}\n", msg_idx, is_sampled=False)
content = msg.get("content")
if content is not None:
self._emit_content(
@@ -1273,6 +1314,7 @@ class KimiK25Renderer:
emit_text,
emit_ids,
emit_image=emit_image,
is_sampled=False,
)
def _normalize_response_tokens(self, response: list[int]) -> list[int]:
+63 -30
View File
@@ -153,17 +153,20 @@ class LagunaXS2Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
emit_special(self._eos, -1)
emit_special(self._eos, -1, is_sampled=False)
# ── System header (absorbs messages[0] if it's a system message) ──
system_content = _DEFAULT_SYSTEM_MESSAGE
@@ -180,9 +183,13 @@ class LagunaXS2Renderer:
# The template emits ``<system>\n`` then conditionally a second
# ``\n``. Bundle those into one emit so BPE merges ``\n\n`` into
# its single-token form (rather than two ``\n`` atoms).
emit_text("<system>\n\n" if has_sys_content else "<system>\n", -1)
emit_text(
"<system>\n\n" if has_sys_content else "<system>\n",
-1,
is_sampled=False,
)
if has_sys_content:
emit_text(system_content.rstrip(), system_msg_idx)
emit_text(system_content.rstrip(), system_msg_idx, is_sampled=False)
if tools:
tool_text = _TOOLS_HEADER
for tool in tools:
@@ -192,8 +199,8 @@ class LagunaXS2Renderer:
if self._enable_thinking
else _TOOLS_FOOTER_NO_THINKING
)
emit_text(tool_text, -1)
emit_text("\n</system>\n", -1)
emit_text(tool_text, -1, is_sampled=False)
emit_text("\n</system>\n", -1, is_sampled=False)
# ── Per-message loop ──────────────────────────────────────────
for i, msg in enumerate(messages):
@@ -204,26 +211,34 @@ class LagunaXS2Renderer:
# Already consumed in the header block.
if i == 0:
continue
emit_text("<system>\n" + content + "\n</system>\n", i)
emit_text(
"<system>\n" + content + "\n</system>\n", i, is_sampled=False
)
case "user":
emit_text("<user>\n" + content + "\n</user>\n", i)
emit_text("<user>\n" + content + "\n</user>\n", i, is_sampled=False)
case "assistant":
self._render_assistant(
msg, i, content, emit_special=emit_special, emit_text=emit_text
)
case "tool":
emit_text("<tool_response>\n" + content + "\n</tool_response>\n", i)
emit_text(
"<tool_response>\n" + content + "\n</tool_response>\n",
i,
is_sampled=False,
)
# ── Generation prompt ─────────────────────────────────────────
if add_generation_prompt:
emit_special(self._assistant, -1)
emit_text("\n", -1)
emit_special(self._assistant, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1)
emit_special(self._think, -1, is_sampled=False)
else:
emit_special(self._think_end, -1)
emit_special(self._think_end, -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
@@ -288,10 +303,19 @@ class LagunaXS2Renderer:
ext: list[int] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility and ignore it; the returned
# ``RenderedTokens`` leaves ``sampled_mask`` empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.extend(self._encode(text))
for msg in new_messages:
@@ -335,22 +359,27 @@ class LagunaXS2Renderer:
if part_thinking:
reasoning_content = part_thinking
emit_special(self._assistant, msg_idx)
emit_text("\n", msg_idx)
# ``<assistant>\n`` is template-injected scaffolding — the chat
# template emits these as the generation prompt at inference and
# the model never samples them. Marking the role tag as
# ``is_sampled=False`` keeps the SFT loss mask aligned with what
# the model would actually have produced.
emit_special(self._assistant, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
if reasoning_content:
emit_special(self._think, msg_idx)
emit_text("\n" + reasoning_content.strip() + "\n", msg_idx)
emit_special(self._think_end, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content.strip() + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
else:
emit_special(self._think_end, msg_idx)
emit_special(self._think_end, msg_idx, is_sampled=True)
# Combined newline-after-</think> with optional content. Bundling
# preserves BPE merges across the boundary.
post_think_text = "\n"
if content.strip():
post_think_text += content.strip() + "\n"
emit_text(post_think_text, msg_idx)
emit_text(post_think_text, msg_idx, is_sampled=True)
tool_calls = msg.get("tool_calls") or []
for tc in tool_calls:
@@ -363,7 +392,7 @@ class LagunaXS2Renderer:
except json.JSONDecodeError:
arguments = {}
emit_special(self._tool_call, msg_idx)
emit_special(self._tool_call, msg_idx, is_sampled=True)
inner = name + "\n"
if isinstance(arguments, dict):
for k, v in arguments.items():
@@ -373,9 +402,13 @@ class LagunaXS2Renderer:
else:
val_text = json.dumps(v, ensure_ascii=False)
inner += "<arg_value>" + val_text + "</arg_value>\n"
emit_text(inner, msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_text("\n", msg_idx)
emit_text(inner, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._assistant_end, msg_idx)
emit_text("\n", msg_idx)
# ``</assistant>`` is the model's stop signal (alongside
# ``〈|EOS|〉``) — it samples this to end its turn, so it's part of
# the sampled stream. The trailing ``\n`` is template-appended
# between turns and never sampled.
emit_special(self._assistant_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
+98 -42
View File
@@ -118,15 +118,18 @@ class MiniMaxM2Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
# ── Extract system message ──────────────────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -134,8 +137,8 @@ class MiniMaxM2Renderer:
conversation: list[Message] = messages[1:] if first_is_system else messages
# ── System block (always present) ───────────────────────────
emit_special(self._bos, sys_idx)
emit_special(self._role, sys_idx)
emit_special(self._bos, sys_idx, is_sampled=False)
emit_special(self._role, sys_idx, is_sampled=False)
sys_content = (
self._visible_text(messages[0].get("content")) if first_is_system else ""
@@ -152,9 +155,9 @@ class MiniMaxM2Renderer:
system_text += _TOOLS_FOOTER_PREFIX
system_text += _TOOLS_INSTRUCTIONS
emit_text(system_text, sys_idx)
emit_special(self._eos, sys_idx)
emit_text("\n", sys_idx)
emit_text(system_text, sys_idx, is_sampled=False)
emit_special(self._eos, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
# ── Compute last_user_index (relative to conversation) ──────
last_ui = -1
@@ -169,10 +172,14 @@ class MiniMaxM2Renderer:
orig_idx = ci + (1 if first_is_system else 0)
if role == "user":
emit_special(self._role, orig_idx)
emit_text("user\n" + self._visible_text(msg.get("content")), orig_idx)
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
emit_special(self._role, orig_idx, is_sampled=False)
emit_text(
"user\n" + self._visible_text(msg.get("content")),
orig_idx,
is_sampled=False,
)
emit_special(self._eos, orig_idx, is_sampled=False)
emit_text("\n", orig_idx, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -203,12 +210,14 @@ class MiniMaxM2Renderer:
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._role, -1)
emit_text("ai\n", -1)
emit_special(self._think, -1)
emit_text("\n", -1)
emit_special(self._role, -1, is_sampled=False)
emit_text("ai\n", -1, is_sampled=False)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
@@ -269,10 +278,20 @@ class MiniMaxM2Renderer:
ext: list[int] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.extend(self._encode(text))
# Trailing ``\n`` after the ``[e~[`` turn close — see ``render()``.
@@ -335,26 +354,53 @@ class MiniMaxM2Renderer:
reasoning_content = before.strip("\n")
content = after.strip("\n")
emit_special(self._role, orig_idx)
# ``]~b]ai\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 marker and tag as
# ``is_sampled=False`` keeps the SFT loss mask aligned with what
# the model would actually have produced.
emit_special(self._role, orig_idx, is_sampled=False)
# Build the full text between ]~b]ai and [e~[ with special tokens
# interspersed. Keep text segments contiguous to preserve BPE merges.
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges.
tool_calls = msg.get("tool_calls") or []
emit_thinking = reasoning_content and (
conv_idx > last_user_index or preserve_thinking
)
if reasoning_content and (conv_idx > last_user_index or preserve_thinking):
emit_text("ai\n", orig_idx)
emit_special(self._think, orig_idx)
emit_text("\n" + reasoning_content + "\n", orig_idx)
emit_special(self._think_end, orig_idx)
if emit_thinking:
# The thinking branch has the ``<think>`` special token
# immediately after ``ai\n``, which forces a tokenizer
# boundary — splitting ``ai\n`` (not_sampled) from the
# ``<think>``-led body (sampled) is BPE-safe.
emit_text("ai\n", orig_idx, is_sampled=False)
emit_special(self._think, orig_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", orig_idx, is_sampled=True)
emit_special(self._think_end, orig_idx, is_sampled=True)
# \n\n + content must be contiguous for BPE
after_think = "\n\n" + content if content else "\n\n"
body = "\n\n" + content if content else "\n\n"
else:
after_think = "ai\n" + content if content else "ai\n"
body = content
# Empty body + tool_calls would emit ``"\n"`` next, and
# ``ai\n`` + ``\n`` BPE-merges into a single ``\n\n`` token
# in this tokenizer. Fold the boundary ``\n`` into the
# role-tag emission so the merged token stays whole. The
# combined token is is_sampled=False — the conservative
# choice for SFT (don't train on a token whose first byte
# is template scaffolding).
if tool_calls and not body:
emit_text("ai\n\n", orig_idx, is_sampled=False)
else:
emit_text("ai\n", orig_idx, is_sampled=False)
if tool_calls:
# \n before <minimax:tool_call> must be contiguous with preceding text
emit_text(after_think + "\n", orig_idx)
emit_special(self._tool_call_tok, orig_idx)
# \n before <minimax:tool_call> must be contiguous with preceding text.
# The empty-body / non-thinking case folded the leading \n
# into the role-tag emission above; skip it here.
if emit_thinking or body:
emit_text(body + "\n", orig_idx, is_sampled=True)
emit_special(self._tool_call_tok, orig_idx, is_sampled=True)
invoke_block = "\n"
for tc in tool_calls:
@@ -386,13 +432,16 @@ class MiniMaxM2Renderer:
)
invoke_block += "</invoke>\n"
emit_text(invoke_block, orig_idx)
emit_special(self._tool_call_end_tok, orig_idx)
else:
emit_text(after_think, orig_idx)
emit_text(invoke_block, orig_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, orig_idx, is_sampled=True)
elif body:
emit_text(body, orig_idx, is_sampled=True)
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
# ``[e~[`` 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.
emit_special(self._eos, orig_idx, is_sampled=True)
emit_text("\n", orig_idx, is_sampled=False)
def _render_tool(
self,
@@ -404,6 +453,9 @@ class MiniMaxM2Renderer:
emit_special,
emit_text,
) -> 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.
prev_is_tool = conv_idx > 0 and conversation[conv_idx - 1]["role"] == "tool"
next_is_tool = (
conv_idx + 1 < len(conversation)
@@ -411,8 +463,8 @@ class MiniMaxM2Renderer:
)
if not prev_is_tool:
emit_special(self._role, orig_idx)
emit_text("tool", orig_idx)
emit_special(self._role, orig_idx, is_sampled=False)
emit_text("tool", orig_idx, is_sampled=False)
content = self._visible_text(msg.get("content"))
# Leading ``\n`` before ``<response>`` only on the first of a
@@ -421,8 +473,12 @@ class MiniMaxM2Renderer:
# through a single emit_text call instead of splitting the merge.
prefix = "" if prev_is_tool else "\n"
suffix = "\n" if next_is_tool else ""
emit_text(prefix + "<response>" + content + "</response>" + suffix, orig_idx)
emit_text(
prefix + "<response>" + content + "</response>" + suffix,
orig_idx,
is_sampled=False,
)
if not next_is_tool:
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
emit_special(self._eos, orig_idx, is_sampled=False)
emit_text("\n", orig_idx, is_sampled=False)
+81 -55
View File
@@ -240,17 +240,20 @@ class Nemotron3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -259,8 +262,8 @@ class Nemotron3Renderer:
# Nemotron 3: system prompt BEFORE tools block
sys_idx = orig_idx(0) if first_is_system else -1
emit_special(self._im_start, sys_idx)
emit_text("system\n", sys_idx)
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n", sys_idx, is_sampled=False)
# Build system content: user's system text first, then tools
if first_is_system:
@@ -284,17 +287,17 @@ class Nemotron3Renderer:
else:
full_sys = tools_block
emit_text(full_sys, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
emit_text(full_sys, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
elif first_is_system:
sys_idx = orig_idx(0)
sys_content = self._render_content(messages[0].get("content")).strip()
emit_special(self._im_start, sys_idx)
emit_text("system\n" + sys_content, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n" + sys_content, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
# Track the most-recent plain (non-tool-call) assistant so we can
# preserve its reasoning while stripping reasoning from earlier
@@ -319,10 +322,10 @@ class Nemotron3Renderer:
continue # Already handled above
elif role == "user":
emit_special(self._im_start, msg_orig_idx)
emit_text("user\n" + content, msg_orig_idx)
emit_special(self._im_end, msg_orig_idx)
emit_text("\n", msg_orig_idx)
emit_special(self._im_start, msg_orig_idx, is_sampled=False)
emit_text("user\n" + content, msg_orig_idx, is_sampled=False)
emit_special(self._im_end, msg_orig_idx, is_sampled=False)
emit_text("\n", msg_orig_idx, is_sampled=False)
elif role == "assistant":
is_last_turn = i >= last_plain_assistant_idx
@@ -359,17 +362,19 @@ class Nemotron3Renderer:
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
else:
# Disable-thinking suffix: <think></think> with no trailing newlines
emit_special(self._think, -1)
emit_special(self._think_end, -1)
emit_special(self._think, -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
@@ -438,10 +443,20 @@ class Nemotron3Renderer:
ext: list[int] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.extend(self._encode(text))
emit_text("\n", -1)
@@ -515,8 +530,13 @@ class Nemotron3Renderer:
reasoning_content = reasoning_content.strip()
emit_special(self._im_start, msg_idx)
emit_text("assistant\n", msg_idx)
# ``<|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
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced.
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# Nemotron 3 keeps reasoning on the most-recent plain assistant but
# strips it from historical turns, which collapse to an empty
@@ -531,35 +551,35 @@ class Nemotron3Renderer:
content_suffix = "\n" if tool_calls else ""
if reasoning_content and (is_last_turn or preserve_thinking):
emit_special(self._think, msg_idx)
emit_text("\n" + reasoning_content + "\n", msg_idx)
emit_special(self._think_end, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
# Single \n separator (not \n\n like Qwen3.5)
emit_text("\n" + content + content_suffix, msg_idx)
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=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)
emit_special(self._think_end, msg_idx)
emit_text("\n" + content + content_suffix, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=True)
else:
# No reasoning ever — <think></think> glued directly to content.
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
emit_text(content + content_suffix, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text(content + content_suffix, msg_idx, is_sampled=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_idx, tc in enumerate(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)
emit_text("\n<function=" + name + ">\n", msg_idx)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_text("\n<function=" + name + ">\n", msg_idx, is_sampled=True)
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
@@ -582,15 +602,19 @@ class Nemotron3Renderer:
+ value_str
+ "\n</parameter>\n",
msg_idx,
is_sampled=True,
)
emit_text("</function>\n", msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_text("</function>\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
# Trailing \n after </tool_call> (Nemotron 3 specific)
emit_text("\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# ``<|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.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
# ------------------------------------------------------------------
# Tool message rendering
@@ -607,7 +631,9 @@ class Nemotron3Renderer:
emit_special,
emit_text,
) -> None:
# Consecutive tool messages are grouped under a single <|im_start|>user block
# 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.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
@@ -615,17 +641,17 @@ class Nemotron3Renderer:
oi = msg_orig_idx
if not prev_is_tool:
emit_special(self._im_start, oi)
emit_text("user\n", oi)
emit_special(self._im_start, oi, is_sampled=False)
emit_text("user\n", oi, is_sampled=False)
# else: the previous tool's trailing \n already provides the
# separator into this block.
emit_special(self._tool_response, oi)
emit_text("\n" + content + "\n", oi)
emit_special(self._tool_response_end, oi)
emit_special(self._tool_response, oi, is_sampled=False)
emit_text("\n" + content + "\n", oi, is_sampled=False)
emit_special(self._tool_response_end, oi, is_sampled=False)
# Nemotron 3: trailing \n after </tool_response>
emit_text("\n", oi)
emit_text("\n", oi, is_sampled=False)
if not next_is_tool:
emit_special(self._im_end, oi)
emit_text("\n", oi)
emit_special(self._im_end, oi, is_sampled=False)
emit_text("\n", oi, is_sampled=False)
+81 -48
View File
@@ -107,24 +107,27 @@ class Qwen3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
# ── 1. System + tools ───────────────────────────────────────
first_is_system = messages[0].get("role") == "system"
if tools:
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx)
emit_special(self._im_start, sys_idx, is_sampled=False)
tool_text = "system\n"
if first_is_system:
tool_text += (messages[0].get("content") or "") + "\n\n"
@@ -132,14 +135,16 @@ class Qwen3Renderer:
for tool in tools:
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
tool_text += _TOOLS_FOOTER
emit_text(tool_text, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
emit_text(tool_text, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
elif first_is_system:
emit_special(self._im_start, 0)
emit_text("system\n" + (messages[0].get("content") or ""), 0)
emit_special(self._im_end, 0)
emit_text("\n", 0)
emit_special(self._im_start, 0, is_sampled=False)
emit_text(
"system\n" + (messages[0].get("content") or ""), 0, is_sampled=False
)
emit_special(self._im_end, 0, is_sampled=False)
emit_text("\n", 0, is_sampled=False)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
@@ -153,16 +158,16 @@ class Qwen3Renderer:
if role == "system":
if i == 0:
continue
emit_special(self._im_start, i)
emit_text(role + "\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
emit_special(self._im_start, i, is_sampled=False)
emit_text(role + "\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
elif role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
emit_special(self._im_start, i, is_sampled=False)
emit_text("user\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -189,12 +194,14 @@ class Qwen3Renderer:
# ── 4. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if not self._enable_thinking:
emit_text("<think>\n\n</think>\n\n", -1)
emit_text("<think>\n\n</think>\n\n", -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
)
def render_ids(
self,
@@ -252,10 +259,20 @@ class Qwen3Renderer:
ext: list[int] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.extend(self._encode(text))
# Trailing ``\n`` after the turn-close token. ``render()`` emits this
@@ -318,11 +335,20 @@ class Qwen3Renderer:
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._im_start, msg_idx)
# ``<|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
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced.
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# Build the full text between <|im_start|> and <|im_end|> with tool call
# special tokens interspersed. We must keep text segments contiguous to
# preserve BPE merges (e.g., ".\n" is a single token in Qwen3).
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges (e.g., ".\n" is a single token in
# Qwen3); the only split we introduce here is at ``\n`` after the
# role tag, which the existing renderer already treats as a
# token boundary (cf. ``_render_tool``).
tool_calls = msg.get("tool_calls") or []
emit_in_template_window = msg_idx > last_query_index and (
@@ -330,17 +356,17 @@ class Qwen3Renderer:
)
emit_via_override = preserve_thinking and bool(reasoning_content)
if emit_in_template_window or emit_via_override:
prefix = (
"assistant\n<think>\n"
body = (
"<think>\n"
+ reasoning_content.strip("\n")
+ "\n</think>\n\n"
+ content.lstrip("\n")
)
else:
prefix = "assistant\n" + content
body = content
if not tool_calls:
emit_text(prefix, msg_idx)
emit_text(body, msg_idx, is_sampled=True)
else:
for tc_idx, tc in enumerate(tool_calls):
func = tc.get("function") or tc
@@ -355,19 +381,23 @@ class Qwen3Renderer:
# Text before this tool_call (includes separator)
if tc_idx == 0:
separator = "\n" if content else ""
emit_text(prefix + separator, msg_idx)
emit_text(body + separator, msg_idx, is_sampled=True)
else:
emit_text("\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call, msg_idx)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_text(
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
msg_idx,
is_sampled=True,
)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# ``<|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.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
def _render_tool(
self,
@@ -378,20 +408,23 @@ class Qwen3Renderer:
emit_special,
emit_text,
) -> 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.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
)
if not prev_is_tool:
emit_special(self._im_start, msg_idx)
emit_text("user", msg_idx)
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("user", msg_idx, is_sampled=False)
emit_text("\n", msg_idx)
emit_special(self._tool_response, msg_idx)
emit_text("\n" + content + "\n", msg_idx)
emit_special(self._tool_response_end, msg_idx)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._tool_response, msg_idx, is_sampled=False)
emit_text("\n" + content + "\n", msg_idx, is_sampled=False)
emit_special(self._tool_response_end, msg_idx, is_sampled=False)
if not next_is_tool:
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
+97 -59
View File
@@ -290,28 +290,34 @@ class Qwen35Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
mm_hashes: dict[str, list[str]] = {}
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
mm_items: dict[str, list[dict[str, Any]]] = {}
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_image(part: dict[str, Any], msg_idx: int) -> None:
# Image placeholders only appear in user / tool messages; the
# model never samples them. Pin is_sampled=False here so
# callers don't need to thread the flag through.
_, out, n, h = self._process_image(part)
emit_special(self._vision_start, msg_idx)
emit_special(self._vision_start, msg_idx, is_sampled=False)
offset = len(tokens)
for _ in range(n):
emit_special(self._image_pad, msg_idx)
emit_special(self._vision_end, msg_idx)
emit_special(self._image_pad, msg_idx, is_sampled=False)
emit_special(self._vision_end, msg_idx, is_sampled=False)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -332,12 +338,14 @@ class Qwen35Renderer:
concatenates strings before tokenization. This preserves BPE
byte-parity against ``apply_chat_template``.
"""
emit_special(self._im_start, msg_idx)
# Every token in a user message is conversation history that
# the model never samples at inference.
emit_special(self._im_start, msg_idx, is_sampled=False)
buf: list[str] = ["user\n"]
def flush_buf() -> None:
if buf:
emit_text("".join(buf), msg_idx)
emit_text("".join(buf), msg_idx, is_sampled=False)
buf.clear()
for item in content_list:
@@ -358,8 +366,8 @@ class Qwen35Renderer:
else:
raise ValueError(f"Unexpected content item: {item}")
flush_buf()
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -368,8 +376,8 @@ class Qwen35Renderer:
# System message index for attribution
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx)
emit_text("system\n", sys_idx)
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n", sys_idx, is_sampled=False)
# Tools header + JSON definitions
tool_text = _TOOLS_HEADER
@@ -384,15 +392,15 @@ class Qwen35Renderer:
if sys_content:
tool_text += "\n\n" + sys_content
emit_text(tool_text, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
emit_text(tool_text, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
elif first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
emit_special(self._im_start, 0)
emit_text("system\n" + sys_content, 0)
emit_special(self._im_end, 0)
emit_text("\n", 0)
emit_special(self._im_start, 0, is_sampled=False)
emit_text("system\n" + sys_content, 0, is_sampled=False)
emit_special(self._im_end, 0, is_sampled=False)
emit_text("\n", 0, is_sampled=False)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
@@ -412,10 +420,10 @@ class Qwen35Renderer:
if self._content_has_media(raw_content):
emit_user_with_media(raw_content, i)
else:
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
emit_special(self._im_start, i, is_sampled=False)
emit_text("user\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -449,16 +457,16 @@ class Qwen35Renderer:
# ── 4. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
else:
emit_special(self._think, -1)
emit_text("\n\n", -1)
emit_special(self._think_end, -1)
emit_text("\n\n", -1)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n\n", -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
emit_text("\n\n", -1, is_sampled=False)
mm_data: MultiModalData | None = None
if mm_hashes or mm_placeholders or mm_items:
@@ -471,6 +479,7 @@ class Qwen35Renderer:
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
multi_modal_data=mm_data,
)
@@ -539,10 +548,20 @@ class Qwen35Renderer:
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
tokens.append(token_id)
def emit_text(text: str, _msg_idx: int = -1) -> None:
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
tokens.extend(self._encode(text))
def emit_image(part: dict[str, Any], _msg_idx: int = -1) -> None:
@@ -731,20 +750,30 @@ class Qwen35Renderer:
reasoning_content = reasoning_content.strip()
emit_special(self._im_start, msg_idx)
# ``<|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
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced. The split between
# ``assistant`` and ``\n`` is a safe BPE boundary in the Qwen
# tokenizer (``\n`` after the role is its own token).
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges.
emit_thinking = self._should_render_thinking(msg_idx, last_query_index) or (
preserve_thinking and bool(reasoning_content)
)
if emit_thinking:
# Include thinking block
emit_text("assistant\n", msg_idx)
emit_special(self._think, msg_idx)
emit_text("\n" + reasoning_content + "\n", msg_idx)
emit_special(self._think_end, msg_idx)
emit_text("\n\n" + content, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text("\n\n" + content, msg_idx, is_sampled=True)
else:
emit_text("assistant\n" + content, msg_idx)
emit_text(content, msg_idx, is_sampled=True)
# Tool calls
tool_calls = msg.get("tool_calls") or []
@@ -757,13 +786,13 @@ class Qwen35Renderer:
# Separator before <tool_call>
if tc_idx == 0:
if content.strip():
emit_text("\n\n", msg_idx)
emit_text("\n\n", msg_idx, is_sampled=True)
# else: no separator
else:
emit_text("\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call, msg_idx)
emit_text("\n<function=" + name + ">\n", msg_idx)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_text("\n<function=" + name + ">\n", msg_idx, is_sampled=True)
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
@@ -783,13 +812,17 @@ class Qwen35Renderer:
+ value_str
+ "\n</parameter>\n",
msg_idx,
is_sampled=True,
)
emit_text("</function>\n", msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_text("</function>\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# ``<|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.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
# ------------------------------------------------------------------
# Tool message rendering
@@ -808,6 +841,11 @@ class Qwen35Renderer:
# envelope. Whether to open and close the envelope depends only on the
# neighbouring roles, never on the content type of this or any other
# tool message — keep this predicate text/media-agnostic.
# 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 bridge's
# local emit_special / emit_text accept the is_sampled kwarg for
# signature compatibility but ignore it.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
@@ -815,11 +853,11 @@ class Qwen35Renderer:
raw_content = messages[msg_idx].get("content")
if not prev_is_tool:
emit_special(self._im_start, msg_idx)
emit_text("user", msg_idx)
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("user", msg_idx, is_sampled=False)
emit_text("\n", msg_idx)
emit_special(self._tool_response, msg_idx)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._tool_response, msg_idx, is_sampled=False)
if self._content_has_media(raw_content):
# Mirror the chat template's ``render_content`` macro for list
@@ -833,7 +871,7 @@ class Qwen35Renderer:
def flush_buf() -> None:
if buf:
emit_text("".join(buf), msg_idx)
emit_text("".join(buf), msg_idx, is_sampled=False)
buf.clear()
for item in raw_content:
@@ -854,13 +892,13 @@ class Qwen35Renderer:
else:
raise ValueError(f"Unexpected content item: {item}")
flush_buf()
emit_text("\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=False)
else:
content = self._render_content(raw_content).strip()
emit_text("\n" + content + "\n", msg_idx)
emit_text("\n" + content + "\n", msg_idx, is_sampled=False)
emit_special(self._tool_response_end, msg_idx)
emit_special(self._tool_response_end, msg_idx, is_sampled=False)
if not next_is_tool:
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
+114 -64
View File
@@ -162,14 +162,24 @@ class _Emitter:
hit a special token (or end of message). Two text fragments emitted
back-to-back end up in the same flush, exactly matching how the
chat template concatenates string outputs before the final encode.
Per-token ``sampled_mask`` is tracked alongside ``token_ids`` /
``message_indices``: every ``text(..., is_sampled=...)`` and
``special(..., is_sampled=...)`` call stamps its emitted tokens with
the supplied flag. A text fragment with a different ``is_sampled``
value than the current buffer triggers a flush first — split points
are always at the ``is_sampled`` boundary, which the caller is
expected to place at a ``\\n`` boundary so BPE merges don't drift.
"""
def __init__(self, encode_fn, msg_idx: int = -1):
self._encode = encode_fn
self.token_ids: list[int] = []
self.message_indices: list[int] = []
self.sampled: list[bool] = []
self._buf: str = ""
self._buf_idx: int = msg_idx
self._buf_sampled: bool = False
self.msg_idx = msg_idx
def set_msg_idx(self, msg_idx: int) -> None:
@@ -182,22 +192,27 @@ class _Emitter:
self.msg_idx = msg_idx
self._buf_idx = msg_idx
def text(self, text: str) -> None:
def text(self, text: str, *, is_sampled: bool) -> None:
if not text:
return
# Adjacent text under different msg_idx is rare in this template
# — but if it happens, flush so attribution stays accurate.
if self._buf and self._buf_idx != self.msg_idx:
# Adjacent text under different msg_idx or is_sampled is rare in
# this template — but flush at those boundaries so attribution
# and the sampled signal stay accurate.
if self._buf and (
self._buf_idx != self.msg_idx or self._buf_sampled != is_sampled
):
self._flush()
if not self._buf:
self._buf_idx = self.msg_idx
self._buf_sampled = is_sampled
self._buf += text
def special(self, token_id: int) -> None:
def special(self, token_id: int, *, is_sampled: bool) -> None:
if self._buf:
self._flush()
self.token_ids.append(token_id)
self.message_indices.append(self.msg_idx)
self.sampled.append(is_sampled)
def cursor(self) -> int:
"""Current token offset after flushing — used to anchor placeholder ranges."""
@@ -213,6 +228,7 @@ class _Emitter:
ids = self._encode(self._buf)
self.token_ids.extend(ids)
self.message_indices.extend([self._buf_idx] * len(ids))
self.sampled.extend([self._buf_sampled] * len(ids))
self._buf = ""
@@ -384,12 +400,15 @@ class Qwen3VLRenderer:
mm_items: dict[str, list[dict[str, Any]]] = {}
def emit_image(part: dict[str, Any]) -> None:
# Image placeholders are prompt-side scaffolding the user
# message attaches — the model never samples ``<|vision_start|>``
# / ``<|image_pad|>`` / ``<|vision_end|>``.
_, out, n, h = self._process_image(part)
em.special(self._vision_start)
em.special(self._vision_start, is_sampled=False)
offset = em.cursor()
for _ in range(n):
em.special(self._image_pad)
em.special(self._vision_end)
em.special(self._image_pad, is_sampled=False)
em.special(self._vision_end, is_sampled=False)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -402,16 +421,20 @@ class Qwen3VLRenderer:
)
def render_media_content(content: Any) -> None:
"""Emit a user/tool content list with media handled inline."""
"""Emit a user/tool content list with media handled inline.
User / tool content is conversation context the model never
samples — every text fragment goes in as ``is_sampled=False``.
"""
if isinstance(content, str):
em.text(content)
em.text(content, is_sampled=False)
return
if not isinstance(content, list):
em.text(self._render_text_content(content))
em.text(self._render_text_content(content), is_sampled=False)
return
for item in content:
if isinstance(item, str):
em.text(item)
em.text(item, is_sampled=False)
elif isinstance(item, dict):
if _is_image_part(item):
emit_image(item)
@@ -420,7 +443,7 @@ class Qwen3VLRenderer:
"Video parts are not yet supported by Qwen3VLRenderer."
)
elif "text" in item:
em.text(item["text"])
em.text(item["text"], is_sampled=False)
# ── 1. System + tools ───────────────────────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -428,7 +451,7 @@ class Qwen3VLRenderer:
if tools:
sys_idx = 0 if first_is_system else -1
em.set_msg_idx(sys_idx)
em.special(self._im_start)
em.special(self._im_start, is_sampled=False)
buf = "system\n"
if first_is_system:
buf += self._render_text_content(messages[0].get("content")) + "\n\n"
@@ -436,15 +459,18 @@ class Qwen3VLRenderer:
for tool in tools:
buf += "\n" + json.dumps(tool, ensure_ascii=False)
buf += _TOOLS_FOOTER
em.text(buf)
em.special(self._im_end)
em.text("\n")
em.text(buf, is_sampled=False)
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
elif first_is_system:
em.set_msg_idx(0)
em.special(self._im_start)
em.text("system\n" + self._render_text_content(messages[0].get("content")))
em.special(self._im_end)
em.text("\n")
em.special(self._im_start, is_sampled=False)
em.text(
"system\n" + self._render_text_content(messages[0].get("content")),
is_sampled=False,
)
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
# ── 2. Iterate messages ─────────────────────────────────────
for i, msg in enumerate(messages):
@@ -456,11 +482,11 @@ class Qwen3VLRenderer:
em.set_msg_idx(i)
if role == "user":
em.special(self._im_start)
em.text("user\n")
em.special(self._im_start, is_sampled=False)
em.text("user\n", is_sampled=False)
render_media_content(msg.get("content"))
em.special(self._im_end)
em.text("\n")
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
elif role == "assistant":
self._render_assistant(msg, em)
@@ -474,8 +500,8 @@ class Qwen3VLRenderer:
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
em.set_msg_idx(-1)
em.special(self._im_start)
em.text("assistant\n")
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
em.finalize()
@@ -490,6 +516,7 @@ class Qwen3VLRenderer:
return RenderedTokens(
token_ids=em.token_ids,
message_indices=em.message_indices,
sampled_mask=em.sampled,
multi_modal_data=mm_data,
)
@@ -557,6 +584,13 @@ class Qwen3VLRenderer:
if previous_ids is None:
return None
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't surface a sampled_mask here. The shared ``_render_tool``
# helper still routes through ``em.special``/``em.text`` with
# ``is_sampled`` kwargs, which the emitter accepts and tracks,
# but the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty (the field defaults to ``[]``).
em = _Emitter(self._encode)
# Seed the emitter with the prior turn's tokens so cursor() reports
# absolute offsets in the combined sequence.
@@ -569,11 +603,11 @@ class Qwen3VLRenderer:
def emit_image(part: dict[str, Any]) -> None:
_, out, n, h = self._process_image(part)
em.special(self._vision_start)
em.special(self._vision_start, is_sampled=False)
offset = em.cursor()
for _ in range(n):
em.special(self._image_pad)
em.special(self._vision_end)
em.special(self._image_pad, is_sampled=False)
em.special(self._vision_end, is_sampled=False)
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -587,14 +621,14 @@ class Qwen3VLRenderer:
def render_media_content(content: Any) -> None:
if isinstance(content, str):
em.text(content)
em.text(content, is_sampled=False)
return
if not isinstance(content, list):
em.text(self._render_text_content(content))
em.text(self._render_text_content(content), is_sampled=False)
return
for item in content:
if isinstance(item, str):
em.text(item)
em.text(item, is_sampled=False)
elif isinstance(item, dict):
if _is_image_part(item):
emit_image(item)
@@ -603,34 +637,34 @@ class Qwen3VLRenderer:
"Video parts are not yet supported by Qwen3VLRenderer."
)
elif "text" in item:
em.text(item["text"])
em.text(item["text"], is_sampled=False)
em.set_msg_idx(-1)
em.text("\n")
em.text("\n", is_sampled=False)
for i, msg in enumerate(new_messages):
role = msg.get("role")
em.set_msg_idx(i)
if role == "user":
em.special(self._im_start)
em.text("user\n")
em.special(self._im_start, is_sampled=False)
em.text("user\n", is_sampled=False)
render_media_content(msg.get("content"))
em.special(self._im_end)
em.text("\n")
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
elif role == "system":
em.special(self._im_start)
em.text("system\n")
em.special(self._im_start, is_sampled=False)
em.text("system\n", is_sampled=False)
render_media_content(msg.get("content"))
em.special(self._im_end)
em.text("\n")
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
elif role == "tool":
self._render_tool(new_messages, i, em, render_media_content)
else:
return None
em.set_msg_idx(-1)
em.special(self._im_start)
em.text("assistant\n")
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
em.finalize()
# Merge prev mm_data with the new turn's items.
@@ -674,18 +708,24 @@ class Qwen3VLRenderer:
original_content = msg.get("content")
tool_calls = msg.get("tool_calls") or []
em.special(self._im_start)
# ``<|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. Splitting the text
# at the ``\n`` after the role tag is safe: Qwen3 BPE treats
# ``\n`` as a token boundary.
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
prefix = "assistant\n" + content
# Body (content + tool calls) is the model-sampled portion.
if not tool_calls:
em.text(prefix)
em.text(content, is_sampled=True)
else:
for tc_idx, tc in enumerate(tool_calls):
if tc_idx == 0:
separator = "\n" if original_content else ""
em.text(prefix + separator)
em.text(content + separator, is_sampled=True)
else:
em.text("\n")
em.text("\n", is_sampled=True)
func = tc.get("function") or tc
name = func.get("name", "")
@@ -696,12 +736,18 @@ class Qwen3VLRenderer:
else json.dumps(arguments, ensure_ascii=False)
)
em.special(self._tool_call)
em.text('\n{"name": "' + name + '", "arguments": ' + args_str + "}\n")
em.special(self._tool_call_end)
em.special(self._tool_call, is_sampled=True)
em.text(
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
is_sampled=True,
)
em.special(self._tool_call_end, is_sampled=True)
em.special(self._im_end)
em.text("\n")
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn. The trailing ``\n`` is template-appended between
# turns and never sampled.
em.special(self._im_end, is_sampled=True)
em.text("\n", is_sampled=False)
def _render_tool(
self,
@@ -710,22 +756,26 @@ class Qwen3VLRenderer:
em: _Emitter,
render_media_content,
) -> 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. (render_media_content
# also stamps is_sampled=False on its emissions.)
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
)
if not prev_is_tool:
em.special(self._im_start)
em.text("user")
em.special(self._im_start, is_sampled=False)
em.text("user", is_sampled=False)
em.text("\n")
em.special(self._tool_response)
em.text("\n")
em.text("\n", is_sampled=False)
em.special(self._tool_response, is_sampled=False)
em.text("\n", is_sampled=False)
render_media_content(messages[msg_idx].get("content"))
em.text("\n")
em.special(self._tool_response_end)
em.text("\n", is_sampled=False)
em.special(self._tool_response_end, is_sampled=False)
if not next_is_tool:
em.special(self._im_end)
em.text("\n")
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
+119
View File
@@ -0,0 +1,119 @@
"""Per-token ``RenderedTokens.sampled_mask`` invariants.
``sampled_mask[k]`` answers "would the model have produced
``token_ids[k]`` at inference?" — distinct from ``message_indices``,
which only attributes a token to a source message. SFT loss masks
should AND both signals so the trainer only sees tokens the model
would actually sample.
These tests parametrise across every renderer in ``conftest.RENDERER_MODELS``
and verify the contract for hand-coded renderers. ``DefaultRenderer``
leaves ``sampled_mask`` empty by design (the Jinja template is opaque,
so the renderer cannot know the prompt / completion split) and is
exempt from the populated-length check.
"""
from __future__ import annotations
def test_sampled_mask_length_or_empty(model_name, renderer):
"""``sampled_mask`` is either empty (opt-out) or matches token_ids
length exactly. No partial fills."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
n_tokens = len(rendered.token_ids)
n_mask = len(rendered.sampled_mask)
assert n_mask == 0 or n_mask == n_tokens, (
f"{model_name}: sampled_mask length {n_mask} must be 0 or match "
f"token_ids length {n_tokens}"
)
def test_sampled_mask_excludes_user_and_system(model_name, renderer):
"""Every token attributed to a user / system / tool message must be
is_sampled=False — the model never samples conversation history.
Skips renderers that don't populate sampled_mask (DefaultRenderer)."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return # renderer opted out
bad = []
for k, (msg_idx, is_sampled) in enumerate(
zip(rendered.message_indices, rendered.sampled_mask)
):
if msg_idx < 0:
continue
role = msgs[msg_idx].get("role")
if role in ("user", "system", "tool") and is_sampled:
bad.append((k, role, msg_idx))
assert not bad, (
f"{model_name}: non-assistant tokens marked is_sampled=True "
f"(k, role, msg_idx): {bad[:8]}"
)
def test_sampled_mask_excludes_generation_prompt(model_name, renderer):
"""All generation-prompt tokens (msg_idx=-1 when add_generation_prompt=True)
must be is_sampled=False — they are template-injected scaffolding the
model continues from, not samples."""
msgs = [{"role": "user", "content": "Hi"}]
rendered = renderer.render(msgs, add_generation_prompt=True)
if not rendered.sampled_mask:
return
bad = [
k
for k, (msg_idx, is_sampled) in enumerate(
zip(rendered.message_indices, rendered.sampled_mask)
)
if msg_idx == -1 and is_sampled
]
assert not bad, (
f"{model_name}: generation-prompt tokens marked is_sampled=True "
f"at positions {bad[:8]}"
)
def test_sampled_mask_assistant_role_tag_excluded(model_name, renderer):
"""The leading ``<|im_start|>{role}\\n`` (or equivalent role-tag run)
on an assistant message must be is_sampled=False — the chat template
emits it as part of the generation prompt at inference, so the model
never samples it. Asserts that the *first* token attributed to an
assistant message is is_sampled=False; the last token (turn-close
signal) should be is_sampled=True."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello world!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return
assistant_positions = [
k for k, idx in enumerate(rendered.message_indices) if idx == 1
]
assert assistant_positions, (
f"{model_name}: no tokens attributed to assistant message"
)
first_k = assistant_positions[0]
assert not rendered.sampled_mask[first_k], (
f"{model_name}: first assistant-attributed token at k={first_k} "
f"should be is_sampled=False (role-tag scaffolding), but was True"
)
# At least one assistant-attributed token must be is_sampled=True
# (the content + turn close — otherwise the loss mask is empty).
any_sampled = any(rendered.sampled_mask[k] for k in assistant_positions)
assert any_sampled, (
f"{model_name}: no assistant tokens marked is_sampled=True — the "
f"resulting SFT loss mask would be empty"
)