Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
596c15ffd9 | ||
|
|
942449c37a | ||
|
|
9f3b24c0ac | ||
|
|
35c2407e92 | ||
|
|
a11f8d8193 | ||
|
|
89ab3f0bed | ||
|
|
e729baa5af |
+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",
|
||||
|
||||
+173
-14
@@ -6,6 +6,7 @@ import io
|
||||
import logging
|
||||
import queue
|
||||
import threading
|
||||
from collections.abc import Mapping
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from typing import (
|
||||
@@ -117,6 +118,68 @@ class Message(TypedDict, total=False):
|
||||
reasoning_content: str
|
||||
|
||||
|
||||
def extract_message_tool_names(messages: list[Message]) -> list[str | None]:
|
||||
"""Per-message tool function names parallel to ``message_roles``.
|
||||
|
||||
Returns one entry per message: the function name for ``role="tool"``
|
||||
messages, ``None`` for every other message. Length matches the
|
||||
input list.
|
||||
|
||||
For tool messages the name is taken from ``msg["name"]`` when set
|
||||
(caller-provided), otherwise recovered by joining
|
||||
``msg["tool_call_id"]`` against any prior assistant's
|
||||
``tool_calls[i].function.name`` in the same list. Tool messages
|
||||
whose issuing assistant lives outside the provided list (e.g. on
|
||||
a :meth:`Renderer.bridge_to_next_turn` call where ``new_messages``
|
||||
covers only the new turn) resolve to ``None``.
|
||||
|
||||
Pure metadata: this never mutates the caller's messages and has
|
||||
no effect on the rendered token stream. It runs independently of
|
||||
the render path so the renderer can populate the field on
|
||||
:class:`RenderedTokens` without breaking HF byte parity for tool
|
||||
messages that carry no ``name``. Callers who *also* want the
|
||||
function name to appear in the rendered scaffold (e.g. GPT-OSS
|
||||
Harmony's ``functions.{name}`` prefix) must attach ``name`` to
|
||||
their tool messages before calling :meth:`Renderer.render`
|
||||
themselves — renderers don't synthesize ``name`` into the input,
|
||||
only into this metadata field.
|
||||
|
||||
Trainers join this list with :attr:`RenderedTokens.message_indices`
|
||||
to recover per-token tool attribution — the canonical use case is
|
||||
SFT on tool response bodies while RL acts only on assistant tokens
|
||||
(tool body tokens get a constant positive advantage so the model
|
||||
learns to anticipate tool outputs without learning to emit
|
||||
``<|tool_response>`` itself).
|
||||
|
||||
Per-message rather than per-token because the data is naturally
|
||||
per-message — storing it per-token would duplicate the same
|
||||
string across every body token of the same tool message.
|
||||
"""
|
||||
lookup: dict[str, str] = {}
|
||||
for m in messages:
|
||||
if not isinstance(m, Mapping) or m.get("role") != "assistant":
|
||||
continue
|
||||
for tc in m.get("tool_calls") or []:
|
||||
if not isinstance(tc, Mapping):
|
||||
continue
|
||||
tc_id = tc.get("id")
|
||||
fn = tc.get("function")
|
||||
tc_name = fn.get("name") if isinstance(fn, Mapping) else None
|
||||
if isinstance(tc_id, str) and isinstance(tc_name, str):
|
||||
lookup[tc_id] = tc_name
|
||||
out: list[str | None] = []
|
||||
for m in messages:
|
||||
if not isinstance(m, Mapping) or m.get("role") != "tool":
|
||||
out.append(None)
|
||||
continue
|
||||
name = m.get("name")
|
||||
if not (isinstance(name, str) and name):
|
||||
tc_id = m.get("tool_call_id")
|
||||
name = lookup.get(tc_id) if isinstance(tc_id, str) else None
|
||||
out.append(name if isinstance(name, str) and name else None)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Renderer data types
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -208,6 +271,32 @@ class RenderedTokens:
|
||||
renderer doesn't provide the signal. ``DefaultRenderer`` leaves it
|
||||
empty for the same reason.
|
||||
|
||||
``message_tool_names`` is the per-message tool function name list,
|
||||
parallel to ``message_roles`` (same length). For tool-role
|
||||
messages it carries the function name — either taken from
|
||||
``msg["name"]`` (caller-provided) or recovered by joining
|
||||
``msg["tool_call_id"]`` against a prior assistant's
|
||||
``tool_calls[i].function.name`` in the rendered slice. Every
|
||||
other message is ``None``, as are tool messages whose issuing
|
||||
assistant lives outside the rendered slice (e.g. on a
|
||||
:meth:`Renderer.bridge_to_next_turn` call where ``new_messages``
|
||||
covers only the new turn).
|
||||
|
||||
This is pure metadata, computed by :func:`extract_message_tool_names`
|
||||
independently of the render path: populating it never touches the
|
||||
rendered token stream, so HF chat-template byte parity is
|
||||
preserved for tool messages carrying no ``name``. Callers who
|
||||
*also* want the function name to appear in the rendered scaffold
|
||||
(e.g. GPT-OSS Harmony's ``functions.{name}`` prefix) must attach
|
||||
``name`` to their tool messages before calling
|
||||
:meth:`Renderer.render` themselves.
|
||||
|
||||
Trainers join this with ``message_indices`` to build per-tool
|
||||
selective loss masks (SFT on tool response bodies of a specific
|
||||
tool while RL acts on assistant tokens). Empty
|
||||
``message_tool_names`` (``[]``) means the renderer doesn't
|
||||
provide the signal.
|
||||
|
||||
``multi_modal_data`` is populated by multimodal renderers (e.g.
|
||||
``Qwen3VLRenderer``) when image / video content parts are present;
|
||||
text-only renderers leave it as ``None``.
|
||||
@@ -218,6 +307,7 @@ class RenderedTokens:
|
||||
sampled_mask: list[bool] = field(default_factory=list)
|
||||
is_content: list[bool] = field(default_factory=list)
|
||||
message_roles: list[str] = field(default_factory=list)
|
||||
message_tool_names: list[str | None] = field(default_factory=list)
|
||||
multi_modal_data: "MultiModalData | None" = None
|
||||
|
||||
def tokens_per_message(
|
||||
@@ -911,8 +1001,8 @@ MODEL_RENDERER_MAP: dict[str, str] = {
|
||||
# ``enable_thinking=true`` (open ``<think>\n`` at the gen prompt);
|
||||
# the smaller 0.8B / 2B variants flip the polarity (default
|
||||
# ``enable_thinking=false``, empty ``<think>\n\n</think>\n\n``).
|
||||
# ``Qwen35Renderer`` auto-detects polarity from the tokenizer's
|
||||
# chat_template at construction, so all seven sizes are
|
||||
# ``Qwen35Renderer`` hard-codes this polarity per model
|
||||
# (``_ENABLE_THINKING_DEFAULTS``), so all seven sizes are
|
||||
# token-for-token parity-tested against their own
|
||||
# ``apply_chat_template`` — including with
|
||||
# ``add_generation_prompt=True``.
|
||||
@@ -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.
|
||||
@@ -1089,7 +1184,6 @@ def _patched_load(model_name_or_path: str, **kwargs):
|
||||
path is still discoverable in logs.
|
||||
"""
|
||||
import fastokens
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
global _FASTOKENS_ANNOUNCED
|
||||
|
||||
@@ -1102,13 +1196,72 @@ def _patched_load(model_name_or_path: str, **kwargs):
|
||||
)
|
||||
_FASTOKENS_ANNOUNCED = True
|
||||
try:
|
||||
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
|
||||
return _load_tokenizer_via_auto(model_name_or_path, **kwargs)
|
||||
finally:
|
||||
with _FASTOKENS_PATCH_LOCK:
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
fastokens.unpatch_transformers()
|
||||
|
||||
|
||||
def _load_fast_tokenizer_directly(
|
||||
model_name_or_path: str, revision: str | None
|
||||
) -> Any | None:
|
||||
"""Load a self-contained fast tokenizer without building the model config.
|
||||
|
||||
``AutoTokenizer.from_pretrained`` eagerly constructs the *model* config to
|
||||
resolve the tokenizer class — even for a plain ``PreTrainedTokenizerFast``.
|
||||
That construction can raise on modeling-only concerns the tokenizer never
|
||||
needs (e.g. RoPE parameter validation for configs that carry nested
|
||||
``rope_parameters``). When the repo ships a complete ``tokenizer.json`` and
|
||||
declares no custom tokenizer, the tokenizer is fully self-describing, so we
|
||||
load it directly and skip the config detour.
|
||||
|
||||
Returns ``None`` when there's nothing safe to load this way — a custom
|
||||
``auto_map`` tokenizer (which must run through ``AutoTokenizer`` with
|
||||
``trust_remote_code``) or no fast tokenizer at all — so the caller can
|
||||
surface its original error instead.
|
||||
"""
|
||||
from transformers import PreTrainedTokenizerFast
|
||||
from transformers.models.auto.tokenization_auto import get_tokenizer_config
|
||||
|
||||
try:
|
||||
if "auto_map" in get_tokenizer_config(model_name_or_path, revision=revision):
|
||||
return None
|
||||
return PreTrainedTokenizerFast.from_pretrained(
|
||||
model_name_or_path, revision=revision
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _load_tokenizer_via_auto(model_name_or_path: str, **kwargs) -> Any:
|
||||
"""``AutoTokenizer.from_pretrained`` with a config-free fallback.
|
||||
|
||||
renderers needs the tokenizer, not the model. If ``AutoTokenizer`` fails
|
||||
while building the model config it loads to resolve the tokenizer class,
|
||||
retry by loading the repo's self-contained ``tokenizer.json`` directly. The
|
||||
original error is re-raised if the repo has no such tokenizer.
|
||||
"""
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
try:
|
||||
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
|
||||
except Exception as exc:
|
||||
tok = _load_fast_tokenizer_directly(
|
||||
model_name_or_path, revision=kwargs.get("revision")
|
||||
)
|
||||
if tok is None:
|
||||
raise
|
||||
logger.debug(
|
||||
"AutoTokenizer.from_pretrained(%r) failed building the model config "
|
||||
"(%s: %s); loaded the tokenizer directly from tokenizer.json.",
|
||||
model_name_or_path,
|
||||
type(exc).__name__,
|
||||
str(exc)[:160],
|
||||
)
|
||||
return tok
|
||||
|
||||
|
||||
def load_tokenizer(
|
||||
model_name_or_path: str,
|
||||
*,
|
||||
@@ -1138,9 +1291,14 @@ def load_tokenizer(
|
||||
fastokens raises during the patched load (e.g. an unknown
|
||||
pre-tokenizer type), we automatically retry with the vanilla
|
||||
backend and emit an INFO log.
|
||||
"""
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
``AutoTokenizer.from_pretrained`` eagerly builds the model config to
|
||||
resolve the tokenizer class. If that construction raises on a
|
||||
modeling-only concern the tokenizer doesn't need (e.g. RoPE
|
||||
validation for configs with nested ``rope_parameters``), we fall
|
||||
back to loading the repo's self-contained ``tokenizer.json``
|
||||
directly — see ``_load_tokenizer_via_auto``.
|
||||
"""
|
||||
kwargs: dict[str, Any] = {}
|
||||
revision = TRUSTED_REVISIONS.get(model_name_or_path)
|
||||
if revision is not None:
|
||||
@@ -1149,7 +1307,7 @@ def load_tokenizer(
|
||||
kwargs = {"trust_remote_code": False}
|
||||
|
||||
if not use_fastokens or model_name_or_path in FASTOKENS_INCOMPATIBLE:
|
||||
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
|
||||
return _load_tokenizer_via_auto(model_name_or_path, **kwargs)
|
||||
|
||||
try:
|
||||
return _patched_load(model_name_or_path, **kwargs)
|
||||
@@ -1162,7 +1320,7 @@ def load_tokenizer(
|
||||
type(exc).__name__,
|
||||
str(exc)[:160],
|
||||
)
|
||||
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
|
||||
return _load_tokenizer_via_auto(model_name_or_path, **kwargs)
|
||||
|
||||
|
||||
def _populate_registry():
|
||||
@@ -1524,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)
|
||||
@@ -1534,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(
|
||||
|
||||
+44
-34
@@ -27,6 +27,7 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
@@ -66,39 +67,44 @@ _TOOLS_INSTRUCTIONS = (
|
||||
)
|
||||
|
||||
|
||||
def _detect_enable_thinking_default(tokenizer: PreTrainedTokenizer) -> bool:
|
||||
"""Probe the tokenizer's chat template to learn its ``enable_thinking``
|
||||
default polarity at the generation-prompt boundary.
|
||||
# Per-model ``enable_thinking`` default, applied when the renderer config
|
||||
# leaves it ``None``. The Qwen3.5 family ships two chat-template variants
|
||||
# that differ only in the polarity of the gated thinking branch:
|
||||
#
|
||||
# * Big sizes (4B / 9B / 35B-A3B / 122B-A10B / 397B-A17B) default
|
||||
# ``enable_thinking=true`` — an open ``<think>\n`` at the gen prompt.
|
||||
# * Small sizes (0.8B / 2B) flip it — default ``false``, emitting the
|
||||
# empty ``<think>\n\n</think>\n\n`` block.
|
||||
#
|
||||
# These are hard-coded (keyed by ``tokenizer.name_or_path``) rather than
|
||||
# probed from the live ``chat_template``: probing meant calling
|
||||
# ``apply_chat_template`` at construction, which pulls ``transformers`` onto
|
||||
# the hot path and breaks bring-your-own-tokenizer use. The values are the
|
||||
# ground truth pinned by ``tests/test_qwen35_size_coverage.py`` — both the
|
||||
# polarity assertions and byte-parity against each size's own
|
||||
# ``apply_chat_template``.
|
||||
_ENABLE_THINKING_DEFAULTS: dict[str, bool] = {
|
||||
"Qwen/Qwen3.5-0.8B": False,
|
||||
"Qwen/Qwen3.5-2B": False,
|
||||
"Qwen/Qwen3.5-4B": True,
|
||||
"Qwen/Qwen3.5-9B": True,
|
||||
"Qwen/Qwen3.5-35B-A3B": True,
|
||||
"Qwen/Qwen3.5-122B-A10B": True,
|
||||
"Qwen/Qwen3.5-397B-A17B": True,
|
||||
# Qwen3.6 extends the Qwen3.5 template; same big-size polarity.
|
||||
"Qwen/Qwen3.6-35B-A3B": True,
|
||||
}
|
||||
|
||||
The Qwen3.5 family ships two template variants that differ only in the
|
||||
polarity of the gated branch:
|
||||
|
||||
* Big sizes (4B / 9B / 35B-A3B / 122B-A10B / 397B-A17B) emit an open
|
||||
``<think>\\n`` by default and the empty ``<think>\\n\\n</think>\\n\\n``
|
||||
block when ``enable_thinking`` is explicitly false.
|
||||
* Small sizes (0.8B / 2B) flip the polarity — they emit the empty
|
||||
block by default and the open ``<think>\\n`` only when
|
||||
``enable_thinking`` is explicitly true.
|
||||
def _default_enable_thinking(tokenizer) -> bool:
|
||||
"""Hard-coded ``enable_thinking`` default for ``tokenizer``'s model.
|
||||
|
||||
A one-shot ``apply_chat_template`` call with no flag and a minimal
|
||||
user message reveals which variant is in use: the empty-block tail
|
||||
ends with ``</think>``, the open-think tail does not. Failing the
|
||||
probe (no chat_template, exotic config) falls back to the big-model
|
||||
default of True, which matches every entry in
|
||||
``MODEL_RENDERER_MAP`` that routes to ``qwen3.5`` without explicit
|
||||
polarity awareness.
|
||||
Falls back to ``True`` (the big-model default, and the majority of the
|
||||
family) for unknown / fine-tuned checkpoints whose ``name_or_path`` isn't
|
||||
in ``_ENABLE_THINKING_DEFAULTS``; pass an explicit ``enable_thinking=`` to
|
||||
a small-size fine-tune that needs ``False``.
|
||||
"""
|
||||
try:
|
||||
out = tokenizer.apply_chat_template(
|
||||
[{"role": "user", "content": "x"}],
|
||||
tokenize=False,
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
except Exception:
|
||||
return True
|
||||
if not isinstance(out, str):
|
||||
return True
|
||||
return not out.rstrip().endswith("</think>")
|
||||
return _ENABLE_THINKING_DEFAULTS.get(getattr(tokenizer, "name_or_path", ""), True)
|
||||
|
||||
|
||||
class Qwen35Renderer:
|
||||
@@ -116,13 +122,13 @@ class Qwen35Renderer:
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
cfg = config or type(self)._config_cls()
|
||||
# ``enable_thinking=None`` defers to the tokenizer's chat-template
|
||||
# default (Instruct → off, Thinking → on). Materialise here so
|
||||
# downstream reads see a concrete bool; rebind the config with
|
||||
# the resolved value so introspection sees the same.
|
||||
# ``enable_thinking=None`` defers to the model's known default (see
|
||||
# ``_ENABLE_THINKING_DEFAULTS``). Materialise here so downstream reads
|
||||
# see a concrete bool; rebind the config with the resolved value so
|
||||
# introspection sees the same.
|
||||
if cfg.enable_thinking is None:
|
||||
cfg = cfg.model_copy(
|
||||
update={"enable_thinking": _detect_enable_thinking_default(tokenizer)}
|
||||
update={"enable_thinking": _default_enable_thinking(tokenizer)}
|
||||
)
|
||||
self.config = cfg
|
||||
|
||||
@@ -560,6 +566,7 @@ class Qwen35Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -836,6 +843,7 @@ class Qwen35Renderer:
|
||||
merged_items.setdefault(modality, []).extend(vals)
|
||||
|
||||
bridge_roles = [m.get("role") or "" for m in new_messages]
|
||||
bridge_tool_names = extract_message_tool_names(new_messages)
|
||||
if not (merged_hashes or merged_placeholders or merged_items):
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
@@ -843,6 +851,7 @@ class Qwen35Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
)
|
||||
|
||||
mm_data = MultiModalData(
|
||||
@@ -856,6 +865,7 @@ class Qwen35Renderer:
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -5,9 +5,8 @@ Seven Qwen3.5 sizes route to ``Qwen35Renderer``. The 4B / 9B / 35B-A3B /
|
||||
``enable_thinking=true``); the smaller 0.8B / 2B sizes ship the polarity-
|
||||
flipped variant (default ``enable_thinking=false`` → empty
|
||||
``<think>\\n\\n</think>\\n\\n`` at the gen-prompt boundary). The renderer
|
||||
detects polarity from the tokenizer's chat_template at construction, so
|
||||
both variants render byte-identical to their own
|
||||
``apply_chat_template``.
|
||||
hard-codes this polarity per model (``_ENABLE_THINKING_DEFAULTS``), so
|
||||
both variants render byte-identical to their own ``apply_chat_template``.
|
||||
|
||||
These tests lock in (a) the exact set of Qwen3.5 sizes in the map and
|
||||
(b) byte parity for every one of them across representative
|
||||
@@ -57,7 +56,7 @@ def test_no_other_qwen35_sizes_silently_added():
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Polarity auto-detection: 0.8B / 2B flip ``enable_thinking`` default.
|
||||
# Polarity defaults: 0.8B / 2B flip ``enable_thinking`` default.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -73,10 +72,10 @@ def test_no_other_qwen35_sizes_silently_added():
|
||||
("Qwen/Qwen3.5-397B-A17B", True),
|
||||
],
|
||||
)
|
||||
def test_qwen35_enable_thinking_polarity_autodetected(qwen35_model, expected_default):
|
||||
"""The renderer's ``_enable_thinking`` resolves to the chat template's
|
||||
own default when no explicit flag is passed — so big / small sizes
|
||||
each match their own template at the gen-prompt boundary."""
|
||||
def test_qwen35_enable_thinking_polarity_default(qwen35_model, expected_default):
|
||||
"""With no explicit flag, the renderer resolves ``enable_thinking`` from
|
||||
the hard-coded per-model default — so big / small sizes each match their
|
||||
own template at the gen-prompt boundary."""
|
||||
tok = load_tokenizer(qwen35_model)
|
||||
renderer = create_renderer(tok, Qwen35RendererConfig())
|
||||
assert isinstance(renderer, Qwen35Renderer)
|
||||
@@ -86,6 +85,30 @@ def test_qwen35_enable_thinking_polarity_autodetected(qwen35_model, expected_def
|
||||
)
|
||||
|
||||
|
||||
def test_construction_does_not_call_apply_chat_template():
|
||||
"""The ``enable_thinking`` default is hard-coded per model, so building a
|
||||
``Qwen35Renderer`` must not probe ``apply_chat_template`` — a
|
||||
bring-your-own tokenizer with no chat-template support still works."""
|
||||
|
||||
class _Stub:
|
||||
name_or_path = "Qwen/Qwen3.5-0.8B"
|
||||
unk_token_id = -1
|
||||
|
||||
def convert_tokens_to_ids(self, token):
|
||||
# Any stable non-unk id per token; the renderer only needs the
|
||||
# special tokens to resolve to distinct, in-vocab ids.
|
||||
return abs(hash(token)) % 1_000_000 + 1
|
||||
|
||||
def apply_chat_template(self, *args, **kwargs):
|
||||
raise AssertionError(
|
||||
"apply_chat_template must not be called at construction"
|
||||
)
|
||||
|
||||
renderer = Qwen35Renderer(_Stub())
|
||||
# 0.8B is a small size → thinking defaults off, from the hard-coded table.
|
||||
assert renderer.config.enable_thinking is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Byte parity for each in-map Qwen3.5 size.
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -146,7 +169,7 @@ def test_qwen35_size_parity_with_apply_chat_template(
|
||||
"""Each in-map Qwen3.5 size renders byte-identical to its own
|
||||
``apply_chat_template`` output. Locks in the property that lets us
|
||||
share ``Qwen35Renderer`` across all seven sizes — the polarity
|
||||
flip on 0.8B / 2B is absorbed by the constructor's auto-detect."""
|
||||
flip on 0.8B / 2B is absorbed by the per-model default."""
|
||||
tok = load_tokenizer(qwen35_model)
|
||||
renderer = create_renderer(tok, Qwen35RendererConfig())
|
||||
assert isinstance(renderer, Qwen35Renderer)
|
||||
|
||||
@@ -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