Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
596c15ffd9 | ||
|
|
942449c37a | ||
|
|
9f3b24c0ac | ||
|
|
35c2407e92 | ||
|
|
a11f8d8193 |
+12
-1
@@ -79,13 +79,24 @@ dev = [
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
# Enforce a uv version that supports the friendly-duration form
|
||||
# (`"7 days"`) in the static pyproject parser. Older uvs silently parse
|
||||
# the value as an RFC 3339 date, emit a TOML parse warning, and proceed
|
||||
# *without* the cooldown — bypassing this security policy.
|
||||
required-version = ">=0.11.1"
|
||||
exclude-newer = "7 days"
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# fastokens 0.2.0 was published on 2026-05-17 and contains the
|
||||
# ``unpatch_transformers`` fix (crusoecloud/fastokens#32) needed for
|
||||
# MiniMax-M2's slow→fast tokenizer conversion path. Exempting it from
|
||||
# the project-wide 7-day cutoff lets the lockfile pick it up immediately
|
||||
# while the rest of the dependency graph stays gated.
|
||||
exclude-newer-package = { fastokens = false, "prime-pydantic-config" = false }
|
||||
fastokens = false
|
||||
# PrimeIntellect-published packages in this project's dependency closure —
|
||||
# fast-track so first-party releases can land same-day. Only packages that
|
||||
# appear in `uv tree` are listed.
|
||||
prime-pydantic-config = false
|
||||
|
||||
[tool.ty.environment]
|
||||
python-version = "3.13"
|
||||
|
||||
@@ -33,6 +33,7 @@ from renderers.base import (
|
||||
build_trajectory_step,
|
||||
create_renderer,
|
||||
create_renderer_pool,
|
||||
extract_message_tool_names,
|
||||
is_multimodal,
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
@@ -168,6 +169,7 @@ __all__ = [
|
||||
"config_from_name",
|
||||
"create_renderer",
|
||||
"create_renderer_pool",
|
||||
"extract_message_tool_names",
|
||||
"is_multimodal",
|
||||
"reject_assistant_in_extension",
|
||||
"trim_to_turn_close",
|
||||
|
||||
+102
-6
@@ -6,6 +6,7 @@ import io
|
||||
import logging
|
||||
import queue
|
||||
import threading
|
||||
from collections.abc import Mapping
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from typing import (
|
||||
@@ -117,6 +118,68 @@ class Message(TypedDict, total=False):
|
||||
reasoning_content: str
|
||||
|
||||
|
||||
def extract_message_tool_names(messages: list[Message]) -> list[str | None]:
|
||||
"""Per-message tool function names parallel to ``message_roles``.
|
||||
|
||||
Returns one entry per message: the function name for ``role="tool"``
|
||||
messages, ``None`` for every other message. Length matches the
|
||||
input list.
|
||||
|
||||
For tool messages the name is taken from ``msg["name"]`` when set
|
||||
(caller-provided), otherwise recovered by joining
|
||||
``msg["tool_call_id"]`` against any prior assistant's
|
||||
``tool_calls[i].function.name`` in the same list. Tool messages
|
||||
whose issuing assistant lives outside the provided list (e.g. on
|
||||
a :meth:`Renderer.bridge_to_next_turn` call where ``new_messages``
|
||||
covers only the new turn) resolve to ``None``.
|
||||
|
||||
Pure metadata: this never mutates the caller's messages and has
|
||||
no effect on the rendered token stream. It runs independently of
|
||||
the render path so the renderer can populate the field on
|
||||
:class:`RenderedTokens` without breaking HF byte parity for tool
|
||||
messages that carry no ``name``. Callers who *also* want the
|
||||
function name to appear in the rendered scaffold (e.g. GPT-OSS
|
||||
Harmony's ``functions.{name}`` prefix) must attach ``name`` to
|
||||
their tool messages before calling :meth:`Renderer.render`
|
||||
themselves — renderers don't synthesize ``name`` into the input,
|
||||
only into this metadata field.
|
||||
|
||||
Trainers join this list with :attr:`RenderedTokens.message_indices`
|
||||
to recover per-token tool attribution — the canonical use case is
|
||||
SFT on tool response bodies while RL acts only on assistant tokens
|
||||
(tool body tokens get a constant positive advantage so the model
|
||||
learns to anticipate tool outputs without learning to emit
|
||||
``<|tool_response>`` itself).
|
||||
|
||||
Per-message rather than per-token because the data is naturally
|
||||
per-message — storing it per-token would duplicate the same
|
||||
string across every body token of the same tool message.
|
||||
"""
|
||||
lookup: dict[str, str] = {}
|
||||
for m in messages:
|
||||
if not isinstance(m, Mapping) or m.get("role") != "assistant":
|
||||
continue
|
||||
for tc in m.get("tool_calls") or []:
|
||||
if not isinstance(tc, Mapping):
|
||||
continue
|
||||
tc_id = tc.get("id")
|
||||
fn = tc.get("function")
|
||||
tc_name = fn.get("name") if isinstance(fn, Mapping) else None
|
||||
if isinstance(tc_id, str) and isinstance(tc_name, str):
|
||||
lookup[tc_id] = tc_name
|
||||
out: list[str | None] = []
|
||||
for m in messages:
|
||||
if not isinstance(m, Mapping) or m.get("role") != "tool":
|
||||
out.append(None)
|
||||
continue
|
||||
name = m.get("name")
|
||||
if not (isinstance(name, str) and name):
|
||||
tc_id = m.get("tool_call_id")
|
||||
name = lookup.get(tc_id) if isinstance(tc_id, str) else None
|
||||
out.append(name if isinstance(name, str) and name else None)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Renderer data types
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -208,6 +271,32 @@ class RenderedTokens:
|
||||
renderer doesn't provide the signal. ``DefaultRenderer`` leaves it
|
||||
empty for the same reason.
|
||||
|
||||
``message_tool_names`` is the per-message tool function name list,
|
||||
parallel to ``message_roles`` (same length). For tool-role
|
||||
messages it carries the function name — either taken from
|
||||
``msg["name"]`` (caller-provided) or recovered by joining
|
||||
``msg["tool_call_id"]`` against a prior assistant's
|
||||
``tool_calls[i].function.name`` in the rendered slice. Every
|
||||
other message is ``None``, as are tool messages whose issuing
|
||||
assistant lives outside the rendered slice (e.g. on a
|
||||
:meth:`Renderer.bridge_to_next_turn` call where ``new_messages``
|
||||
covers only the new turn).
|
||||
|
||||
This is pure metadata, computed by :func:`extract_message_tool_names`
|
||||
independently of the render path: populating it never touches the
|
||||
rendered token stream, so HF chat-template byte parity is
|
||||
preserved for tool messages carrying no ``name``. Callers who
|
||||
*also* want the function name to appear in the rendered scaffold
|
||||
(e.g. GPT-OSS Harmony's ``functions.{name}`` prefix) must attach
|
||||
``name`` to their tool messages before calling
|
||||
:meth:`Renderer.render` themselves.
|
||||
|
||||
Trainers join this with ``message_indices`` to build per-tool
|
||||
selective loss masks (SFT on tool response bodies of a specific
|
||||
tool while RL acts on assistant tokens). Empty
|
||||
``message_tool_names`` (``[]``) means the renderer doesn't
|
||||
provide the signal.
|
||||
|
||||
``multi_modal_data`` is populated by multimodal renderers (e.g.
|
||||
``Qwen3VLRenderer``) when image / video content parts are present;
|
||||
text-only renderers leave it as ``None``.
|
||||
@@ -218,6 +307,7 @@ class RenderedTokens:
|
||||
sampled_mask: list[bool] = field(default_factory=list)
|
||||
is_content: list[bool] = field(default_factory=list)
|
||||
message_roles: list[str] = field(default_factory=list)
|
||||
message_tool_names: list[str | None] = field(default_factory=list)
|
||||
multi_modal_data: "MultiModalData | None" = None
|
||||
|
||||
def tokens_per_message(
|
||||
@@ -947,9 +1037,14 @@ MODEL_RENDERER_MAP: dict[str, str] = {
|
||||
"moonshotai/Kimi-K2-Instruct": "kimi-k2",
|
||||
"moonshotai/Kimi-K2.5": "kimi-k2.5",
|
||||
"moonshotai/Kimi-K2.6": "kimi-k2.5",
|
||||
# Nemotron 3.
|
||||
# Nemotron 3. Nano / Super share one chat-template variant; the Ultra
|
||||
# checkpoints use the Ultra variant — the renderer auto-selects it from
|
||||
# the model name (see ``nemotron3._ULTRA_DEFAULTS``). BF16 and FP8 share the
|
||||
# same tokenizer and template.
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "nemotron-3",
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "nemotron-3",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16": "nemotron-3",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8": "nemotron-3",
|
||||
# Poolside Laguna.
|
||||
"poolside/Laguna-XS.2": "laguna-xs.2",
|
||||
# GPT-OSS.
|
||||
@@ -1587,7 +1682,6 @@ def _get_offset_tokenizer(tokenizer):
|
||||
cached = _offset_tokenizers.get(name_or_path)
|
||||
if cached is not None:
|
||||
return cached
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
kwargs: dict[str, Any] = {}
|
||||
revision = TRUSTED_REVISIONS.get(name_or_path)
|
||||
@@ -1597,10 +1691,12 @@ def _get_offset_tokenizer(tokenizer):
|
||||
kwargs = {"trust_remote_code": False}
|
||||
# Explicitly vanilla — we want HF's Rust tokenizer with offset
|
||||
# tracking, not the fastokens shim. ``load_tokenizer`` would
|
||||
# patch fastokens in by default; calling
|
||||
# ``AutoTokenizer.from_pretrained`` directly here keeps the
|
||||
# fastokens patch out of this code path entirely.
|
||||
offset_tok = AutoTokenizer.from_pretrained(name_or_path, **kwargs)
|
||||
# patch fastokens in by default; routing through
|
||||
# ``_load_tokenizer_via_auto`` keeps the fastokens patch out
|
||||
# of this code path while still applying the config-build
|
||||
# fallback (RoPE-validation failures on nested
|
||||
# ``rope_parameters``, etc.).
|
||||
offset_tok = _load_tokenizer_via_auto(name_or_path, **kwargs)
|
||||
if not getattr(offset_tok, "is_fast", False):
|
||||
raise RuntimeError(
|
||||
f"Vanilla tokenizer for {name_or_path!r} is not a fast "
|
||||
|
||||
@@ -337,6 +337,26 @@ class Nemotron3RendererConfig(BaseRendererConfig):
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
ultra: bool | None = None
|
||||
"""Select the Nemotron-3 **Ultra** chat-template variant.
|
||||
|
||||
``None`` (default) auto-detects from the model name (see
|
||||
``renderers.nemotron3._ULTRA_DEFAULTS``): the Ultra checkpoints resolve
|
||||
to ``True``; Nano / Super and unknown checkpoints to ``False``. Set
|
||||
explicitly to force a variant — e.g. an Ultra fine-tune or a
|
||||
locally-pathed checkpoint whose ``name_or_path`` isn't in the table.
|
||||
|
||||
Ultra's template differs from Nano/Super: the reasoning block is glued
|
||||
as ``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around
|
||||
``</think>``), truncated historical turns collapse to
|
||||
``<think></think>{content}`` (no ``\\n``), and the thinking-truncation
|
||||
boundary follows the template's ``loop.index0 < last_user_idx`` rule
|
||||
(drop thinking on every assistant turn before the last user message).
|
||||
|
||||
Not a chat-template kwarg — it picks which template the renderer
|
||||
mirrors, not a variable passed into one — so it's listed in
|
||||
``_internal_fields`` and excluded from ``template_field_names()``."""
|
||||
|
||||
truncate_history_thinking: bool = True
|
||||
"""When ``False``, keep ``<think>{reasoning}</think>`` on past-cycle
|
||||
assistant turns instead of dropping them. Mirrors the chat
|
||||
@@ -344,6 +364,15 @@ class Nemotron3RendererConfig(BaseRendererConfig):
|
||||
``preserve_all_thinking`` / ``preserve_thinking_between_tool_calls``
|
||||
— see :class:`BaseRendererConfig` for the contract."""
|
||||
|
||||
# ``ultra`` is a template-variant SELECTOR — it picks which template the
|
||||
# renderer mirrors (Ultra vs Nano/Super), not a variable passed into one;
|
||||
# there is no ``ultra`` Jinja variable. Marked internal so the parity
|
||||
# matrix doesn't cross it as a template field. Same ``_internal_fields``
|
||||
# mechanism DeepSeek-V3 uses for its no-op ``enable_thinking``, for a
|
||||
# different underlying reason (theirs is an ignored kwarg, this is a
|
||||
# variant switch).
|
||||
_internal_fields = frozenset({"ultra"})
|
||||
|
||||
|
||||
class DeepSeekV3RendererConfig(BaseRendererConfig):
|
||||
"""DeepSeek V3 renderer config.
|
||||
|
||||
@@ -22,6 +22,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
@@ -247,6 +248,7 @@ class DeepSeekV3Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -390,6 +392,7 @@ class DeepSeekV3Renderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -18,6 +18,7 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
)
|
||||
from renderers.configs import DefaultRendererConfig
|
||||
from renderers.parsers import (
|
||||
@@ -141,6 +142,7 @@ class DefaultRenderer:
|
||||
token_ids=token_ids,
|
||||
message_indices=message_indices,
|
||||
message_roles=message_roles,
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def _apply(self, messages, *, tools=None, add_generation_prompt=False) -> list[int]:
|
||||
|
||||
@@ -21,6 +21,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
)
|
||||
@@ -265,6 +266,7 @@ class GLM45Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -445,6 +447,7 @@ class GLM45Renderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
|
||||
@@ -22,6 +22,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
)
|
||||
@@ -281,6 +282,7 @@ class GLM5Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -456,6 +458,7 @@ class GLM5Renderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
|
||||
@@ -56,6 +56,7 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
@@ -465,6 +466,7 @@ class GptOssRenderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -594,6 +596,7 @@ class GptOssRenderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
# ── message conversion ───────────────────────────────────────────────────
|
||||
|
||||
@@ -23,6 +23,7 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
@@ -305,6 +306,7 @@ class KimiK2Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in caller_messages],
|
||||
message_tool_names=extract_message_tool_names(caller_messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -454,6 +456,7 @@ class KimiK2Renderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
|
||||
@@ -36,6 +36,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolCallParseStatus,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
@@ -946,6 +947,7 @@ class KimiK25Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -1188,6 +1190,7 @@ class KimiK25Renderer:
|
||||
merged_items.setdefault(modality, []).extend(vals)
|
||||
|
||||
bridge_roles = [m.get("role") or "" for m in new_messages]
|
||||
bridge_tool_names = extract_message_tool_names(new_messages)
|
||||
if not (merged_hashes or merged_placeholders or merged_items):
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
@@ -1195,6 +1198,7 @@ class KimiK25Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
)
|
||||
|
||||
mm_data = MultiModalData(
|
||||
@@ -1208,6 +1212,7 @@ class KimiK25Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
)
|
||||
from renderers.configs import LagunaXS2RendererConfig
|
||||
@@ -275,6 +276,7 @@ class LagunaXS2Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -426,6 +428,7 @@ class LagunaXS2Renderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
|
||||
@@ -22,6 +22,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
@@ -278,6 +279,7 @@ class MiniMaxM2Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -459,6 +461,7 @@ class MiniMaxM2Renderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
|
||||
+71
-9
@@ -25,6 +25,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
@@ -74,6 +75,35 @@ def _render_extra_keys(obj: dict[str, Any], handled_keys: set[str]) -> list[str]
|
||||
return lines
|
||||
|
||||
|
||||
# Per-model ``ultra`` default, applied when the renderer config leaves it
|
||||
# ``None``. The Nemotron-3 family ships two chat-template variants: Nano /
|
||||
# Super share one; Ultra differs in the reasoning-block glue (no ``\n`` around
|
||||
# ``</think>``) and the thinking-truncation boundary (drop thinking on every
|
||||
# assistant turn before the last user message). BF16 and FP8 share the same
|
||||
# tokenizer and template. Hard-coded keyed by
|
||||
# ``tokenizer.name_or_path`` rather than probed from the live template — the
|
||||
# same convention as Qwen3.5's ``_ENABLE_THINKING_DEFAULTS`` (avoids pulling
|
||||
# ``apply_chat_template`` onto the construction hot path and keeps
|
||||
# bring-your-own-tokenizer use working).
|
||||
_ULTRA_DEFAULTS: dict[str, bool] = {
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": False,
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": False,
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16": True,
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8": True,
|
||||
}
|
||||
|
||||
|
||||
def _default_ultra(tokenizer) -> bool:
|
||||
"""Hard-coded ``ultra`` default for ``tokenizer``'s model.
|
||||
|
||||
Falls back to ``False`` (the Nano / Super template, and the majority of
|
||||
the family) for unknown / fine-tuned checkpoints whose ``name_or_path``
|
||||
isn't in ``_ULTRA_DEFAULTS`` — pass an explicit ``ultra=True`` for an
|
||||
Ultra fine-tune or a locally-pathed Ultra checkpoint.
|
||||
"""
|
||||
return _ULTRA_DEFAULTS.get(getattr(tokenizer, "name_or_path", ""), False)
|
||||
|
||||
|
||||
class Nemotron3Renderer:
|
||||
"""Deterministic message → token renderer for Nemotron 3 models."""
|
||||
|
||||
@@ -83,7 +113,14 @@ class Nemotron3Renderer:
|
||||
config: Nemotron3RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or Nemotron3RendererConfig()
|
||||
cfg = config or Nemotron3RendererConfig()
|
||||
# ``ultra=None`` defers to the model's known default (see
|
||||
# ``_ULTRA_DEFAULTS``). Materialise here so downstream reads see a
|
||||
# concrete bool; rebind the frozen config with the resolved value so
|
||||
# introspection sees the same.
|
||||
if cfg.ultra is None:
|
||||
cfg = cfg.model_copy(update={"ultra": _default_ultra(tokenizer)})
|
||||
self.config = cfg
|
||||
|
||||
# Look up special token IDs from the tokenizer (not hardcoded).
|
||||
# <|endoftext|> is optional: Nemotron-3 Nano / Super tokenizers ship
|
||||
@@ -334,6 +371,17 @@ class Nemotron3Renderer:
|
||||
last_plain_assistant_idx = j
|
||||
break
|
||||
|
||||
# Ultra truncates thinking on every assistant turn *before the last
|
||||
# user message* (template rule ``loop.index0 < last_user_idx``),
|
||||
# whereas Nano/Super preserve only the last plain assistant. Compute
|
||||
# the last-user index over the normalized ``messages`` list (a leading
|
||||
# system never holds a user, so the relative comparison is unaffected).
|
||||
last_user_idx_norm = -1
|
||||
for j in range(len(messages) - 1, -1, -1):
|
||||
if messages[j].get("role") == "user":
|
||||
last_user_idx_norm = j
|
||||
break
|
||||
|
||||
# ── 2. Iterate messages ─────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
role = msg["role"]
|
||||
@@ -359,7 +407,10 @@ class Nemotron3Renderer:
|
||||
emit_text("\n", msg_orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
is_last_turn = i >= last_plain_assistant_idx
|
||||
if self.config.ultra:
|
||||
is_last_turn = i >= last_user_idx_norm
|
||||
else:
|
||||
is_last_turn = i >= last_plain_assistant_idx
|
||||
preserve_thinking = msg_orig_idx >= 0 and should_preserve_past_thinking(
|
||||
original_messages,
|
||||
msg_orig_idx,
|
||||
@@ -411,6 +462,7 @@ class Nemotron3Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in original_messages],
|
||||
message_tool_names=extract_message_tool_names(original_messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -581,6 +633,7 @@ class Nemotron3Renderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -614,6 +667,7 @@ class Nemotron3Renderer:
|
||||
content = after_think_end.lstrip("\n")
|
||||
|
||||
reasoning_content = reasoning_content.strip()
|
||||
ultra = self.config.ultra
|
||||
|
||||
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
|
||||
# at inference the chat template emits these as the generation
|
||||
@@ -642,28 +696,36 @@ class Nemotron3Renderer:
|
||||
or not self.config.truncate_history_thinking
|
||||
):
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
# Ultra: <think>\n{reasoning}</think>{content} (no \n around </think>).
|
||||
# Nano/Super: <think>\n{reasoning}\n</think>\n{content}.
|
||||
emit_text(
|
||||
"\n" + reasoning_content + "\n",
|
||||
("\n" + reasoning_content)
|
||||
if ultra
|
||||
else ("\n" + reasoning_content + "\n"),
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
# Single \n separator (not \n\n like Qwen3.5)
|
||||
# Single \n separator (not \n\n like Qwen3.5); Ultra glues directly.
|
||||
emit_text(
|
||||
"\n" + content + content_suffix,
|
||||
(content + content_suffix)
|
||||
if ultra
|
||||
else ("\n" + content + content_suffix),
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
elif reasoning_content:
|
||||
# Historical assistant whose reasoning got stripped — template
|
||||
# keeps a single \n between the collapsed <think></think> and
|
||||
# the content as a marker that reasoning existed.
|
||||
# Historical assistant whose reasoning got stripped. Nano/Super keep
|
||||
# a single \n between the collapsed <think></think> and the content
|
||||
# as a marker that reasoning existed; Ultra glues content directly.
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n" + content + content_suffix,
|
||||
(content + content_suffix)
|
||||
if ultra
|
||||
else ("\n" + content + content_suffix),
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
|
||||
@@ -19,6 +19,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
@@ -247,6 +248,7 @@ class Qwen3Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -403,6 +405,7 @@ class Qwen3Renderer:
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
|
||||
@@ -27,6 +27,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
@@ -565,6 +566,7 @@ class Qwen35Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -841,6 +843,7 @@ class Qwen35Renderer:
|
||||
merged_items.setdefault(modality, []).extend(vals)
|
||||
|
||||
bridge_roles = [m.get("role") or "" for m in new_messages]
|
||||
bridge_tool_names = extract_message_tool_names(new_messages)
|
||||
if not (merged_hashes or merged_placeholders or merged_items):
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
@@ -848,6 +851,7 @@ class Qwen35Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
)
|
||||
|
||||
mm_data = MultiModalData(
|
||||
@@ -861,6 +865,7 @@ class Qwen35Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
@@ -604,6 +605,7 @@ class Qwen3VLRenderer:
|
||||
sampled_mask=em.sampled,
|
||||
is_content=em.is_content,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -839,6 +841,7 @@ class Qwen3VLRenderer:
|
||||
sampled_mask=em.sampled,
|
||||
is_content=em.is_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ RENDERER_MODELS = [
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
|
||||
# Ultra resolves the Ultra template variant via name (auto → ultra=True).
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Tests for ``RenderedTokens.message_tool_names`` and its populating helper.
|
||||
|
||||
``message_tool_names`` is a per-message sidecar parallel to
|
||||
``message_roles``: for each tool-role message in the rendered slice
|
||||
it carries the tool function name, ``None`` everywhere else. The name
|
||||
comes from ``msg["name"]`` when set, otherwise from a
|
||||
``tool_call_id`` join against any prior assistant's ``tool_calls`` in
|
||||
the same slice. Pure metadata — does not affect the rendered token
|
||||
stream, does not mutate the caller's messages.
|
||||
|
||||
Unit tests below cover the join's case matrix without a tokenizer.
|
||||
The single integration test runs every renderer in the conftest
|
||||
matrix to catch any of the ~25 ``RenderedTokens(...)`` construction
|
||||
sites that might fail to wire the field through.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from renderers.base import extract_message_tool_names
|
||||
|
||||
|
||||
def test_extract_empty():
|
||||
assert extract_message_tool_names([]) == []
|
||||
|
||||
|
||||
def test_extract_caller_provided_name_wins():
|
||||
"""``msg['name']`` set by the caller is used verbatim — no join attempted."""
|
||||
messages = [
|
||||
{"role": "tool", "tool_call_id": "c1", "name": "caller_set", "content": "x"},
|
||||
]
|
||||
assert extract_message_tool_names(messages) == ["caller_set"]
|
||||
|
||||
|
||||
def test_extract_resolves_from_prior_assistant():
|
||||
"""Tool message without ``name``: recovered via tool_call_id → assistant.tool_calls."""
|
||||
messages = [
|
||||
{"role": "user", "content": "go"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_calls": [{"id": "c1", "function": {"name": "screenshot"}}],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "c1", "content": "ok"},
|
||||
]
|
||||
assert extract_message_tool_names(messages) == [None, None, "screenshot"]
|
||||
|
||||
|
||||
def test_extract_orphan_tool_message_is_none():
|
||||
"""``tool_call_id`` matching no in-slice assistant resolves to ``None``
|
||||
(bridge case: the issuing assistant lives in the prior portion that
|
||||
``new_messages`` doesn't cover).
|
||||
"""
|
||||
messages = [{"role": "tool", "tool_call_id": "orphan", "content": "x"}]
|
||||
assert extract_message_tool_names(messages) == [None]
|
||||
|
||||
|
||||
def test_extract_does_not_mutate_caller():
|
||||
"""Caller's tool message must not gain a ``name`` field after extraction —
|
||||
the helper produces a sidecar list, not a mutated view of the input.
|
||||
"""
|
||||
messages = [
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_calls": [{"id": "c1", "function": {"name": "f"}}],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "c1", "content": "x"},
|
||||
]
|
||||
extract_message_tool_names(messages)
|
||||
assert "name" not in messages[1]
|
||||
|
||||
|
||||
def test_renderer_populates_message_tool_names(model_name, renderer):
|
||||
"""Every renderer wires ``message_tool_names`` through ``RenderedTokens``.
|
||||
|
||||
Catches missed wire-up at any of the ~25 ``RenderedTokens(...)``
|
||||
construction sites across concrete renderers. The input is
|
||||
spec-conformant (tool message carries ``tool_call_id`` but no
|
||||
``name``) so the resolution path exercises the internal join.
|
||||
"""
|
||||
messages = [
|
||||
{"role": "user", "content": "go"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "c1",
|
||||
"type": "function",
|
||||
"function": {"name": "screenshot", "arguments": {}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "c1", "content": "ok"},
|
||||
]
|
||||
rt = renderer.render(messages)
|
||||
assert rt.message_tool_names == [None, None, "screenshot"], (
|
||||
f"{model_name}: got {rt.message_tool_names}"
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Offline wiring tests for the Nemotron-3 Ultra template variant.
|
||||
|
||||
Assert the name-based ``ultra`` auto-selection, the model→renderer mapping,
|
||||
and the typed-config surface WITHOUT loading any tokenizer (no network). This
|
||||
pins the wiring the parity matrix can't reach — in particular the FP8 entry,
|
||||
which no test loads a tokenizer for — so it can't silently rot.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
from renderers.configs import Nemotron3RendererConfig
|
||||
from renderers.nemotron3 import _ULTRA_DEFAULTS, _default_ultra
|
||||
|
||||
_ULTRA_REPOS = [
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8",
|
||||
]
|
||||
_NON_ULTRA_REPOS = [
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
|
||||
]
|
||||
|
||||
|
||||
def _fake_tok(name):
|
||||
return SimpleNamespace(name_or_path=name)
|
||||
|
||||
|
||||
def test_ultra_and_non_ultra_models_map_to_nemotron3():
|
||||
for repo in _ULTRA_REPOS + _NON_ULTRA_REPOS:
|
||||
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3", repo
|
||||
|
||||
|
||||
def test_default_ultra_resolves_by_name():
|
||||
# Ultra checkpoints (incl. the gated FP8 repo) resolve True.
|
||||
for repo in _ULTRA_REPOS:
|
||||
assert _ULTRA_DEFAULTS[repo] is True
|
||||
assert _default_ultra(_fake_tok(repo)) is True
|
||||
# Nano / Super resolve False (the shared Nano/Super template).
|
||||
for repo in _NON_ULTRA_REPOS:
|
||||
assert _default_ultra(_fake_tok(repo)) is False
|
||||
# Unknown / fine-tuned / local-path checkpoints fall back to False;
|
||||
# those must pass an explicit ultra= if they need the Ultra template.
|
||||
assert _default_ultra(_fake_tok("acme/my-nemotron-ultra-ft")) is False
|
||||
assert _default_ultra(_fake_tok("/home/user/local-ckpt")) is False
|
||||
assert _default_ultra(SimpleNamespace()) is False # no name_or_path attr
|
||||
|
||||
|
||||
def test_ultra_is_not_a_template_kwarg():
|
||||
fields = Nemotron3RendererConfig.template_field_names()
|
||||
assert "ultra" not in fields
|
||||
assert fields == frozenset({"enable_thinking", "truncate_history_thinking"})
|
||||
assert "ultra" in Nemotron3RendererConfig._internal_fields
|
||||
|
||||
|
||||
def test_ultra_config_default_is_none_and_overridable():
|
||||
assert Nemotron3RendererConfig().ultra is None # None => auto-detect by name
|
||||
assert Nemotron3RendererConfig(ultra=True).ultra is True
|
||||
assert Nemotron3RendererConfig(ultra=False).ultra is False
|
||||
@@ -55,6 +55,9 @@ _RENDERER_MODELS = [
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("deepseek-ai/DeepSeek-V3", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
# Ultra: auto-resolves to the Ultra template variant (ultra=True) via the
|
||||
# model name; parity asserted against the Ultra apply_chat_template.
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
]
|
||||
|
||||
@@ -43,6 +43,9 @@ _ROUNDTRIP_MODELS = [
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
|
||||
# Ultra: parse must recover content after a </think> glued directly to it
|
||||
# (no separating newline) — the Ultra-specific glue stresses the round-trip.
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
|
||||
|
||||
Reference in New Issue
Block a user