feat(hy3): add Tencent Hunyuan Hy3 renderer (#98)
This commit is contained in:
@@ -40,7 +40,7 @@ next_prompt_ids = r.bridge_to_next_turn(
|
||||
)
|
||||
```
|
||||
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `deepseek-r1`, `kimi-k2`, `kimi-k2.5` / `kimi-k2.6`, `nemotron-3`, `nemotron-3-ultra`, `llama-3`, and `gpt-oss`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `deepseek-r1`, `kimi-k2`, `kimi-k2.5` / `kimi-k2.6`, `nemotron-3`, `nemotron-3-ultra`, `llama-3`, `gpt-oss`, and `hy3`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
|
||||
|
||||
## API
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ chat-template kwargs. Those fields are covered by parity tests against
|
||||
| GLM-5 / 5.1 | `GLM5RendererConfig` / `GLM51RendererConfig` | `enable_thinking`, `clear_thinking` | - |
|
||||
| GLM-4.5 | `GLM45RendererConfig` | `enable_thinking` | - |
|
||||
| gpt-oss | `GptOssRendererConfig` | `reasoning_effort`, `conversation_start_date` | `use_system_prompt`, `knowledge_cutoff`, `model_identity`, `auto_drop_analysis` |
|
||||
| Hy3 | `Hy3RendererConfig` | `reasoning_effort`, `preserved_thinking`, `is_training`, `raw_last_assistant`, `fallback_strategy` | - |
|
||||
| Kimi K2 | `KimiK2RendererConfig` | - | `enable_thinking` |
|
||||
| Kimi K2.5 / 2.6 | `KimiK25RendererConfig` | `thinking` | `image_cache_max` |
|
||||
| Laguna XS.2 | `LagunaXS2RendererConfig` | `enable_thinking`, `render_assistant_messages_raw` | - |
|
||||
@@ -129,6 +130,7 @@ the knobs its template actually exposes:
|
||||
| GLM-5 / 5.1 | `clear_thinking=False -> all`; else `enable_thinking=False -> all`; else `tool_cycle` |
|
||||
| GLM-4.5 | `enable_thinking=False -> all`, else `tool_cycle` |
|
||||
| gpt-oss | `auto_drop_analysis=False -> all`, else `tool_cycle` |
|
||||
| Hy3 | `preserved_thinking=True -> all`, else `tool_cycle` |
|
||||
| Kimi K2.5 / 2.6 | `thinking=False -> all`, else `tool_cycle` |
|
||||
| Nemotron-3 | `truncate_history_thinking=False -> all`; else `enable_thinking=False -> all`; else `tool_cycle` |
|
||||
| DeepSeek R1 | `template` |
|
||||
|
||||
@@ -51,6 +51,7 @@ from renderers.configs import (
|
||||
GLM51RendererConfig,
|
||||
GLM5RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
Hy3RendererConfig,
|
||||
KimiK25RendererConfig,
|
||||
KimiK2RendererConfig,
|
||||
LagunaXS2RendererConfig,
|
||||
@@ -85,6 +86,7 @@ _LAZY_RENDERERS: dict[str, str] = {
|
||||
"GLM51Renderer": "renderers.glm5",
|
||||
"GLM5Renderer": "renderers.glm5",
|
||||
"GptOssRenderer": "renderers.gpt_oss",
|
||||
"Hy3Renderer": "renderers.hy3",
|
||||
"KimiK25Renderer": "renderers.kimi_k25",
|
||||
"KimiK2Renderer": "renderers.kimi_k2",
|
||||
"LagunaXS21Renderer": "renderers.laguna_xs2",
|
||||
@@ -134,6 +136,8 @@ __all__ = [
|
||||
"GLM5RendererConfig",
|
||||
"GptOssRenderer",
|
||||
"GptOssRendererConfig",
|
||||
"Hy3Renderer",
|
||||
"Hy3RendererConfig",
|
||||
"ImagePart",
|
||||
"KimiK25Renderer",
|
||||
"KimiK25RendererConfig",
|
||||
|
||||
@@ -1067,6 +1067,12 @@ MODEL_RENDERER_MAP: dict[str, str] = {
|
||||
# GPT-OSS.
|
||||
"openai/gpt-oss-20b": "gpt-oss",
|
||||
"openai/gpt-oss-120b": "gpt-oss",
|
||||
# Tencent Hunyuan Hy3 (295B-A21B MoE). The FP8 checkpoint shares the same
|
||||
# tokenizer and chat template. Hy3-preview is deliberately unmapped: it
|
||||
# ships an older, incompatible template (un-suffixed special tokens,
|
||||
# ``interleaved_thinking`` instead of ``preserved_thinking``).
|
||||
"tencent/Hy3": "hy3",
|
||||
"tencent/Hy3-FP8": "hy3",
|
||||
}
|
||||
|
||||
|
||||
@@ -1302,6 +1308,7 @@ def _populate_registry():
|
||||
from renderers.glm5 import GLM5Renderer, GLM51Renderer
|
||||
from renderers.glm45 import GLM45Renderer
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.hy3 import Hy3Renderer
|
||||
from renderers.kimi_k2 import KimiK2Renderer
|
||||
from renderers.kimi_k25 import KimiK25Renderer
|
||||
from renderers.laguna_xs2 import LagunaXS2Renderer, LagunaXS21Renderer
|
||||
@@ -1326,6 +1333,7 @@ def _populate_registry():
|
||||
"minimax-m2": MiniMaxM2Renderer,
|
||||
"deepseek-v3": DeepSeekV3Renderer,
|
||||
"deepseek-r1": DeepSeekR1Renderer,
|
||||
"hy3": Hy3Renderer,
|
||||
"kimi-k2": KimiK2Renderer,
|
||||
"kimi-k2.5": KimiK25Renderer,
|
||||
"laguna-xs.2": LagunaXS2Renderer,
|
||||
|
||||
@@ -310,6 +310,70 @@ class GLM45RendererConfig(BaseRendererConfig):
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
|
||||
class Hy3RendererConfig(BaseRendererConfig):
|
||||
"""Tencent Hunyuan Hy3 renderer config.
|
||||
|
||||
Hy3 reasons via a ``reasoning_effort`` gate rather than a boolean
|
||||
``enable_thinking``. ``"no_think"`` (the template default) prefills an
|
||||
empty ``<think></think>`` at the generation prompt so the model answers
|
||||
directly; ``"low"`` / ``"high"`` prefill only the ``<think>`` opener so
|
||||
the model streams reasoning up to a ``</think>`` it emits itself.
|
||||
|
||||
``preserved_thinking`` mirrors the template kwarg of the same name:
|
||||
``True`` keeps ``<think>{reasoning}</think>`` on every historical
|
||||
assistant turn; ``False`` collapses past-cycle reasoning to
|
||||
``<think></think>``, keeping it only on the in-flight turn (after the
|
||||
last user query). ``None`` (default) follows the template's own
|
||||
default — ``True`` when ``tools`` are supplied at render time, ``False``
|
||||
otherwise. Bridge policy tracks the same resolution: ``"all"`` whenever
|
||||
``preserved_thinking`` resolves to ``True`` for the tools at hand,
|
||||
``"tool_cycle"`` otherwise.
|
||||
"""
|
||||
|
||||
name: Literal["hy3"] = "hy3"
|
||||
|
||||
reasoning_effort: Literal["no_think", "low", "high"] = "no_think"
|
||||
"""Reasoning gate. Mirrors the chat template's ``reasoning_effort`` kwarg.
|
||||
``"no_think"`` prefills ``<think></think>`` at the generation prompt;
|
||||
``"low"`` / ``"high"`` prefill just ``<think>``."""
|
||||
|
||||
preserved_thinking: bool | None = None
|
||||
"""Keep historical assistant reasoning. Mirrors the template's
|
||||
``preserved_thinking`` kwarg. ``None`` defers to the template default
|
||||
(``True`` with tools, ``False`` without). Bridge policy is ``"all"``
|
||||
whenever this resolves to ``True`` for the tools at hand."""
|
||||
|
||||
is_training: bool = False
|
||||
"""Mirrors the template's ``is_training`` kwarg. ``True`` renders SFT
|
||||
targets: reasoning is kept on every assistant turn (regardless of
|
||||
``preserved_thinking`` / position) and the final assistant is terminated
|
||||
with ``<|hy_eos|>``. Leave ``False`` for inference-faithful renders;
|
||||
the training loss mask is normally derived via ``build_training_sample``
|
||||
rather than this flag."""
|
||||
|
||||
raw_last_assistant: bool = False
|
||||
"""Mirrors the template's ``raw_last_assistant`` kwarg. When ``True`` a
|
||||
trailing non-tool assistant message is emitted as raw visible content —
|
||||
no ``<think>`` wrap, no ``<|hy_eos|>`` — for prefill / continuation."""
|
||||
|
||||
fallback_strategy: Literal["reasoning_toolcall_retry"] | None = None
|
||||
"""Mirrors the template's ``fallback_strategy`` kwarg. The sole active
|
||||
value, ``"reasoning_toolcall_retry"``, forces ``reasoning_effort="high"``
|
||||
and suppresses the generation prompt (``add_generation_prompt=False``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
if self.preserved_thinking is not None and self.thinking_retention is not None:
|
||||
implied = "all" if self.preserved_thinking else "tool_cycle"
|
||||
if self.thinking_retention != implied:
|
||||
raise ValueError(
|
||||
f"preserved_thinking={self.preserved_thinking!r} implies "
|
||||
f"thinking_retention={implied!r}, which conflicts with "
|
||||
f"explicit thinking_retention={self.thinking_retention!r}."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class GptOssRendererConfig(BaseRendererConfig):
|
||||
"""OpenAI gpt-oss (harmony) renderer config.
|
||||
|
||||
@@ -592,6 +656,7 @@ RendererConfig = Annotated[
|
||||
GLM51RendererConfig,
|
||||
GLM45RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
Hy3RendererConfig,
|
||||
KimiK2RendererConfig,
|
||||
KimiK25RendererConfig,
|
||||
LagunaXS2RendererConfig,
|
||||
@@ -630,6 +695,7 @@ _CONFIG_BY_NAME: dict[str, type[BaseRendererConfig]] = {
|
||||
"glm-5.1": GLM51RendererConfig,
|
||||
"glm-4.5": GLM45RendererConfig,
|
||||
"gpt-oss": GptOssRendererConfig,
|
||||
"hy3": Hy3RendererConfig,
|
||||
"kimi-k2": KimiK2RendererConfig,
|
||||
"kimi-k2.5": KimiK25RendererConfig,
|
||||
"laguna-xs.2": LagunaXS2RendererConfig,
|
||||
@@ -677,6 +743,7 @@ __all__ = [
|
||||
"GLM51RendererConfig",
|
||||
"GLM5RendererConfig",
|
||||
"GptOssRendererConfig",
|
||||
"Hy3RendererConfig",
|
||||
"KimiK25RendererConfig",
|
||||
"KimiK2RendererConfig",
|
||||
"LagunaXS2RendererConfig",
|
||||
|
||||
@@ -0,0 +1,706 @@
|
||||
"""Hy3 renderer — hard-coded Python mirroring the Tencent Hunyuan Hy3 Jinja
|
||||
chat template (``tencent/Hy3`` / ``Hy3-FP8``; ``Hy3-preview`` uses an older,
|
||||
incompatible template and is not supported).
|
||||
|
||||
Shape of the Hy3 template, distinct from the GLM / Qwen families:
|
||||
|
||||
- No per-message ``<|system|>`` marker: every system message's content is
|
||||
concatenated into a single blob emitted right after ``<|hy_begin_of_sentence|>``.
|
||||
- Reasoning is gated by ``reasoning_effort`` (``no_think`` / ``low`` / ``high``),
|
||||
not a boolean. Without tools a ``<|reasoning_mode|>reasoning_effort:{effort}``
|
||||
marker is appended to the system blob; with tools it rides at the end of the
|
||||
tool-instruction block instead.
|
||||
- The generation prompt prefills ``<think></think>`` in ``no_think`` mode (the
|
||||
model answers directly) and only ``<think>`` in ``low`` / ``high`` mode (the
|
||||
model streams reasoning up to a ``</think>`` it emits itself).
|
||||
- Each assistant turn closes with an explicit ``<|hy_eos|>`` — the sole stop
|
||||
token — unlike GLM where the next role marker doubles as the close.
|
||||
- Tool calls: ``<tool_calls>`` wraps one or more ``<tool_call>name<tool_sep>``
|
||||
blocks, each carrying ``<arg_key>``/``<arg_value>`` pairs (single special
|
||||
tokens, as in GLM), and the block closes ``</tool_calls><|hy_eos|>``.
|
||||
- Tool responses: ``<tool_responses>`` wraps one or more
|
||||
``<tool_response>…</tool_response>`` blocks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from renderers.base import (
|
||||
Message,
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
)
|
||||
from renderers.configs import Hy3RendererConfig, ResolvedThinkingRetention
|
||||
from renderers.parsing import parse_hy3
|
||||
|
||||
# Special-token strings, constructed exactly as the Jinja template does
|
||||
# (``'<|hy_eos{}|>'.format(':opensource')`` etc.) so ``convert_tokens_to_ids``
|
||||
# resolves each to its single vocabulary id.
|
||||
_HYTK = ":opensource"
|
||||
_BOS = f"<|hy_begin_of_sentence{_HYTK}|>"
|
||||
_EOS = f"<|hy_eos{_HYTK}|>"
|
||||
_USER = f"<|hy_User{_HYTK}|>"
|
||||
_ASSISTANT = f"<|hy_Assistant{_HYTK}|>"
|
||||
_REASONING_MODE = f"<|reasoning_mode{_HYTK}|>"
|
||||
_THINK = f"<think{_HYTK}>"
|
||||
_THINK_END = f"</think{_HYTK}>"
|
||||
_TOOL_CALLS = f"<tool_calls{_HYTK}>"
|
||||
_TOOL_CALLS_END = f"</tool_calls{_HYTK}>"
|
||||
_TOOL_CALL = f"<tool_call{_HYTK}>"
|
||||
_TOOL_CALL_END = f"</tool_call{_HYTK}>"
|
||||
_TOOL_SEP = f"<tool_sep{_HYTK}>"
|
||||
_ARG_KEY = f"<arg_key{_HYTK}>"
|
||||
_ARG_KEY_END = f"</arg_key{_HYTK}>"
|
||||
_ARG_VALUE = f"<arg_value{_HYTK}>"
|
||||
_ARG_VALUE_END = f"</arg_value{_HYTK}>"
|
||||
_TOOL_RESPONSES = f"<tool_responses{_HYTK}>"
|
||||
_TOOL_RESPONSES_END = f"</tool_responses{_HYTK}>"
|
||||
_TOOL_RESPONSE = f"<tool_response{_HYTK}>"
|
||||
_TOOL_RESPONSE_END = f"</tool_response{_HYTK}>"
|
||||
|
||||
|
||||
class Hy3Renderer:
|
||||
"""Deterministic message → token renderer for Tencent Hy3 models."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Hy3RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or Hy3RendererConfig()
|
||||
self._is_training = self.config.is_training
|
||||
self._raw_last_assistant = self.config.raw_last_assistant
|
||||
# ``fallback_strategy="reasoning_toolcall_retry"`` forces high effort and
|
||||
# suppresses the generation prompt (template lines 50-53), resolved here
|
||||
# so the reasoning-mode marker and gen-prompt polarity see the override.
|
||||
self._force_no_gen_prompt = (
|
||||
self.config.fallback_strategy == "reasoning_toolcall_retry"
|
||||
)
|
||||
self._reasoning_effort = (
|
||||
"high" if self._force_no_gen_prompt else self.config.reasoning_effort
|
||||
)
|
||||
# ``<think>`` (and, in no_think mode, the matching ``</think>``) are
|
||||
# prefilled by the generation prompt, so the model never samples them.
|
||||
# Only in low/high mode does the model itself emit the ``</think>``
|
||||
# that closes its reasoning.
|
||||
self._think_is_sampled = self._reasoning_effort in ("low", "high")
|
||||
# Derived bridge policy: when the template keeps reasoning on every
|
||||
# historical turn it is safe to extend across a user query ("all");
|
||||
# otherwise past-cycle reasoning is stripped once a new user query
|
||||
# arrives, so the faithful policy declines there ("tool_cycle").
|
||||
# ``preserved_thinking=None`` follows the template's tools-dependent
|
||||
# default, so the bridge resolves the policy per call; this attribute
|
||||
# holds the no-tools resolution.
|
||||
self.effective_thinking_retention = self._thinking_retention_for(None)
|
||||
|
||||
self._bos = self._token_id(_BOS)
|
||||
self._eos = self._token_id(_EOS)
|
||||
self._user = self._token_id(_USER)
|
||||
self._assistant = self._token_id(_ASSISTANT)
|
||||
self._reasoning_mode = self._token_id(_REASONING_MODE)
|
||||
self._think = self._token_id(_THINK)
|
||||
self._think_end = self._token_id(_THINK_END)
|
||||
self._tool_calls = self._token_id(_TOOL_CALLS)
|
||||
self._tool_calls_end = self._token_id(_TOOL_CALLS_END)
|
||||
self._tool_call = self._token_id(_TOOL_CALL)
|
||||
self._tool_call_end = self._token_id(_TOOL_CALL_END)
|
||||
self._tool_sep = self._token_id(_TOOL_SEP)
|
||||
self._arg_key = self._token_id(_ARG_KEY)
|
||||
self._arg_key_end = self._token_id(_ARG_KEY_END)
|
||||
self._arg_value = self._token_id(_ARG_VALUE)
|
||||
self._arg_value_end = self._token_id(_ARG_VALUE_END)
|
||||
self._tool_responses = self._token_id(_TOOL_RESPONSES)
|
||||
self._tool_responses_end = self._token_id(_TOOL_RESPONSES_END)
|
||||
self._tool_response = self._token_id(_TOOL_RESPONSE)
|
||||
self._tool_response_end = self._token_id(_TOOL_RESPONSE_END)
|
||||
|
||||
# ── helpers ──────────────────────────────────────────────────────
|
||||
|
||||
def _preserved_thinking_for(self, tools: list[ToolSpec] | None) -> bool:
|
||||
"""Mirror the template's ``preserved_thinking`` default: the kwarg
|
||||
when set, else True iff tools are present."""
|
||||
if self.config.preserved_thinking is None:
|
||||
return bool(tools)
|
||||
return self.config.preserved_thinking
|
||||
|
||||
def _thinking_retention_for(
|
||||
self, tools: list[ToolSpec] | None
|
||||
) -> ResolvedThinkingRetention:
|
||||
implied = "all" if self._preserved_thinking_for(tools) else "tool_cycle"
|
||||
return resolve_thinking_retention(self.config, implied)
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
tid = self._tokenizer.convert_tokens_to_ids(token)
|
||||
assert isinstance(tid, int) and tid != self._tokenizer.unk_token_id, (
|
||||
f"Special token {token!r} not found in tokenizer vocabulary"
|
||||
)
|
||||
return tid
|
||||
|
||||
def _encode(self, text: str) -> list[int]:
|
||||
if not text:
|
||||
return []
|
||||
return self._tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
@staticmethod
|
||||
def _visible_text(content: Any) -> str:
|
||||
"""Mirror the template's ``visible_text`` macro: string verbatim, list
|
||||
of text parts concatenated, ``None`` → empty string."""
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
parts.append(item)
|
||||
elif isinstance(item, dict) and item.get("type") == "text":
|
||||
parts.append(item.get("text", ""))
|
||||
return "".join(parts)
|
||||
return str(content)
|
||||
|
||||
@staticmethod
|
||||
def _last_user_index(messages: list[Message]) -> int:
|
||||
for i in range(len(messages) - 1, -1, -1):
|
||||
if messages[i].get("role") == "user":
|
||||
return i
|
||||
return -1
|
||||
|
||||
def _reasoning_content(self, msg: Message) -> str | None:
|
||||
rc = msg.get("reasoning_content")
|
||||
if isinstance(rc, str):
|
||||
return rc
|
||||
rc = msg.get("reasoning")
|
||||
if isinstance(rc, str):
|
||||
return rc
|
||||
return None
|
||||
|
||||
def _tools_instruction_block(self, tools: list[ToolSpec], has_system: bool) -> str:
|
||||
"""Build the ``# Tools`` instruction blob (all scaffold).
|
||||
|
||||
Embedded special-token strings (``<tool_calls>`` etc.) tokenize to
|
||||
their single ids just as ``apply_chat_template`` produces them.
|
||||
"""
|
||||
intro = (
|
||||
"# Tools\n\nYou may call one or more functions to assist with the "
|
||||
"user query."
|
||||
)
|
||||
s = ("\n\n" + intro) if has_system else intro
|
||||
s += (
|
||||
"\n\nYou are provided with function signatures within "
|
||||
"<tools></tools> XML tags:\n<tools>\n"
|
||||
)
|
||||
for idx, tool in enumerate(tools):
|
||||
if idx > 0:
|
||||
s += "\n"
|
||||
s += json.dumps(tool, ensure_ascii=False)
|
||||
s += "\n</tools>\n\n"
|
||||
s += "For function call returns, you should first print " + _TOOL_CALLS + "\n"
|
||||
s += "For each function call, you should return object like:\n"
|
||||
s += _TOOL_CALL + "{function-name}" + _TOOL_SEP + "\n"
|
||||
s += _ARG_KEY + "{arg-key-1}" + _ARG_KEY_END + "\n"
|
||||
s += _ARG_VALUE + "{arg-value-1}" + _ARG_VALUE_END + "\n"
|
||||
s += _ARG_KEY + "{arg-key-2}" + _ARG_KEY_END + "\n"
|
||||
s += _ARG_VALUE + "{arg-value-2}" + _ARG_VALUE_END + "\n"
|
||||
s += "...\n"
|
||||
s += _TOOL_CALL_END + "\n"
|
||||
# ``reasoning_effort`` is always a non-empty string in our config, so
|
||||
# the marker is always appended (matching the template's truthy path).
|
||||
s += (
|
||||
"At the end of function call returns, you should print "
|
||||
+ _TOOL_CALLS_END
|
||||
+ _REASONING_MODE
|
||||
+ "reasoning_effort:"
|
||||
+ self._reasoning_effort
|
||||
)
|
||||
return s
|
||||
|
||||
def _attribute_segments(
|
||||
self, segments: list[tuple[str, bool, int]]
|
||||
) -> list[tuple[int, bool, int]]:
|
||||
"""Tokenize concatenated ``(text, is_content, msg_idx)`` segments as one
|
||||
BPE pass, attributing each token to its source segment via offset
|
||||
mapping. Generalises :func:`attribute_text_segments` with a message
|
||||
index — needed where a system blob abuts the tools block with no
|
||||
special-token boundary between them.
|
||||
"""
|
||||
segments = [s for s in segments if s[0]]
|
||||
if not segments:
|
||||
return []
|
||||
full_text = "".join(text for text, _, _ in segments)
|
||||
encoding = self._tokenizer(
|
||||
full_text,
|
||||
add_special_tokens=False,
|
||||
return_offsets_mapping=True,
|
||||
)
|
||||
token_ids = list(encoding["input_ids"])
|
||||
offsets = list(encoding["offset_mapping"])
|
||||
|
||||
spans: list[tuple[int, int, bool, int]] = []
|
||||
pos = 0
|
||||
for text, is_content, msg_idx in segments:
|
||||
spans.append((pos, pos + len(text), is_content, msg_idx))
|
||||
pos += len(text)
|
||||
total_len = pos
|
||||
|
||||
out: list[tuple[int, bool, int]] = []
|
||||
last = (spans[-1][2], spans[-1][3])
|
||||
for tok_id, (start, _end) in zip(token_ids, offsets):
|
||||
attr = last
|
||||
if start < total_len:
|
||||
for seg_start, seg_end, seg_is_content, seg_idx in spans:
|
||||
if seg_start <= start < seg_end:
|
||||
attr = (seg_is_content, seg_idx)
|
||||
break
|
||||
out.append((tok_id, attr[0], attr[1]))
|
||||
return out
|
||||
|
||||
# ── render ───────────────────────────────────────────────────────
|
||||
|
||||
def render(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> RenderedTokens:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
# fallback_strategy="reasoning_toolcall_retry" suppresses the gen prompt.
|
||||
if self._force_no_gen_prompt:
|
||||
add_generation_prompt = False
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_attributed(segments: list[tuple[str, bool, int]]) -> None:
|
||||
for tok_id, is_content, msg_idx in self._attribute_segments(segments):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(False)
|
||||
content_mask.append(is_content)
|
||||
|
||||
preserved = self._preserved_thinking_for(tools)
|
||||
|
||||
# ── Header: bos + aggregated system + reasoning marker / tools ──
|
||||
emit_special(self._bos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
system_segments = [
|
||||
(self._visible_text(m.get("content")), True, i)
|
||||
for i, m in enumerate(messages)
|
||||
if m.get("role") == "system"
|
||||
]
|
||||
has_system = any(text for text, _, _ in system_segments)
|
||||
|
||||
if tools:
|
||||
tools_text = self._tools_instruction_block(tools, has_system)
|
||||
emit_attributed(system_segments + [(tools_text, False, -1)])
|
||||
else:
|
||||
emit_attributed(system_segments)
|
||||
emit_special(self._reasoning_mode, -1, is_sampled=False, is_content=False)
|
||||
emit_text(
|
||||
"reasoning_effort:" + self._reasoning_effort,
|
||||
-1,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
|
||||
last_ui = self._last_user_index(messages)
|
||||
n = len(messages)
|
||||
prev_is_tool = False
|
||||
is_tool_first = True
|
||||
|
||||
# ── Message loop (system handled in the header) ─────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
role = msg.get("role")
|
||||
if role == "system":
|
||||
continue
|
||||
|
||||
if role == "user":
|
||||
if prev_is_tool:
|
||||
emit_special(
|
||||
self._tool_responses_end, i, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_special(self._user, i, is_sampled=False, is_content=False)
|
||||
emit_text(
|
||||
self._visible_text(msg.get("content")),
|
||||
i,
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
prev_is_tool = False
|
||||
|
||||
elif role == "assistant":
|
||||
if prev_is_tool:
|
||||
emit_special(
|
||||
self._tool_responses_end, i, is_sampled=False, is_content=False
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
is_last=(i == n - 1),
|
||||
retain_thinking=self._is_training or preserved or i > last_ui,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
prev_is_tool = False
|
||||
# The template re-opens a <tool_responses> group only after an
|
||||
# assistant that made tool calls; a plain assistant leaves the
|
||||
# flag as it was.
|
||||
if msg.get("tool_calls"):
|
||||
is_tool_first = True
|
||||
|
||||
elif role == "tool":
|
||||
if is_tool_first:
|
||||
emit_special(
|
||||
self._tool_responses, i, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
is_tool_first = False
|
||||
emit_special(self._tool_response, i, is_sampled=False, is_content=False)
|
||||
emit_text_segments(
|
||||
[
|
||||
("\n", False),
|
||||
(self._visible_text(msg.get("content")), True),
|
||||
("\n", False),
|
||||
],
|
||||
i,
|
||||
is_sampled=False,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_response_end, i, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
prev_is_tool = True
|
||||
|
||||
if prev_is_tool:
|
||||
emit_special(
|
||||
self._tool_responses_end, -1, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
# ── Generation prompt ───────────────────────────────────────────
|
||||
last_is_assistant = messages[-1].get("role") == "assistant"
|
||||
if add_generation_prompt and not last_is_assistant:
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
if self._reasoning_effort == "no_think":
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
msg: Message,
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_last: bool,
|
||||
retain_thinking: bool,
|
||||
emit_special,
|
||||
emit_text,
|
||||
) -> None:
|
||||
# Invariant on assistant tokens: ``is_content == sampled_mask``.
|
||||
# The ``<|hy_Assistant|>`` opener and the ``<think>`` opener are both
|
||||
# generation-prompt scaffold (never sampled). ``</think>`` and any
|
||||
# reasoning body are sampled only in low/high mode; content, tool
|
||||
# calls and the closing ``<|hy_eos|>`` are always sampled.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
visible = self._visible_text(msg.get("content"))
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
|
||||
# Raw passthrough for a trailing non-tool assistant (prefill /
|
||||
# continuation): no ``<think>`` wrap, no ``<|hy_eos|>`` — just the
|
||||
# bare visible content (template lines 186-187).
|
||||
if self._raw_last_assistant and is_last and not tool_calls:
|
||||
emit_text(visible, msg_idx, is_sampled=True, is_content=True)
|
||||
return
|
||||
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
rc = self._reasoning_content(msg)
|
||||
if retain_thinking and rc is not None:
|
||||
emit_text(
|
||||
rc,
|
||||
msg_idx,
|
||||
is_sampled=self._think_is_sampled,
|
||||
is_content=self._think_is_sampled,
|
||||
)
|
||||
emit_special(
|
||||
self._think_end,
|
||||
msg_idx,
|
||||
is_sampled=self._think_is_sampled,
|
||||
is_content=self._think_is_sampled,
|
||||
)
|
||||
|
||||
if tool_calls:
|
||||
emit_text(visible, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_calls, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
for tc in tool_calls:
|
||||
self._emit_tool_call(tc, msg_idx, emit_special, emit_text)
|
||||
emit_special(
|
||||
self._tool_calls_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(self._eos, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_text(visible, msg_idx, is_sampled=True, is_content=True)
|
||||
# Final assistant keeps its close only under is_training; otherwise
|
||||
# a terminal assistant is left open (template lines 188-192).
|
||||
if not is_last or self._is_training:
|
||||
emit_special(self._eos, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
def _emit_tool_call(self, tc: Any, msg_idx: int, emit_special, emit_text) -> None:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(name, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_sep, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# OpenAI canonical form serialises ``arguments`` as a JSON string;
|
||||
# parse it so per-argument rendering still fires.
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
if isinstance(arguments, dict):
|
||||
for key, value in arguments.items():
|
||||
emit_special(self._arg_key, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(key, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._arg_key_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._arg_value, msg_idx, is_sampled=True, is_content=True)
|
||||
if isinstance(value, str):
|
||||
emit_text(value, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_text(
|
||||
json.dumps(value, ensure_ascii=False),
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._arg_value_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> list[int]:
|
||||
return self.render(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
# ── parse ────────────────────────────────────────────────────────
|
||||
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_hy3(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
stop_ids={self._eos},
|
||||
assistant_id=self._assistant,
|
||||
think_id=self._think,
|
||||
think_end_id=self._think_end,
|
||||
tool_calls_id=self._tool_calls,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tool_sep_id=self._tool_sep,
|
||||
arg_key_id=self._arg_key,
|
||||
arg_key_end_id=self._arg_key_end,
|
||||
arg_value_id=self._arg_value,
|
||||
arg_value_end_id=self._arg_value_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
return [self._eos]
|
||||
|
||||
# ── bridge ───────────────────────────────────────────────────────
|
||||
|
||||
def bridge_to_next_turn(
|
||||
self,
|
||||
previous_prompt_ids: list[int],
|
||||
previous_completion_ids: list[int],
|
||||
new_messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> RenderedTokens | None:
|
||||
if (
|
||||
not previous_prompt_ids
|
||||
or not new_messages
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self._thinking_retention_for(tools),
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# A bridge extends a *sampled* assistant turn; with no completion there
|
||||
# is no turn to extend (and no way to tell a pending assistant turn from
|
||||
# a closed tool section), so decline and let the caller re-render.
|
||||
if not previous_completion_ids:
|
||||
return None
|
||||
|
||||
# Anchor on the canonical turn close (``<|hy_eos|>``). The model only
|
||||
# ever ends a turn on eos, so a completion that stops elsewhere was
|
||||
# truncated mid-turn — synthesise the close as non-loss prompt context.
|
||||
# Never synthesise after a boundary that is already a valid
|
||||
# continuation point: eos (turn closed) or ``</tool_responses>`` (tool
|
||||
# section closed, reachable when the prior prompt suppressed the
|
||||
# generation prompt) — an unconditional eos there would wedge a
|
||||
# spurious stop token before the extension.
|
||||
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
|
||||
if previous_ids[-1] not in (self._eos, self._tool_responses_end):
|
||||
previous_ids.append(self._eos)
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int = -1) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_content.append(False)
|
||||
|
||||
def emit_text(
|
||||
text: str, msg_idx: int = -1, *, is_content: bool = False
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(segments: list[tuple[str, bool]], msg_idx: int) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_content.append(is_content)
|
||||
|
||||
# The stream above ends on eos or </tool_responses> — never inside an
|
||||
# open tool group. ``is_tool_first`` mirrors the template's state
|
||||
# machine: it resets only on an assistant turn that made tool calls,
|
||||
# and a tool extension always follows exactly such a turn (that is
|
||||
# what produced the tool results), so it enters the extension True and
|
||||
# is never reset again — assistants are rejected above. The first tool
|
||||
# group opens <tool_responses>; a later group (after a user turn) does
|
||||
# not, matching a full render byte-for-byte.
|
||||
prev_is_tool = False
|
||||
is_tool_first = True
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
if role == "user":
|
||||
if prev_is_tool:
|
||||
emit_special(self._tool_responses_end, i)
|
||||
emit_special(self._user, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
prev_is_tool = False
|
||||
elif role == "system":
|
||||
# Hy3 folds system content into the header, which the bridge
|
||||
# cannot rewrite without re-rendering the prior turn.
|
||||
return None
|
||||
elif role == "tool":
|
||||
if is_tool_first:
|
||||
emit_special(self._tool_responses, i)
|
||||
emit_text("\n", i)
|
||||
is_tool_first = False
|
||||
emit_special(self._tool_response, i)
|
||||
emit_text_segments([("\n", False), (content, True), ("\n", False)], i)
|
||||
emit_special(self._tool_response_end, i)
|
||||
emit_text("\n", i)
|
||||
prev_is_tool = True
|
||||
else:
|
||||
return None
|
||||
|
||||
if prev_is_tool:
|
||||
emit_special(self._tool_responses_end, -1)
|
||||
|
||||
# Generation prompt — suppressed under the fallback retry strategy, so
|
||||
# the extension matches a full render (which forces it off too).
|
||||
if not self._force_no_gen_prompt:
|
||||
emit_special(self._assistant, -1)
|
||||
emit_special(self._think, -1)
|
||||
if self._reasoning_effort == "no_think":
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
@@ -556,6 +556,205 @@ def _parse_glm_tool_calls(
|
||||
return tool_calls
|
||||
|
||||
|
||||
# ── Hy3: <think>…</think> content <tool_calls> <tool_call>name<tool_sep> …
|
||||
# <arg_key>k</arg_key> <arg_value>v</arg_value> … </tool_call> </tool_calls>
|
||||
# Same arg_key/arg_value token scheme as GLM, but each call names the function
|
||||
# between <tool_call> and <tool_sep>, and the calls are wrapped in an outer
|
||||
# <tool_calls></tool_calls> pair. All markers are single special tokens.
|
||||
|
||||
|
||||
def parse_hy3(
|
||||
tokenizer,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
stop_ids: set[int],
|
||||
assistant_id: int,
|
||||
think_id: int,
|
||||
think_end_id: int,
|
||||
tool_calls_id: int,
|
||||
tool_call_id: int,
|
||||
tool_call_end_id: int,
|
||||
tool_sep_id: int,
|
||||
arg_key_id: int,
|
||||
arg_key_end_id: int,
|
||||
arg_value_id: int,
|
||||
arg_value_end_id: int,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
"""Parse Hy3 completion tokens.
|
||||
|
||||
Handles both the inference stream (``reasoning</think>content…`` in
|
||||
``low``/``high`` mode, or bare ``content…`` in ``no_think`` mode, since
|
||||
the ``<think>`` opener lives in the generation prompt) and a round-trip
|
||||
slice that still carries a leading ``<|hy_Assistant|>`` opener and a
|
||||
full ``<think>…</think>`` block.
|
||||
"""
|
||||
ids = _strip_stop_tokens(token_ids, stop_ids)
|
||||
|
||||
# ``token_span`` values are reported relative to this stop-stripped stream
|
||||
# (the documented contract), so track every prefix we slice off below.
|
||||
offset = 0
|
||||
|
||||
# A round-trip slice includes the assistant role marker; the live
|
||||
# inference stream does not. Drop a single leading opener so both paths
|
||||
# land on the same downstream logic.
|
||||
if ids and ids[0] == assistant_id:
|
||||
ids = ids[1:]
|
||||
offset += 1
|
||||
|
||||
reasoning = None
|
||||
think_end = _find(ids, think_end_id)
|
||||
if think_end != -1:
|
||||
reasoning_ids = [t for t in ids[:think_end] if t != think_id]
|
||||
reasoning = _decode(tokenizer, reasoning_ids).strip()
|
||||
ids = ids[think_end + 1 :]
|
||||
offset += think_end + 1
|
||||
elif think_id in set(ids):
|
||||
# Reasoning opened but never closed (truncation): everything after
|
||||
# the opener is reasoning; there is no committed content yet.
|
||||
think_start = _find(ids, think_id)
|
||||
reasoning = _decode(tokenizer, ids[think_start + 1 :]).strip()
|
||||
return ParsedResponse(
|
||||
content="", reasoning_content=reasoning or None, tool_calls=[]
|
||||
)
|
||||
|
||||
# Content ends at the first tool marker — the outer <tool_calls> wrapper
|
||||
# or, defensively, a bare <tool_call> the model emitted without it.
|
||||
marker_positions = [
|
||||
p for p in (_find(ids, tool_calls_id), _find(ids, tool_call_id)) if p != -1
|
||||
]
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
if marker_positions:
|
||||
tool_start = min(marker_positions)
|
||||
content_text = _decode(tokenizer, ids[:tool_start]).strip()
|
||||
tool_calls = _parse_hy3_tool_calls(
|
||||
tokenizer,
|
||||
ids[tool_start:],
|
||||
tool_call_id,
|
||||
tool_call_end_id,
|
||||
tool_sep_id,
|
||||
arg_key_id,
|
||||
arg_key_end_id,
|
||||
arg_value_id,
|
||||
arg_value_end_id,
|
||||
section_offset=offset + tool_start,
|
||||
param_index=_build_param_type_index(tools),
|
||||
)
|
||||
else:
|
||||
content_text = _decode(tokenizer, ids).strip()
|
||||
|
||||
return ParsedResponse(
|
||||
content=content_text,
|
||||
reasoning_content=reasoning or None,
|
||||
tool_calls=tool_calls,
|
||||
)
|
||||
|
||||
|
||||
def _parse_hy3_tool_calls(
|
||||
tokenizer,
|
||||
ids,
|
||||
tc_id,
|
||||
tc_end_id,
|
||||
sep_id,
|
||||
ak_id,
|
||||
ake_id,
|
||||
av_id,
|
||||
ave_id,
|
||||
*,
|
||||
section_offset: int,
|
||||
param_index: dict[str, dict[str, dict[str, Any]]],
|
||||
) -> list[ParsedToolCall]:
|
||||
"""Parse Hy3-style tool calls: ``<tool_call>name<tool_sep>`` then
|
||||
arg_key/arg_value pairs, all by token ID. The outer ``<tool_calls>``
|
||||
wrapper and inter-block newlines are skipped by scanning for the
|
||||
per-call ``<tool_call>`` opener. ``section_offset`` shifts recorded
|
||||
``token_span`` values back into the stop-stripped completion stream
|
||||
(``ids`` here is a suffix of it)."""
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
i = 0
|
||||
while i < len(ids):
|
||||
if ids[i] == tc_id:
|
||||
end = _find(ids, tc_end_id, i + 1)
|
||||
if end == -1:
|
||||
raw = _decode(tokenizer, ids[i + 1 :])
|
||||
tool_calls.append(
|
||||
ParsedToolCall(
|
||||
raw=raw,
|
||||
token_span=(section_offset + i, section_offset + len(ids)),
|
||||
status=ToolCallParseStatus.UNCLOSED_BLOCK,
|
||||
)
|
||||
)
|
||||
break
|
||||
block = ids[i + 1 : end]
|
||||
block_text = _decode(tokenizer, block)
|
||||
span = (section_offset + i, section_offset + end + 1)
|
||||
|
||||
# Name sits between <tool_call> and <tool_sep>. Fall back to the
|
||||
# first <arg_key> boundary if the separator is missing.
|
||||
sep = _find(block, sep_id)
|
||||
if sep != -1:
|
||||
name = _decode(tokenizer, block[:sep]).strip()
|
||||
arg_ids = block[sep + 1 :]
|
||||
else:
|
||||
first_ak = _find(block, ak_id)
|
||||
if first_ak == -1:
|
||||
name = _decode(tokenizer, block).strip()
|
||||
arg_ids = []
|
||||
else:
|
||||
name = _decode(tokenizer, block[:first_ak]).strip()
|
||||
arg_ids = block[first_ak:]
|
||||
|
||||
params = param_index.get(name, {})
|
||||
arguments: dict = {}
|
||||
structure_broke = False
|
||||
any_json_fallback = False
|
||||
j = 0
|
||||
while j < len(arg_ids):
|
||||
if arg_ids[j] == ak_id:
|
||||
ake = _find(arg_ids, ake_id, j + 1)
|
||||
if ake == -1:
|
||||
structure_broke = True
|
||||
break
|
||||
key = _decode(tokenizer, arg_ids[j + 1 : ake]).strip()
|
||||
av = _find(arg_ids, av_id, ake + 1)
|
||||
if av == -1:
|
||||
structure_broke = True
|
||||
break
|
||||
ave = _find(arg_ids, ave_id, av + 1)
|
||||
if ave == -1:
|
||||
structure_broke = True
|
||||
break
|
||||
val_text = _decode(tokenizer, arg_ids[av + 1 : ave]).strip()
|
||||
value, used_fallback = _coerce_arg_value(val_text, params.get(key))
|
||||
arguments[key] = value
|
||||
any_json_fallback = any_json_fallback or used_fallback
|
||||
j = ave + 1
|
||||
else:
|
||||
j += 1
|
||||
|
||||
if not name:
|
||||
status = ToolCallParseStatus.MISSING_NAME
|
||||
elif structure_broke:
|
||||
status = ToolCallParseStatus.MALFORMED_STRUCTURE
|
||||
elif any_json_fallback:
|
||||
status = ToolCallParseStatus.INVALID_JSON
|
||||
else:
|
||||
status = ToolCallParseStatus.OK
|
||||
tool_calls.append(
|
||||
ParsedToolCall(
|
||||
raw=block_text,
|
||||
name=name or None,
|
||||
arguments=arguments,
|
||||
token_span=span,
|
||||
status=status,
|
||||
)
|
||||
)
|
||||
i = end + 1
|
||||
else:
|
||||
i += 1
|
||||
return tool_calls
|
||||
|
||||
|
||||
# ── Laguna-XS.2: <tool_call> name\n<arg_key>k</arg_key>\n<arg_value>v</arg_value> </tool_call>
|
||||
# Same outer skeleton as parse_glm, but <arg_key>/<arg_value> are plain text
|
||||
# (multi-token BPE), not single special tokens — so the inner block is decoded
|
||||
|
||||
@@ -55,6 +55,7 @@ RENDERER_MODELS = [
|
||||
# unsloth mirror so CI needs no Meta-gated HF token.
|
||||
("meta-llama/Llama-3.2-1B-Instruct", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
("tencent/Hy3", "auto"),
|
||||
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
|
||||
]
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ _BRIDGE_MODELS = [
|
||||
("moonshotai/Kimi-K2-Instruct", "auto"),
|
||||
("moonshotai/Kimi-K2.5", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("tencent/Hy3", "auto"),
|
||||
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
]
|
||||
@@ -282,6 +283,7 @@ _GUARDED_THINKING_MODELS = {
|
||||
"MiniMaxAI/MiniMax-M2.5",
|
||||
"moonshotai/Kimi-K2.5",
|
||||
"openai/gpt-oss-20b",
|
||||
"tencent/Hy3",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
"""Hy3-specific coverage beyond the shared barrage.
|
||||
|
||||
The parity / roundtrip / bridge matrices already assert byte-exact
|
||||
``apply_chat_template`` agreement and the emit/parse round trip. This file
|
||||
pins the behaviours unique to Hy3: the ``reasoning_effort`` generation-prompt
|
||||
polarity, parsing of a live inference stream (where the ``<think>`` opener
|
||||
lives in the prompt, not the completion), the reasoning-mode marker
|
||||
placement, and tool-call parse statuses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import Hy3RendererConfig, create_renderer
|
||||
from renderers.base import ToolCallParseStatus, load_tokenizer
|
||||
|
||||
_MODEL = "tencent/Hy3"
|
||||
|
||||
_ASSISTANT = "<|hy_Assistant:opensource|>"
|
||||
_THINK = "<think:opensource>"
|
||||
_THINK_END = "</think:opensource>"
|
||||
_EOS = "<|hy_eos:opensource|>"
|
||||
_REASONING_MODE = "<|reasoning_mode:opensource|>"
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _tok():
|
||||
return load_tokenizer(_MODEL)
|
||||
|
||||
|
||||
def _renderer(**flags):
|
||||
return create_renderer(_tok(), Hy3RendererConfig(**flags))
|
||||
|
||||
|
||||
def _decode(ids):
|
||||
return _tok().decode(ids, skip_special_tokens=False)
|
||||
|
||||
|
||||
# ── generation-prompt polarity ─────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"effort,expected_tail",
|
||||
[
|
||||
("no_think", _ASSISTANT + _THINK + _THINK_END),
|
||||
("low", _ASSISTANT + _THINK),
|
||||
("high", _ASSISTANT + _THINK),
|
||||
],
|
||||
)
|
||||
def test_generation_prompt_polarity(effort, expected_tail):
|
||||
r = _renderer(reasoning_effort=effort)
|
||||
ids = r.render_ids([{"role": "user", "content": "Hi"}], add_generation_prompt=True)
|
||||
assert _decode(ids).endswith(expected_tail), (
|
||||
f"effort={effort}: gen prompt tail was {_decode(ids)[-60:]!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_mode_marker_in_system_without_tools():
|
||||
"""Without tools, ``<|reasoning_mode|>reasoning_effort:{effort}`` is
|
||||
appended to the system blob."""
|
||||
r = _renderer(reasoning_effort="high")
|
||||
text = _decode(r.render_ids([{"role": "user", "content": "Hi"}]))
|
||||
assert _REASONING_MODE + "reasoning_effort:high" in text
|
||||
|
||||
|
||||
def test_reasoning_mode_marker_rides_tools_footer():
|
||||
"""With tools, the reasoning-mode marker moves to the end of the tool
|
||||
instructions (after ``</tool_calls>``), not the system blob."""
|
||||
r = _renderer(reasoning_effort="low")
|
||||
text = _decode(r.render_ids([{"role": "user", "content": "Hi"}], tools=TOOLS))
|
||||
assert "</tool_calls:opensource>" + _REASONING_MODE + "reasoning_effort:low" in text
|
||||
|
||||
|
||||
# ── stop token ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_stop_token_is_eos_only():
|
||||
r = _renderer()
|
||||
eos_id = _tok().convert_tokens_to_ids(_EOS)
|
||||
assert r.get_stop_token_ids() == [eos_id]
|
||||
|
||||
|
||||
# ── parsing a live inference stream ──────────────────────────────────────
|
||||
|
||||
|
||||
def test_parse_low_mode_inference_stream():
|
||||
"""In low/high mode the completion starts with reasoning text and closes
|
||||
it with ``</think>`` the model emits itself (the ``<think>`` opener was in
|
||||
the prompt)."""
|
||||
r = _renderer(reasoning_effort="low")
|
||||
comp = _tok().encode(
|
||||
"Let me work it out." + _THINK_END + "It is 4." + _EOS,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp)
|
||||
assert parsed.reasoning_content == "Let me work it out."
|
||||
assert parsed.content == "It is 4."
|
||||
assert not parsed.tool_calls
|
||||
|
||||
|
||||
def test_parse_no_think_inference_stream():
|
||||
"""In no_think mode the completion is the bare answer (both think tokens
|
||||
were prefilled into the prompt)."""
|
||||
r = _renderer()
|
||||
comp = _tok().encode("It is 4." + _EOS, add_special_tokens=False)
|
||||
parsed = r.parse_response(comp)
|
||||
assert parsed.content == "It is 4."
|
||||
assert parsed.reasoning_content is None
|
||||
|
||||
|
||||
def test_parse_tool_call_stream_with_schema():
|
||||
"""A tool-call completion parses name + typed args; the schema keeps a
|
||||
string arg verbatim (status OK, no JSON fallback)."""
|
||||
r = _renderer()
|
||||
comp = _tok().encode(
|
||||
"<tool_calls:opensource>\n<tool_call:opensource>get_weather<tool_sep:opensource>\n"
|
||||
"<arg_key:opensource>city</arg_key:opensource>\n"
|
||||
"<arg_value:opensource>Paris</arg_value:opensource>\n"
|
||||
"</tool_call:opensource>\n</tool_calls:opensource>" + _EOS,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp, tools=TOOLS)
|
||||
assert len(parsed.tool_calls) == 1
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.name == "get_weather"
|
||||
assert tc.arguments == {"city": "Paris"}
|
||||
assert tc.status is ToolCallParseStatus.OK
|
||||
assert parsed.content == ""
|
||||
|
||||
|
||||
def test_parse_unclosed_tool_call_is_flagged():
|
||||
r = _renderer()
|
||||
comp = _tok().encode(
|
||||
"<tool_calls:opensource>\n<tool_call:opensource>get_weather<tool_sep:opensource>\n"
|
||||
"<arg_key:opensource>city</arg_key:opensource>\n"
|
||||
"<arg_value:opensource>Paris</arg_value:opensource>\n",
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp)
|
||||
assert len(parsed.tool_calls) == 1
|
||||
assert parsed.tool_calls[0].status is ToolCallParseStatus.UNCLOSED_BLOCK
|
||||
|
||||
|
||||
def test_parse_content_before_tool_call_preserved():
|
||||
r = _renderer()
|
||||
comp = _tok().encode(
|
||||
"Let me check."
|
||||
"<tool_calls:opensource>\n<tool_call:opensource>get_weather<tool_sep:opensource>\n"
|
||||
"<arg_key:opensource>city</arg_key:opensource>\n"
|
||||
"<arg_value:opensource>Paris</arg_value:opensource>\n"
|
||||
"</tool_call:opensource>\n</tool_calls:opensource>" + _EOS,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp, tools=TOOLS)
|
||||
assert parsed.content == "Let me check."
|
||||
assert parsed.tool_calls[0].name == "get_weather"
|
||||
|
||||
|
||||
# ── tool-group re-opening (is_tool_first state machine) ─────────────────
|
||||
|
||||
|
||||
def test_tool_group_not_reopened_after_plain_assistant():
|
||||
"""The template resets ``is_tool_first`` only on an assistant that made
|
||||
tool calls; tool results arriving after a plain assistant continue the
|
||||
earlier <tool_responses> group without re-opening it. Byte-parity check
|
||||
on a shape the shared matrices never generate."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Weather?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "sunny"},
|
||||
{"role": "assistant", "content": "Checking again."},
|
||||
{"role": "tool", "content": "rainy"},
|
||||
{"role": "user", "content": "So?"},
|
||||
]
|
||||
ours = _renderer().render_ids(convo, tools=TOOLS, add_generation_prompt=True)
|
||||
theirs = _tok().apply_chat_template(
|
||||
convo,
|
||||
tools=TOOLS,
|
||||
add_generation_prompt=True,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
)
|
||||
assert ours == list(theirs)
|
||||
|
||||
|
||||
# ── preserved_thinking history retention ─────────────────────────────────
|
||||
|
||||
|
||||
def test_preserved_thinking_history_retention():
|
||||
"""A historical assistant (before the last user turn) keeps its reasoning
|
||||
only when ``preserved_thinking`` resolves True."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Q1"},
|
||||
{"role": "assistant", "reasoning_content": "R1", "content": "A1"},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{"role": "assistant", "reasoning_content": "R2", "content": "A2"},
|
||||
]
|
||||
stripped = _decode(_renderer(preserved_thinking=False).render_ids(convo))
|
||||
# Historical reasoning "R1" dropped; in-flight "R2" kept.
|
||||
assert "R1" not in stripped
|
||||
assert "R2" in stripped
|
||||
|
||||
kept = _decode(_renderer(preserved_thinking=True).render_ids(convo))
|
||||
assert "R1" in kept and "R2" in kept
|
||||
|
||||
|
||||
def test_preserved_thinking_defaults_to_tools_presence():
|
||||
"""With the default (None) config, the template keeps historical reasoning
|
||||
iff tools are supplied at render time."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Q1"},
|
||||
{"role": "assistant", "reasoning_content": "R1", "content": "A1"},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{"role": "assistant", "reasoning_content": "R2", "content": "A2"},
|
||||
]
|
||||
r = _renderer()
|
||||
assert "R1" not in _decode(r.render_ids(convo))
|
||||
assert "R1" in _decode(r.render_ids(convo, tools=TOOLS))
|
||||
|
||||
|
||||
# ── bridge policy resolution ─────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_effective_retention_defaults_conservative():
|
||||
assert _renderer().effective_thinking_retention == "tool_cycle"
|
||||
assert _renderer(preserved_thinking=True).effective_thinking_retention == "all"
|
||||
assert _renderer(thinking_retention="all").effective_thinking_retention == "all"
|
||||
|
||||
|
||||
def test_preserved_thinking_conflict_raises():
|
||||
with pytest.raises(ValueError):
|
||||
Hy3RendererConfig(preserved_thinking=True, thinking_retention="tool_cycle")
|
||||
with pytest.raises(ValueError):
|
||||
Hy3RendererConfig(preserved_thinking=False, thinking_retention="all")
|
||||
|
||||
|
||||
_BRIDGE_ASST = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
}
|
||||
_BRIDGE_EXT = [
|
||||
{"role": "tool", "content": "sunny"},
|
||||
{"role": "user", "content": "And tomorrow?"},
|
||||
]
|
||||
|
||||
|
||||
def test_bridge_default_config_with_tools_extends_across_user_turn():
|
||||
"""With the default (None) config the bridge policy mirrors the template's
|
||||
tools-dependent ``preserved_thinking``: a full render with tools keeps
|
||||
historical reasoning across user turns, so declining the bridge there
|
||||
would force a re-render that drops the verbatim sampled tokens for no
|
||||
semantic gain. The bridge must extend, byte-identical to a fresh render."""
|
||||
r = _renderer()
|
||||
prev = [{"role": "user", "content": "Weather?"}]
|
||||
pp = r.render_ids(prev, tools=TOOLS, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, _BRIDGE_ASST], tools=TOOLS)[len(pp) :])
|
||||
|
||||
bridged = r.bridge_to_next_turn(pp, pc, _BRIDGE_EXT, tools=TOOLS)
|
||||
fresh = r.render_ids(
|
||||
[*prev, _BRIDGE_ASST, *_BRIDGE_EXT], tools=TOOLS, add_generation_prompt=True
|
||||
)
|
||||
assert bridged is not None and bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_default_config_without_tools_declines_at_user_turn():
|
||||
"""Without tools the template default drops past-cycle reasoning once a
|
||||
new user query arrives, so the faithful bridge declines there."""
|
||||
r = _renderer()
|
||||
prev = [{"role": "user", "content": "Q1"}]
|
||||
pp = r.render_ids(prev, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, {"role": "assistant", "content": "A1"}])[len(pp) :])
|
||||
assert r.bridge_to_next_turn(pp, pc, [{"role": "user", "content": "Q2"}]) is None
|
||||
|
||||
|
||||
def test_bridge_explicit_tool_cycle_declines_at_user_turn_despite_tools():
|
||||
"""An explicit ``thinking_retention="tool_cycle"`` wins over the
|
||||
tools-dependent template default: the bridge still declines at a new
|
||||
user turn even though tools are present."""
|
||||
r = _renderer(thinking_retention="tool_cycle")
|
||||
prev = [{"role": "user", "content": "Weather?"}]
|
||||
pp = r.render_ids(prev, tools=TOOLS, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, _BRIDGE_ASST], tools=TOOLS)[len(pp) :])
|
||||
assert r.bridge_to_next_turn(pp, pc, _BRIDGE_EXT, tools=TOOLS) is None
|
||||
|
||||
|
||||
# ── is_training / raw_last_assistant / fallback_strategy ─────────────────
|
||||
|
||||
|
||||
def test_is_training_keeps_all_thinking_and_closes_final_assistant():
|
||||
"""``is_training=True`` keeps historical reasoning regardless of position
|
||||
and terminates the final assistant with ``<|hy_eos|>``."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Q1"},
|
||||
{"role": "assistant", "reasoning_content": "R1", "content": "A1"},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{"role": "assistant", "reasoning_content": "R2", "content": "A2"},
|
||||
]
|
||||
default = _decode(_renderer().render_ids(convo))
|
||||
training = _decode(_renderer(is_training=True).render_ids(convo))
|
||||
assert "R1" not in default and not default.endswith(_EOS)
|
||||
assert "R1" in training and "R2" in training and training.endswith(_EOS)
|
||||
|
||||
|
||||
def test_raw_last_assistant_drops_wrap_and_eos():
|
||||
"""A trailing non-tool assistant renders as bare visible content."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Q"},
|
||||
{"role": "assistant", "reasoning_content": "R", "content": "the answer"},
|
||||
]
|
||||
raw = _decode(_renderer(raw_last_assistant=True).render_ids(convo))
|
||||
assert raw.endswith(_ASSISTANT + "the answer") # no think wrap, no eos
|
||||
assert _THINK not in raw.split(_ASSISTANT)[-1]
|
||||
|
||||
|
||||
def test_fallback_strategy_forces_high_and_no_gen_prompt():
|
||||
"""``reasoning_toolcall_retry`` forces high effort and suppresses the gen
|
||||
prompt even when the caller asks for it."""
|
||||
r = _renderer(fallback_strategy="reasoning_toolcall_retry")
|
||||
ids = r.render_ids([{"role": "user", "content": "Hi"}], add_generation_prompt=True)
|
||||
text = _decode(ids)
|
||||
assert _REASONING_MODE + "reasoning_effort:high" in text
|
||||
assert not text.endswith(_ASSISTANT + _THINK) # gen prompt suppressed
|
||||
assert not text.endswith(_ASSISTANT)
|
||||
|
||||
|
||||
def test_fallback_strategy_bridge_matches_full_render():
|
||||
"""The bridge must also suppress the generation prompt under the fallback
|
||||
retry strategy, so it stays consistent with a fresh full render."""
|
||||
r = _renderer(
|
||||
fallback_strategy="reasoning_toolcall_retry", thinking_retention="all"
|
||||
)
|
||||
eos = _tok().convert_tokens_to_ids(_EOS)
|
||||
prior = [{"role": "user", "content": "Hi."}]
|
||||
pp = r.render_ids(prior, add_generation_prompt=True)
|
||||
full = r.render_ids([*prior, {"role": "assistant", "content": "Hello!"}])
|
||||
pc = list(full[len(pp) :])
|
||||
if not pc or pc[-1] != eos:
|
||||
pc = pc + [eos]
|
||||
|
||||
bridged = r.bridge_to_next_turn(pp, pc, [{"role": "tool", "content": "result"}])
|
||||
assert bridged is not None
|
||||
# No generation prompt appended (fallback forces add_generation_prompt=False).
|
||||
assert bridged.token_ids[-1] != _tok().convert_tokens_to_ids(_ASSISTANT)
|
||||
assert _ASSISTANT not in _decode(bridged.token_ids[len(pp) + len(pc) :])
|
||||
|
||||
|
||||
# ── tool-call token_span reporting ───────────────────────────────────────
|
||||
|
||||
|
||||
def test_tool_call_token_span_indexes_stripped_stream():
|
||||
"""``token_span`` must slice the stop-stripped completion back to the
|
||||
<tool_call>…</tool_call> block, accounting for the reasoning + leading
|
||||
content stripped before parsing."""
|
||||
from renderers.parsing import _strip_stop_tokens
|
||||
|
||||
r = _renderer(reasoning_effort="low")
|
||||
tok = _tok()
|
||||
comp = tok.encode(
|
||||
"Let me think." + _THINK_END + "Checking now."
|
||||
"<tool_calls:opensource>\n<tool_call:opensource>get_weather<tool_sep:opensource>\n"
|
||||
"<arg_key:opensource>city</arg_key:opensource>\n"
|
||||
"<arg_value:opensource>Paris</arg_value:opensource>\n"
|
||||
"</tool_call:opensource>\n</tool_calls:opensource>" + _EOS,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp, tools=TOOLS)
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.status is ToolCallParseStatus.OK
|
||||
stripped = _strip_stop_tokens(comp, {tok.convert_tokens_to_ids(_EOS)})
|
||||
s, e = tc.token_span
|
||||
assert stripped[s] == tok.convert_tokens_to_ids("<tool_call:opensource>")
|
||||
assert stripped[e - 1] == tok.convert_tokens_to_ids("</tool_call:opensource>")
|
||||
# The reported block decodes to exactly this call, no reasoning/content leak.
|
||||
block = tok.decode(stripped[s:e], skip_special_tokens=False)
|
||||
assert block.startswith("<tool_call:opensource>get_weather")
|
||||
assert "Let me think" not in block and "Checking now" not in block
|
||||
|
||||
|
||||
# ── bridge close-token synthesis ─────────────────────────────────────────
|
||||
|
||||
|
||||
def test_bridge_tool_cycle_matches_full_render():
|
||||
"""A bridge over a clean assistant tool-call turn (completion ends in
|
||||
<|hy_eos|>) must be byte-identical to a fresh full render — no spurious
|
||||
close token wedged in."""
|
||||
r = _renderer(thinking_retention="all")
|
||||
eos = _tok().convert_tokens_to_ids(_EOS)
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
}
|
||||
prev = [{"role": "user", "content": "Weather?"}]
|
||||
pp = r.render_ids(prev, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, asst])[len(pp) :])
|
||||
assert pc[-1] == eos # tool-call turn closes with eos
|
||||
|
||||
bridged = r.bridge_to_next_turn(pp, pc, [{"role": "tool", "content": '{"t": 20}'}])
|
||||
fresh = r.render_ids(
|
||||
[*prev, asst, {"role": "tool", "content": '{"t": 20}'}],
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
assert bridged is not None and bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_tool_groups_across_user_turn_match_full_render():
|
||||
"""Within one extension, ``is_tool_first`` is consumed by the first tool
|
||||
group and never resets (no assistant turns are allowed in extensions), so
|
||||
a second group after a user turn must not re-open <tool_responses> —
|
||||
exactly as a fresh full render tokenizes it."""
|
||||
r = _renderer(preserved_thinking=True)
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
}
|
||||
prev = [{"role": "user", "content": "Weather?"}]
|
||||
pp = r.render_ids(prev, tools=TOOLS, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, asst], tools=TOOLS)[len(pp) :])
|
||||
|
||||
ext = [
|
||||
{"role": "tool", "content": "sunny"},
|
||||
{"role": "user", "content": "And tomorrow?"},
|
||||
{"role": "tool", "content": "rainy"},
|
||||
]
|
||||
bridged = r.bridge_to_next_turn(pp, pc, ext, tools=TOOLS)
|
||||
fresh = r.render_ids([*prev, asst, *ext], tools=TOOLS, add_generation_prompt=True)
|
||||
assert bridged is not None and bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_declines_on_empty_completion():
|
||||
"""With no sampled completion there is no assistant turn to extend — the
|
||||
bridge declines (so a stream ending at a </tool_responses> tool-section
|
||||
boundary never gets a spurious <|hy_eos|> wedged before the extension)."""
|
||||
rf = _renderer(
|
||||
fallback_strategy="reasoning_toolcall_retry", thinking_retention="all"
|
||||
)
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
}
|
||||
base = [
|
||||
{"role": "user", "content": "Weather?"},
|
||||
asst,
|
||||
{"role": "tool", "content": '{"t": 20}'},
|
||||
]
|
||||
prompt = rf.render_ids(base, add_generation_prompt=True) # fallback → no gen prompt
|
||||
assert prompt[-1] == _tok().convert_tokens_to_ids("</tool_responses:opensource>")
|
||||
assert (
|
||||
rf.bridge_to_next_turn(prompt, [], [{"role": "tool", "content": "more"}])
|
||||
is None
|
||||
)
|
||||
@@ -65,6 +65,7 @@ _RENDERER_MODELS = [
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("poolside/Laguna-XS-2.1", "auto"),
|
||||
("tencent/Hy3", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
]
|
||||
|
||||
@@ -81,7 +82,22 @@ _KWARG_VALUES: dict[str, list[Any]] = {
|
||||
# renderer's typed config (``KimiK25RendererConfig.thinking``)
|
||||
# mirrors that name so the field maps 1:1 onto the template gate.
|
||||
"thinking": [True, False],
|
||||
"reasoning_effort": ["low", "medium", "high"],
|
||||
# gpt-oss accepts low/medium/high; Hy3 accepts no_think/low/high. The
|
||||
# union is listed here and the matrix builder drops values a given
|
||||
# renderer's typed config rejects (see ``_value_valid_for``).
|
||||
"reasoning_effort": ["no_think", "low", "medium", "high"],
|
||||
# Hy3 — keep <think>{reasoning}</think> on historical assistant turns
|
||||
# (True) vs collapse past-cycle reasoning to <think></think> (False).
|
||||
"preserved_thinking": [True, False],
|
||||
# Hy3 — SFT-target rendering (keep all thinking + close the final
|
||||
# assistant with <|hy_eos|>).
|
||||
"is_training": [True, False],
|
||||
# Hy3 — raw passthrough of a trailing non-tool assistant (no <think>
|
||||
# wrap, no eos) for prefill / continuation.
|
||||
"raw_last_assistant": [True, False],
|
||||
# Hy3 — sole active value forces reasoning_effort="high" +
|
||||
# add_generation_prompt=False.
|
||||
"fallback_strategy": ["reasoning_toolcall_retry"],
|
||||
# GLM-5 / GLM-5.1 — ``clear_thinking=False`` preserves the
|
||||
# ``<think>{reasoning}</think>`` wrap on historical assistants too
|
||||
# (default True collapses past-cycle reasoning to ``</think>``).
|
||||
@@ -264,6 +280,19 @@ def _template_fields_for(model: str, renderer_name: str) -> frozenset[str]:
|
||||
return _config_class_for(resolved).template_field_names()
|
||||
|
||||
|
||||
def _value_valid_for(model: str, renderer_name: str, kwarg: str, value: Any) -> bool:
|
||||
"""Whether ``value`` is accepted by this renderer's typed config for
|
||||
``kwarg``. Lets renderers share a template-field name with different value
|
||||
domains (e.g. ``reasoning_effort``: gpt-oss ``low/medium/high`` vs Hy3
|
||||
``no_think/low/high``) — the matrix keeps only the cells that construct."""
|
||||
resolved = _resolve_renderer_name(model, renderer_name)
|
||||
try:
|
||||
_config_class_for(resolved)(**{kwarg: value})
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _hf_parity_matrix() -> list[Any]:
|
||||
"""Auto-derived ``(model, renderer_name, kwarg, value)`` matrix for
|
||||
every renderer with template fields, minus gpt-oss (handled
|
||||
@@ -275,6 +304,8 @@ def _hf_parity_matrix() -> list[Any]:
|
||||
continue
|
||||
for kwarg in sorted(_template_fields_for(model, name)):
|
||||
for value in _KWARG_VALUES.get(kwarg, []):
|
||||
if not _value_valid_for(model, name, kwarg, value):
|
||||
continue
|
||||
out.append(
|
||||
pytest.param(
|
||||
model, name, kwarg, value, id=f"{model}-{kwarg}={value}"
|
||||
@@ -293,6 +324,8 @@ def _harmony_parity_matrix() -> list[Any]:
|
||||
continue
|
||||
for kwarg in sorted(_template_fields_for(model, name)):
|
||||
for value in _KWARG_VALUES.get(kwarg, []):
|
||||
if not _value_valid_for(model, name, kwarg, value):
|
||||
continue
|
||||
out.append(
|
||||
pytest.param(
|
||||
model, name, kwarg, value, id=f"{model}-{kwarg}={value}"
|
||||
|
||||
@@ -51,6 +51,7 @@ _ROUNDTRIP_MODELS = [
|
||||
# ``enable_thinking=False`` its template drops assistant reasoning at
|
||||
# render time, so the reasoning round-trip can't hold by design.
|
||||
# test_laguna_xs21.py covers the round-trip under enable_thinking=True.
|
||||
("tencent/Hy3", "auto"),
|
||||
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
|
||||
|
||||
Reference in New Issue
Block a user