Compare commits
50
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9619bf8f0 | ||
|
|
bdb96b0c84 | ||
|
|
201f88516c | ||
|
|
b6635d261c | ||
|
|
fa04acd916 | ||
|
|
33c8e6f897 | ||
|
|
0d104d82e3 | ||
|
|
defaf8fe2e | ||
|
|
4472b743a6 | ||
|
|
5904fa24aa | ||
|
|
db8698aaa8 | ||
|
|
a5efbb97e4 | ||
|
|
082836b5a8 | ||
|
|
42d6ee930b | ||
|
|
1933293372 | ||
|
|
0dc19a060e | ||
|
|
fe1dcdaed7 | ||
|
|
20d89be418 | ||
|
|
67568f79cf | ||
|
|
a3bf7e88b4 | ||
|
|
d80f36e287 | ||
|
|
1dca3b9a2d | ||
|
|
e6dba5ad6c | ||
|
|
596c15ffd9 | ||
|
|
942449c37a | ||
|
|
9f3b24c0ac | ||
|
|
35c2407e92 | ||
|
|
a11f8d8193 | ||
|
|
89ab3f0bed | ||
|
|
e729baa5af | ||
|
|
74425da166 | ||
|
|
1569dc980d | ||
|
|
1d69232253 | ||
|
|
88aa42d40f | ||
|
|
647335489d | ||
|
|
2ec28a8543 | ||
|
|
c86c50b72e | ||
|
|
1831bcc50c | ||
|
|
3ae276c446 | ||
|
|
1691f87e90 | ||
|
|
9e11214dd5 | ||
|
|
143ffdee56 | ||
|
|
f9414b1e95 | ||
|
|
ee9703fcc9 | ||
|
|
3177399b79 | ||
|
|
8704f9d502 | ||
|
|
fdc03f2861 | ||
|
|
d547eef54c | ||
|
|
25ba413d46 | ||
|
|
17d0584f87 |
@@ -0,0 +1,67 @@
|
||||
name: Publish Dev
|
||||
|
||||
# Every push to main publishes a pre-release wheel to PyPI. The version
|
||||
# is derived at build time by hatch-vcs from ``git describe`` distance
|
||||
# to the latest stable ``renderers-v<MAJOR>.<MINOR>.<PATCH>`` tag (see
|
||||
# ``[tool.hatch.version.raw-options]`` in pyproject.toml) — no per-commit
|
||||
# tag is created. ``local_scheme = "no-local-version"`` strips the
|
||||
# ``+gHASH`` segment so PyPI accepts the wheel directly.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: publish-dev-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# Build (no OIDC) → publish (OIDC only). The build job runs ``uv build``
|
||||
# with ``contents: read`` only so a poisoned build-time dep cannot mint
|
||||
# the OIDC token. The publish job has ``id-token: write`` and the
|
||||
# pypi-prod environment but no source checkout — it only downloads the
|
||||
# prebuilt artifact and runs the SHA-pinned pypa publish action.
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# hatch-vcs needs the full tag history to resolve the version
|
||||
# from the latest stable tag's distance.
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Build renderers
|
||||
run: uv build
|
||||
|
||||
- name: Show derived version
|
||||
run: ls -1 dist/
|
||||
|
||||
- name: Upload dist artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dist-dev
|
||||
path: dist/
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
publish:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
environment: pypi-prod
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Download dist artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: dist-dev
|
||||
path: dist/
|
||||
|
||||
- name: Publish to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
|
||||
with:
|
||||
skip-existing: true
|
||||
@@ -31,3 +31,6 @@ coverage.xml
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
|
||||
# agent harness state
|
||||
.claude/
|
||||
|
||||
@@ -17,7 +17,7 @@ from transformers import AutoTokenizer
|
||||
from renderers import create_renderer
|
||||
|
||||
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
|
||||
r = create_renderer(tok, renderer="auto") # → Qwen3Renderer
|
||||
r = create_renderer(tok) # → Qwen3Renderer (auto-resolved)
|
||||
|
||||
prompt_ids = r.render_ids(
|
||||
[{"role": "user", "content": "hi"}],
|
||||
@@ -40,7 +40,7 @@ next_prompt_ids = r.bridge_to_next_turn(
|
||||
)
|
||||
```
|
||||
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `deepseek-r1`, `kimi-k2`, `kimi-k2.5` / `kimi-k2.6`, `nemotron-3`, `nemotron-3-ultra`, `llama-3`, `gpt-oss`, `hy3`, and `prime-qwen3`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
|
||||
|
||||
## API
|
||||
|
||||
@@ -71,17 +71,17 @@ Each hand-coded bridge:
|
||||
### Picking a renderer
|
||||
|
||||
```python
|
||||
r = create_renderer(tok, renderer="auto")
|
||||
r = create_renderer(tok) # AutoRendererConfig is the implicit default
|
||||
```
|
||||
|
||||
Auto-detect matches `tokenizer.name_or_path` against `MODEL_RENDERER_MAP` by **exact match**. Prefix matching is intentionally off — same architecture can ship different chat templates (base vs instruct, fine-tune renames). Fine-tunes must pass `renderer=<name>` explicitly; unknown names fall back to `DefaultRenderer`.
|
||||
Auto-detect matches `tokenizer.name_or_path` against `MODEL_RENDERER_MAP` by **exact match**. Prefix matching is intentionally off — same architecture can ship different chat templates (base vs instruct, fine-tune renames). Fine-tunes must pass an explicit typed config (e.g. `Qwen3RendererConfig()`). Unknown text-only names fall back to `DefaultRenderer`, unless `AutoRendererConfig(thinking_retention=...)` was set; the default renderer cannot implement that bridge policy.
|
||||
|
||||
### Pools
|
||||
|
||||
```python
|
||||
from renderers import create_renderer_pool
|
||||
|
||||
pool = create_renderer_pool("Qwen/Qwen3-8B", renderer="auto", size=16)
|
||||
pool = create_renderer_pool("Qwen/Qwen3-8B", size=16)
|
||||
with pool.checkout() as r:
|
||||
ids = r.render_ids(messages)
|
||||
```
|
||||
@@ -95,7 +95,6 @@ For RL the trainer must see the exact token ids the sampler saw. The standard al
|
||||
- **Boolean round-trip.** Engine emits `false`; client parses to Python `bool(False)`; `apply_chat_template` re-renders via `str(False)` → `"False"`. Capital F. Reproducible on Qwen3.5-35B-A3B + mini-swe-agent-plus at ~50% break rate per rollout.
|
||||
- **BPE retokenization drift.** The same substring tokenizes differently depending on neighbouring bytes. `json` + `p` + `enderer` (3 tokens) vs `jsonp` + `enderer` (2 tokens) when whitespace shifts by one character. Every subsequent token is shifted from there on.
|
||||
- **Tool-call XML drift.** The engine emits a no-arg call with a stylistic empty `</parameter>`; the Jinja re-render of the reconstructed dict drops it. Extension property broken at every such call.
|
||||
- **Thinking stripped from non-latest assistants.** Some templates strip `<think>…</think>` blocks from prior assistant turns when re-rendering. The recorded stream has the thinking; the next prompt does not.
|
||||
- **Max-seq-len truncation zeroing the anchor.** Client-side `max_seq_len` enforcement zeros `completion_ids` when `prompt_len > max_seq_len`. The bridge anchor is empty, falling back to full re-render — triggering every mode above.
|
||||
- **Scaffold-level history rewriting.** Some agent scaffolds (e.g. opencode's `experimental_repairToolCall`) rewrite tool calls before sending them back as history. The next turn's prompt contains a tool call the model never emitted. *A renderer cannot fix this — the drift happens before rendering.*
|
||||
|
||||
@@ -108,30 +107,60 @@ Empirical delta on Qwen3.5-35B-A3B + mini-swe-agent-plus, step 0:
|
||||
|
||||
Each break fragments a rollout into multiple training samples — every fragment re-encodes its prefix, inflating compute roughly linearly with the number of breaks.
|
||||
|
||||
## Compaction overrides
|
||||
## Typed renderer configs
|
||||
|
||||
`create_renderer` and `create_renderer_pool` accept two constructor-only flags:
|
||||
Each renderer accepts a typed pydantic config at construction. Some fields mirror chat-template kwargs; others configure renderer-only behavior such as image caching, parsers, or Harmony preamble construction. `create_renderer` and `create_renderer_pool` take one positional `config` argument and an optional keyword-only `chat_template_kwargs` mapping:
|
||||
|
||||
```python
|
||||
preserve_all_thinking: bool = False
|
||||
preserve_thinking_between_tool_calls: bool = False
|
||||
from renderers import (
|
||||
create_renderer,
|
||||
AutoRendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
GLM5RendererConfig,
|
||||
DefaultRendererConfig,
|
||||
)
|
||||
|
||||
# Auto-resolve renderer from the tokenizer's model name.
|
||||
renderer = create_renderer(tokenizer)
|
||||
renderer = create_renderer(tokenizer, AutoRendererConfig(thinking_retention="all"))
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
# Explicit choice — use the renderer-specific fields it exposes.
|
||||
renderer = create_renderer(tokenizer, Qwen3RendererConfig(enable_thinking=False))
|
||||
renderer = create_renderer(tokenizer, GLM5RendererConfig(clear_thinking=False))
|
||||
|
||||
# Default renderer (apply_chat_template fallback) — extra fields are
|
||||
# captured via pydantic ``extra="allow"`` and forwarded to the Jinja
|
||||
# template; tool / reasoning parsers are typed.
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
DefaultRendererConfig(tool_parser="qwen3", reasoning_parser="think"),
|
||||
)
|
||||
```
|
||||
|
||||
Defaults preserve byte-identity with the model's chat template. Flipping a flag at construction restores `reasoning_content` the template would otherwise drop:
|
||||
Discriminated union: every per-renderer config is a variant of `RendererConfig`, dispatched on the `name` field. Bogus combinations (e.g. `add_vision_id` under `name="qwen3"`) error at construction with a `pydantic.ValidationError`. Downstream pydantic configs (prime-rl orchestrator, verifiers `ClientConfig`) hold a single field typed as `RendererConfig` and inherit the same strict-per-variant validation.
|
||||
|
||||
- `preserve_all_thinking=True` — every past assistant's reasoning is kept.
|
||||
- `preserve_thinking_between_tool_calls=True` — reasoning is kept on assistants in the in-flight tool cycle (no-op for current renderers; reserved for future templates that drop it).
|
||||
When `chat_template_kwargs` is passed with `config=None` / `AutoRendererConfig`, renderers first resolves the concrete renderer from the model name, then validates those kwargs against that renderer's config. `Auto + unknown model + chat_template_kwargs` fails loudly; use an explicit typed config or explicit `DefaultRendererConfig` for opaque fallback templates.
|
||||
|
||||
The canonical use case is **compaction**. Injecting a `user` turn like *"summarize the work so far"* puts every prior assistant in a "past cycle", so template-default rules drop their `reasoning_content` before the summarizer sees it. Build the renderer with `preserve_all_thinking=True` to keep reasoning visible end-to-end on those flows. Both flags only ever *add* tokens vs the template default.
|
||||
One shared behaviour flag lives on typed renderer configs: `thinking_retention`, an optional bridge-policy override. Leave it unset to derive bridge behaviour from the chat template and its renderer-exposed kwargs.
|
||||
|
||||
- `thinking_retention=None` (default) — derive from the chat template / renderer kwargs.
|
||||
- `thinking_retention="tool_cycle"` — bridge within the in-flight tool cycle; a new user query falls back to a full re-render.
|
||||
- `thinking_retention="all"` — bridge across user-query boundaries when the bridge is otherwise structurally valid.
|
||||
|
||||
Generic `thinking_retention` does **not** change full `render()` output: a full re-render always follows the Python chat-template implementation. Only real template knobs can change full-render thinking behaviour. GLM-5 `clear_thinking=False`, Nemotron-3 `truncate_history_thinking=False`, Qwen3.6 `preserve_thinking=True`, and GPT-OSS `auto_drop_analysis=False` all imply bridge policy `"all"`; no-thinking generation knobs also imply `"all"` when `thinking_retention` is unset. Setting a direct keep/drop template knob and a contradictory `thinking_retention` raises at config-load. The full per-renderer mapping lives in [`docs/renderer-config.md`](docs/renderer-config.md).
|
||||
|
||||
## `DefaultRenderer`
|
||||
|
||||
Fallback for unsupported models. Wraps `apply_chat_template` and accepts `tool_parser` / `reasoning_parser` kwargs (vLLM convention). `bridge_to_next_turn` returns `None` because the template's close is unknown, so multi-turn rollouts fall back to full re-render. Implementing a hand-coded renderer is a few hundred lines of Python (`render_ids` + `parse_response` + `bridge_to_next_turn`) and is the only path that closes the failure modes above by construction.
|
||||
Fallback for unsupported text-only models. Wraps `apply_chat_template` and accepts `tool_parser` / `reasoning_parser` (vLLM convention) plus arbitrary Jinja kwargs via `DefaultRendererConfig`'s `extra="allow"`. Explicit `thinking_retention` is rejected: `bridge_to_next_turn` returns `None` because the template's close is unknown, so multi-turn rollouts fall back to full re-render. Implementing a hand-coded renderer is a few hundred lines of Python (`render_ids` + `parse_response` + `bridge_to_next_turn`) and is the only path that closes the failure modes above by construction.
|
||||
|
||||
## Roadmap
|
||||
|
||||
- **VLM support.** `ContentPart` is text-only today; `Qwen3VLRenderer` ships only because Qwen3-VL's text-only chat template differs from Qwen3's. Plan: add `ImagePart` / `VideoPart`, multimodal bridges, validate against a Qwen3-VL RL run.
|
||||
- **Patched chat templates.** Some shipped templates re-tokenize history, normalize JSON, or auto-strip thinking — each breaks the extension property. Plan: a `use_patched` opt-in per renderer that renders the same surface form while avoiding known-bad patterns.
|
||||
- **VLM expansion.** `ImagePart` support exists for Qwen3-VL and Qwen3.5-family multimodal templates. Remaining work: video support, broader VLM coverage, and more RL validation.
|
||||
- **Patched chat templates.** Some shipped templates re-tokenize history or normalize JSON in ways that break token identity. Plan: a `use_patched` opt-in per renderer that renders the same surface form while avoiding known-bad patterns. (Auto-stripping thinking from past turns is *not* one of these — that's intended template behaviour the renderer reproduces; use `thinking_retention` to override it.)
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
# Renderer config
|
||||
|
||||
`renderers.RendererConfig` is the typed input to `create_renderer` and
|
||||
`create_renderer_pool`. It pins the renderer choice and its config at
|
||||
construction time.
|
||||
|
||||
```python
|
||||
from renderers import create_renderer, Qwen35RendererConfig
|
||||
|
||||
r = create_renderer(tokenizer, Qwen35RendererConfig(enable_thinking=False))
|
||||
r = create_renderer(tokenizer, chat_template_kwargs={"enable_thinking": False})
|
||||
```
|
||||
|
||||
`RendererConfig` is a pydantic discriminated union, one variant per renderer,
|
||||
dispatched on the `name` field. Most variants reject unknown fields at
|
||||
construction. A field can either mirror a chat-template kwarg or configure a
|
||||
renderer-only behavior such as parsing, image caching, or Harmony preamble
|
||||
construction.
|
||||
|
||||
## Per-renderer configs
|
||||
|
||||
Use `type(config).template_field_names()` to inspect the fields that mirror
|
||||
chat-template kwargs. Those fields are covered by parity tests against
|
||||
`apply_chat_template` in `tests/test_renderer_config_parity.py`.
|
||||
|
||||
| Renderer | Config class | Template fields | Renderer-only fields |
|
||||
| --- | --- | --- | --- |
|
||||
| Qwen3 | `Qwen3RendererConfig` | `enable_thinking` | - |
|
||||
| PrimeIntellect Qwen3 | `PrimeQwen3RendererConfig` | - | - |
|
||||
| Qwen3.5 | `Qwen35RendererConfig` | `enable_thinking`, `add_vision_id` | `image_cache_max` |
|
||||
| Qwen3.6 | `Qwen36RendererConfig` | `enable_thinking`, `add_vision_id`, `preserve_thinking` | `image_cache_max` |
|
||||
| Qwen3-VL | `Qwen3VLRendererConfig` | `add_vision_id` | `image_cache_max` |
|
||||
| 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` | - |
|
||||
| Laguna XS-2.1 | `LagunaXS21RendererConfig` | `enable_thinking` | - |
|
||||
| Llama 3 | `Llama3RendererConfig` | `date_string`, `tools_in_user_message` | - |
|
||||
| MiniMax M2 | `MiniMaxM2RendererConfig` | `model_identity` | - |
|
||||
| Nemotron-3 Nano / Super | `Nemotron3RendererConfig` | `enable_thinking`, `truncate_history_thinking`, `low_effort` | - |
|
||||
| Nemotron-3 Ultra | `Nemotron3UltraRendererConfig` | `enable_thinking`, `truncate_history_thinking`, `medium_effort` | - |
|
||||
| DeepSeek V3 | `DeepSeekV3RendererConfig` | - | - |
|
||||
| DeepSeek R1 | `DeepSeekR1RendererConfig` | - | - |
|
||||
|
||||
Configs are frozen value objects. To override a field, construct a new instance
|
||||
or call `config.model_copy(update={...})`.
|
||||
|
||||
## Auto-resolution
|
||||
|
||||
`create_renderer(tokenizer)` resolves the renderer from `tokenizer.name_or_path`
|
||||
via `MODEL_RENDERER_MAP`:
|
||||
|
||||
```python
|
||||
from renderers import AutoRendererConfig, GLM5RendererConfig
|
||||
|
||||
r = create_renderer(tokenizer)
|
||||
r = create_renderer(tokenizer, AutoRendererConfig(thinking_retention="all"))
|
||||
r = create_renderer(tokenizer, GLM5RendererConfig(clear_thinking=False))
|
||||
```
|
||||
|
||||
`AutoRendererConfig` carries only the shared `thinking_retention` override.
|
||||
Callers that receive run-scoped chat-template kwargs can pass them separately:
|
||||
|
||||
```python
|
||||
r = create_renderer(
|
||||
tokenizer,
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
pool = create_renderer_pool(
|
||||
"Qwen/Qwen3-8B",
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
```
|
||||
|
||||
Renderers resolves auto configs before applying `chat_template_kwargs`, so the
|
||||
kwargs validate against the concrete renderer config. Unknown kwargs, or kwargs
|
||||
that conflict with an explicit `thinking_retention`, fail at construction.
|
||||
|
||||
Auto-resolution fails loudly for VLMs without an exact registered renderer.
|
||||
Text-only unknown models fall back to `DefaultRenderer`, unless
|
||||
`AutoRendererConfig(thinking_retention=...)` was set. The default renderer
|
||||
cannot implement selective bridge retention, so that combination raises.
|
||||
`AutoRendererConfig` with `chat_template_kwargs` also raises for unknown models,
|
||||
because renderers cannot validate those kwargs without a concrete renderer.
|
||||
Use an explicit model-specific config, or `DefaultRendererConfig(...)` when you
|
||||
intentionally want opaque `apply_chat_template` kwargs.
|
||||
|
||||
## `thinking_retention`
|
||||
|
||||
Every typed renderer config carries one shared optional bridge-policy override:
|
||||
|
||||
```python
|
||||
thinking_retention: Literal["tool_cycle", "all"] | None = None
|
||||
```
|
||||
|
||||
| Value | Meaning |
|
||||
| --- | --- |
|
||||
| `None` | Derive the effective bridge policy from the renderer's template knobs and defaults. |
|
||||
| `"tool_cycle"` | Bridge within the current tool cycle; re-render when the extension opens a new user query. |
|
||||
| `"all"` | Allow bridging across user-query boundaries when the bridge is otherwise structurally valid. |
|
||||
|
||||
`thinking_retention` affects `bridge_to_next_turn`, not full `render()`.
|
||||
A full render always follows the Python chat-template implementation. Only real
|
||||
template fields, such as `clear_thinking`, `preserve_thinking`, or
|
||||
`truncate_history_thinking`, can change full-render historical thinking.
|
||||
|
||||
Internally, renderers resolve an `effective_thinking_retention` at construction:
|
||||
|
||||
| Internal policy | Bridge behavior |
|
||||
| --- | --- |
|
||||
| `"template"` | Decline bridging; caller falls back to a full re-render. |
|
||||
| `"tool_cycle"` | Bridge unless `new_messages` introduces a user query. |
|
||||
| `"all"` | Do not block bridging for thinking retention. |
|
||||
|
||||
`"template"` is not a public config value. Leave `thinking_retention` unset to
|
||||
get template-derived behavior.
|
||||
|
||||
## Derived retention defaults
|
||||
|
||||
When `thinking_retention` is unset, each renderer derives its bridge policy from
|
||||
the knobs its template actually exposes:
|
||||
|
||||
| Renderer | Derived policy |
|
||||
| --- | --- |
|
||||
| Qwen3 | `enable_thinking=False -> all`, else `tool_cycle` |
|
||||
| Qwen3.5 | `enable_thinking=False -> all`, else `tool_cycle` |
|
||||
| Qwen3.6 | `preserve_thinking=True -> all`; else `enable_thinking=False -> all`; else `tool_cycle` |
|
||||
| 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` |
|
||||
| MiniMax M2 | `tool_cycle` |
|
||||
| DeepSeek V3, Qwen3-VL, Kimi K2, Laguna XS.2 / XS-2.1, Llama 3 | `all` |
|
||||
| PrimeIntellect Qwen3 | `all` |
|
||||
|
||||
Config construction raises when an explicit template knob directly contradicts
|
||||
an explicit generic bridge policy. For example:
|
||||
|
||||
```python
|
||||
GLM5RendererConfig(clear_thinking=False, thinking_retention="tool_cycle")
|
||||
# ValueError: clear_thinking=False implies thinking_retention="all"
|
||||
```
|
||||
|
||||
Generation-only no-thinking knobs, such as `enable_thinking=False`, do not
|
||||
conflict with an explicit conservative `thinking_retention="tool_cycle"`. They
|
||||
only change the derived default when `thinking_retention` is unset.
|
||||
|
||||
## `DefaultRendererConfig`
|
||||
|
||||
`DefaultRenderer` wraps `tokenizer.apply_chat_template` for unsupported
|
||||
text-only models. Its config sets `extra="allow"` so unknown fields are
|
||||
forwarded as Jinja kwargs:
|
||||
|
||||
```python
|
||||
from renderers import create_renderer, DefaultRendererConfig
|
||||
|
||||
r = create_renderer(
|
||||
tokenizer,
|
||||
DefaultRendererConfig(
|
||||
tool_parser="qwen3",
|
||||
reasoning_parser="think",
|
||||
enable_thinking=False,
|
||||
custom_jinja_kwarg=True,
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
`tool_parser` and `reasoning_parser` configure `DefaultRenderer` itself. Every
|
||||
other extra field lands in `model_extra` and is forwarded to
|
||||
`apply_chat_template`.
|
||||
|
||||
`DefaultRenderer` rejects explicit `thinking_retention` and the removed
|
||||
`preserve_*` flags. Its bridge always returns `None`, because the template's
|
||||
turn-close structure is opaque to the renderer.
|
||||
|
||||
## Downstream integration
|
||||
|
||||
Downstream pydantic configs can hold a single field typed as `RendererConfig`:
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
|
||||
class ClientConfig(BaseModel):
|
||||
renderer: RendererConfig = Field(default_factory=AutoRendererConfig)
|
||||
```
|
||||
|
||||
In TOML or YAML, the `name` discriminator selects the variant:
|
||||
|
||||
```toml
|
||||
[client.renderer]
|
||||
name = "qwen3.5"
|
||||
enable_thinking = false
|
||||
add_vision_id = true
|
||||
thinking_retention = "all"
|
||||
```
|
||||
|
||||
Bogus combinations, such as `add_vision_id` under `name = "qwen3"`, raise at
|
||||
config load with a pydantic validation error.
|
||||
|
||||
To construct a config from a renderer name string:
|
||||
|
||||
```python
|
||||
from renderers import config_from_name
|
||||
|
||||
cfg = config_from_name("glm-5") # GLM5RendererConfig()
|
||||
cfg = config_from_name("auto") # None, the implicit auto form
|
||||
```
|
||||
|
||||
## Renaming a renderer is a breaking change
|
||||
|
||||
The discriminator key is the renderer name string. Renaming `"qwen3.5"` to
|
||||
something else would break downstream configs that reference it by name. Add
|
||||
new renderers instead of renaming existing ones.
|
||||
@@ -22,6 +22,7 @@ import json
|
||||
import os
|
||||
|
||||
import sglang as sgl
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from transformers import AutoTokenizer
|
||||
@@ -52,7 +53,9 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None):
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(
|
||||
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -62,8 +65,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -141,21 +145,33 @@ def main() -> None:
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -167,11 +183,14 @@ def main() -> None:
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
@@ -44,6 +44,7 @@ from typing import Any
|
||||
|
||||
import httpx
|
||||
from renderers.base import Renderer
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from transformers import AutoTokenizer
|
||||
@@ -71,7 +72,9 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None) -> Renderer:
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(
|
||||
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -116,8 +119,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -164,21 +168,33 @@ async def run_one(
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages: list[dict[str, Any]] = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -190,11 +206,14 @@ async def run_one(
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
@@ -22,6 +22,7 @@ import json
|
||||
import os
|
||||
|
||||
import tinker
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from tinker import types
|
||||
@@ -53,7 +54,9 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None):
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(
|
||||
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -63,8 +66,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -131,21 +135,33 @@ async def main() -> None:
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -157,11 +173,14 @@ async def main() -> None:
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
@@ -26,6 +26,7 @@ import os
|
||||
import torch
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
|
||||
@@ -55,7 +56,8 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None):
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking), tokenizer
|
||||
config = Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(tokenizer, config), tokenizer
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer), tokenizer
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -65,8 +67,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -139,21 +142,33 @@ def main() -> None:
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -165,11 +180,14 @@ def main() -> None:
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
@@ -21,6 +21,7 @@ import gc
|
||||
import json
|
||||
import os
|
||||
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from transformers import AutoTokenizer
|
||||
@@ -52,7 +53,9 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None):
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(
|
||||
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -62,8 +65,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -134,21 +138,33 @@ def main() -> None:
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -160,11 +176,14 @@ def main() -> None:
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
+40
-7
@@ -23,13 +23,19 @@ dependencies = [
|
||||
# Used by GptOssRenderer to render and parse harmony tokens. Vendoring
|
||||
# OpenAI's reference implementation keeps us byte-identical with vLLM
|
||||
# (which also uses it) and saves us mirroring a 330-line Jinja template.
|
||||
"openai-harmony>=0.0.8",
|
||||
# Crusoe's Rust BPE tokenizer; ~10x faster encode vs HF's tokenizers.
|
||||
# ``load_tokenizer`` patches it in by default for every supported model
|
||||
# except a small denylist (DeepSeek-V3 family, MiniMax-M2 family). The
|
||||
# patch is bracketed around ``from_pretrained``, so subsequent
|
||||
# ``AutoTokenizer`` calls outside the renderers package stay vanilla.
|
||||
"fastokens>=0.1.1",
|
||||
#
|
||||
# Floor is ``>=0.0.4`` (not the latest 0.0.8) on purpose: every SGLang
|
||||
# release through 0.5.12.post1 hard-pins ``openai-harmony==0.0.4``, so a
|
||||
# higher floor makes ``renderers`` uninstallable alongside SGLang. The
|
||||
# GptOssRenderer renders byte-identically on 0.0.4 (verified token-for-token
|
||||
# against 0.0.8) and ``tests/test_gpt_oss_harmony_parity.py`` passes on it,
|
||||
# so the older harmony is safe.
|
||||
"openai-harmony>=0.0.4",
|
||||
# ``BaseRendererConfig`` inherits from ``pydantic_config.BaseConfig`` so
|
||||
# the typed-config surface stays uniform with prime-rl / verifiers config
|
||||
# bases. Transitively brings pydantic, which ``renderers.configs`` also
|
||||
# imports directly.
|
||||
"prime-pydantic-config>=0.3.0.dev83",
|
||||
]
|
||||
|
||||
[tool.hatch.version]
|
||||
@@ -45,6 +51,22 @@ tag-pattern = '^renderers-v(?P<version>.+)$'
|
||||
# only fires when the resolver has nothing to go on.
|
||||
fallback-version = "0.0.0"
|
||||
|
||||
[tool.hatch.version.raw-options]
|
||||
# Only stable ``renderers-v<MAJOR>.<MINOR>.<PATCH>`` tags participate in
|
||||
# version resolution; legacy per-commit ``.devN`` tags are excluded.
|
||||
# Untagged commits get a clean PEP 440 dev version derived from distance
|
||||
# to the latest stable tag (e.g. ``0.1.8.dev46``), with no ``+gHASH``
|
||||
# local segment so PyPI accepts the wheel directly. setuptools-scm
|
||||
# refuses to bump a pre-existing ``.devN`` tag, so matching only stable
|
||||
# tags also unblocks local ``uv lock`` / ``uv build`` on untagged
|
||||
# branches. Mirrors verifiers' setup.
|
||||
local_scheme = "no-local-version"
|
||||
git_describe_command = [
|
||||
"git", "describe", "--tags", "--long",
|
||||
"--match", "renderers-v[0-9]*.[0-9]*.[0-9]*",
|
||||
"--exclude", "*dev*",
|
||||
]
|
||||
|
||||
[tool.hatch.build.hooks.vcs]
|
||||
# Write the resolved version to a Python file so it can be inspected
|
||||
# at runtime via ``renderers.__version__`` without re-parsing the
|
||||
@@ -67,8 +89,19 @@ 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]
|
||||
# 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"
|
||||
|
||||
|
||||
+121
-17
@@ -19,6 +19,7 @@ from renderers.base import (
|
||||
PlaceholderRange,
|
||||
RenderedConversation,
|
||||
RenderedTokens,
|
||||
RenderedTrainingSample,
|
||||
Renderer,
|
||||
RendererPool,
|
||||
TextPart,
|
||||
@@ -28,57 +29,157 @@ from renderers.base import (
|
||||
ToolCallParseStatus,
|
||||
ToolSpec,
|
||||
VideoPart,
|
||||
attribute_text_segments,
|
||||
build_training_sample,
|
||||
build_trajectory_step,
|
||||
create_renderer,
|
||||
create_renderer_pool,
|
||||
extract_message_tool_names,
|
||||
is_multimodal,
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.deepseek_v3 import DeepSeekV3Renderer
|
||||
from renderers.default import DefaultRenderer
|
||||
from renderers.glm5 import GLM5Renderer
|
||||
from renderers.glm45 import GLM45Renderer
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.kimi_k2 import KimiK2Renderer
|
||||
from renderers.kimi_k25 import KimiK25Renderer
|
||||
from renderers.laguna_xs2 import LagunaXS2Renderer
|
||||
from renderers.minimax_m2 import MiniMaxM2Renderer
|
||||
from renderers.nemotron3 import Nemotron3Renderer
|
||||
from renderers.qwen3 import Qwen3Renderer
|
||||
from renderers.qwen3_vl import Qwen3VLRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from renderers.qwen36 import Qwen36Renderer
|
||||
from renderers.client import OverlongPromptError
|
||||
from renderers.configs import (
|
||||
AutoRendererConfig,
|
||||
BaseRendererConfig,
|
||||
config_from_name,
|
||||
DefaultRendererConfig,
|
||||
DeepSeekR1RendererConfig,
|
||||
DeepSeekV3RendererConfig,
|
||||
GLM45RendererConfig,
|
||||
GLM51RendererConfig,
|
||||
GLM5RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
Hy3RendererConfig,
|
||||
KimiK25RendererConfig,
|
||||
KimiK2RendererConfig,
|
||||
LagunaXS2RendererConfig,
|
||||
LagunaXS21RendererConfig,
|
||||
Llama3RendererConfig,
|
||||
MiniMaxM2RendererConfig,
|
||||
Nemotron3RendererConfig,
|
||||
Nemotron3UltraRendererConfig,
|
||||
PrimeQwen3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
Qwen36RendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
Qwen3VLRendererConfig,
|
||||
RendererConfig,
|
||||
)
|
||||
|
||||
# Concrete renderer classes are lazy-loaded so that consumers needing
|
||||
# only the config layer (``RendererConfig`` discriminated union) don't
|
||||
# pay the ``transformers`` import cost. Each renderer module does
|
||||
# ``from transformers.tokenization_utils import PreTrainedTokenizer``
|
||||
# at module level, so eager imports here would drag ``transformers``
|
||||
# into every downstream ``import renderers``. ``__getattr__`` (PEP 562)
|
||||
# resolves the names on first attribute access, so ``from renderers
|
||||
# import DefaultRenderer`` and ``renderers.DefaultRenderer`` both work
|
||||
# transparently. ``create_renderer`` doesn't depend on these eager
|
||||
# imports — ``renderers.base._populate_registry`` lazy-imports the
|
||||
# concrete classes itself when a renderer is instantiated.
|
||||
_LAZY_RENDERERS: dict[str, str] = {
|
||||
"DeepSeekR1Renderer": "renderers.deepseek_r1",
|
||||
"DeepSeekV3Renderer": "renderers.deepseek_v3",
|
||||
"DefaultRenderer": "renderers.default",
|
||||
"GLM45Renderer": "renderers.glm45",
|
||||
"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",
|
||||
"LagunaXS2Renderer": "renderers.laguna_xs2",
|
||||
"Llama3Renderer": "renderers.llama_3",
|
||||
"MiniMaxM2Renderer": "renderers.minimax_m2",
|
||||
"Nemotron3Renderer": "renderers.nemotron3",
|
||||
"Nemotron3UltraRenderer": "renderers.nemotron3",
|
||||
"PrimeQwen3Renderer": "renderers.prime_qwen3",
|
||||
"Qwen35Renderer": "renderers.qwen35",
|
||||
"Qwen36Renderer": "renderers.qwen36",
|
||||
"Qwen3Renderer": "renderers.qwen3",
|
||||
"Qwen3VLRenderer": "renderers.qwen3_vl",
|
||||
}
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
if name in _LAZY_RENDERERS:
|
||||
import importlib
|
||||
|
||||
module = importlib.import_module(_LAZY_RENDERERS[name])
|
||||
value = getattr(module, name)
|
||||
globals()[name] = value # cache for subsequent lookups
|
||||
return value
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
|
||||
|
||||
def __dir__() -> list[str]:
|
||||
return sorted(set(globals().keys()) | set(_LAZY_RENDERERS))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AutoRendererConfig",
|
||||
"BaseRendererConfig",
|
||||
"Content",
|
||||
"ContentPart",
|
||||
"DeepSeekR1Renderer",
|
||||
"DeepSeekR1RendererConfig",
|
||||
"DeepSeekV3Renderer",
|
||||
"DeepSeekV3RendererConfig",
|
||||
"DefaultRenderer",
|
||||
"DefaultRendererConfig",
|
||||
"GLM45Renderer",
|
||||
"GLM45RendererConfig",
|
||||
"GLM51Renderer",
|
||||
"GLM51RendererConfig",
|
||||
"GLM5Renderer",
|
||||
"GLM5RendererConfig",
|
||||
"GptOssRenderer",
|
||||
"GptOssRendererConfig",
|
||||
"Hy3Renderer",
|
||||
"Hy3RendererConfig",
|
||||
"ImagePart",
|
||||
"KimiK2Renderer",
|
||||
"KimiK25Renderer",
|
||||
"KimiK25RendererConfig",
|
||||
"KimiK2Renderer",
|
||||
"KimiK2RendererConfig",
|
||||
"LagunaXS2Renderer",
|
||||
"LagunaXS2RendererConfig",
|
||||
"LagunaXS21Renderer",
|
||||
"LagunaXS21RendererConfig",
|
||||
"Llama3Renderer",
|
||||
"Llama3RendererConfig",
|
||||
"MULTIMODAL_MODELS",
|
||||
"Message",
|
||||
"MiniMaxM2Renderer",
|
||||
"MiniMaxM2RendererConfig",
|
||||
"MultiModalData",
|
||||
"MultimodalRenderer",
|
||||
"Nemotron3Renderer",
|
||||
"Nemotron3RendererConfig",
|
||||
"Nemotron3UltraRenderer",
|
||||
"Nemotron3UltraRendererConfig",
|
||||
"OverlongPromptError",
|
||||
"ParsedResponse",
|
||||
"ParsedToolCall",
|
||||
"PlaceholderRange",
|
||||
"Qwen3Renderer",
|
||||
"Qwen3VLRenderer",
|
||||
"PrimeQwen3Renderer",
|
||||
"PrimeQwen3RendererConfig",
|
||||
"Qwen35Renderer",
|
||||
"Qwen35RendererConfig",
|
||||
"Qwen36Renderer",
|
||||
"Qwen36RendererConfig",
|
||||
"Qwen3Renderer",
|
||||
"Qwen3RendererConfig",
|
||||
"Qwen3VLRenderer",
|
||||
"Qwen3VLRendererConfig",
|
||||
"RenderedConversation",
|
||||
"RenderedTokens",
|
||||
"RenderedTrainingSample",
|
||||
"Renderer",
|
||||
"RendererConfig",
|
||||
"RendererPool",
|
||||
"TextPart",
|
||||
"ThinkingPart",
|
||||
@@ -88,10 +189,13 @@ __all__ = [
|
||||
"ToolSpec",
|
||||
"VideoPart",
|
||||
"__version__",
|
||||
"attribute_text_segments",
|
||||
"build_training_sample",
|
||||
"build_trajectory_step",
|
||||
"config_from_name",
|
||||
"create_renderer",
|
||||
"create_renderer_pool",
|
||||
"extract_message_tool_names",
|
||||
"is_multimodal",
|
||||
"reject_assistant_in_extension",
|
||||
"trim_to_turn_close",
|
||||
|
||||
+1056
-245
File diff suppressed because it is too large
Load Diff
+177
-68
@@ -12,16 +12,18 @@ achieve real parallelism.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
from openai import AsyncOpenAI, BadRequestError
|
||||
import httpx
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from renderers.base import (
|
||||
Message,
|
||||
MultiModalData,
|
||||
RenderedTokens,
|
||||
Renderer,
|
||||
RendererPool,
|
||||
ToolCallParseStatus,
|
||||
@@ -29,6 +31,81 @@ from renderers.base import (
|
||||
)
|
||||
|
||||
_request_logger = logging.getLogger("renderers.client")
|
||||
ROUTED_EXPERTS_DATA_PREFIX = b'"routed_experts":{"data":"'
|
||||
KEPT_TOKENS_IDS_PREFIX = b'"kept_tokens":{"ids":"'
|
||||
|
||||
|
||||
class OverlongPromptError(Exception):
|
||||
"""The rendered prompt exceeds the engine's context window.
|
||||
|
||||
Raised by :func:`generate` when the rendered token sequence is strictly
|
||||
longer than the resolved cap — either an explicit ``max_prompt_len`` the
|
||||
caller passed in, or the engine's ``max_model_len`` discovered via
|
||||
``GET /v1/models``. Caught client-side before the engine ever sees the
|
||||
request, so callers route the failure to a deterministic policy (skip /
|
||||
truncate / count) instead of round-tripping through an engine 4xx.
|
||||
|
||||
Named after the corresponding ``verifiers.errors.OverlongPromptError``;
|
||||
the two are distinct classes (different package hierarchies) but the
|
||||
concept is the same and downstream clients translate one to the other.
|
||||
"""
|
||||
|
||||
def __init__(self, *, prompt_len: int, max_prompt_len: int) -> None:
|
||||
self.prompt_len = prompt_len
|
||||
self.max_prompt_len = max_prompt_len
|
||||
super().__init__(
|
||||
f"Prompt length ({prompt_len}) exceeds maximum "
|
||||
f"context length ({max_prompt_len})."
|
||||
)
|
||||
|
||||
|
||||
# Per-process cache of resolved engine context-length caps, keyed by
|
||||
# ``(base_url, model)``. ``None`` is the "we asked the engine and it didn't
|
||||
# tell us" sentinel — distinct from "key missing" (haven't asked yet). The
|
||||
# lock serializes the first lookup per key; cache hits avoid the lock.
|
||||
_max_prompt_len_cache: dict[tuple[str, str], int | None] = {}
|
||||
_max_prompt_len_lock = asyncio.Lock()
|
||||
|
||||
|
||||
async def _resolve_max_prompt_len(client: AsyncOpenAI, model: str) -> int | None:
|
||||
"""Discover ``max_model_len`` from the engine via ``GET /v1/models``.
|
||||
|
||||
OpenAI-API-compatible engines expose model metadata at this endpoint;
|
||||
vLLM extends its ``ModelCard`` with a ``max_model_len`` field. Engines
|
||||
that don't (SGLang as of this writing, third-party gateways, etc.) get
|
||||
a cached ``None`` and the pre-flight overflow check silently disables —
|
||||
callers fall back to whatever reactive handling they have for engine
|
||||
4xx, which the verifiers ``@handle_openai_overlong_prompt`` decorator
|
||||
already supplies for the prime-rl path.
|
||||
|
||||
Any exception during lookup (network error, non-JSON body, attribute
|
||||
miss on a mock client in tests) is treated as "unknown cap": cached
|
||||
``None`` so we don't retry on every call.
|
||||
"""
|
||||
key = (str(getattr(client, "base_url", "")), model)
|
||||
if key in _max_prompt_len_cache:
|
||||
return _max_prompt_len_cache[key]
|
||||
async with _max_prompt_len_lock:
|
||||
if key in _max_prompt_len_cache:
|
||||
return _max_prompt_len_cache[key]
|
||||
try:
|
||||
payload = await client.get("/models", cast_to=cast(Any, dict[str, Any]))
|
||||
except Exception as exc:
|
||||
_request_logger.debug("max_prompt_len lookup failed: %s", exc)
|
||||
_max_prompt_len_cache[key] = None
|
||||
return None
|
||||
value: int | None = None
|
||||
for card in payload.get("data") or []:
|
||||
if not isinstance(card, Mapping):
|
||||
continue
|
||||
if card.get("id") != model:
|
||||
continue
|
||||
raw = card.get("max_model_len")
|
||||
if isinstance(raw, int) and raw > 0:
|
||||
value = raw
|
||||
break
|
||||
_max_prompt_len_cache[key] = value
|
||||
return value
|
||||
|
||||
|
||||
async def _maybe_offload(renderer: Renderer | RendererPool, fn):
|
||||
@@ -45,6 +122,34 @@ async def _maybe_offload(renderer: Renderer | RendererPool, fn):
|
||||
return fn()
|
||||
|
||||
|
||||
def _strip_base64_field(raw: bytes, prefix: bytes) -> tuple[bytes, memoryview | None]:
|
||||
"""Splice a large base64 string field out of raw JSON bytes.
|
||||
|
||||
Avoids json-decoding megabytes of base64; the returned memoryview
|
||||
references ``raw`` and is re-inserted into the parsed payload.
|
||||
"""
|
||||
data_start = raw.find(prefix)
|
||||
if data_start < 0:
|
||||
return raw, None
|
||||
|
||||
data_start += len(prefix)
|
||||
data_end = raw.index(b'"', data_start)
|
||||
data = memoryview(raw)[data_start:data_end]
|
||||
stripped = raw[:data_start] + raw[data_end:]
|
||||
return stripped, data
|
||||
|
||||
|
||||
def parse_generate_response(raw: bytes) -> dict[str, Any]:
|
||||
stripped, routed_data = _strip_base64_field(raw, ROUTED_EXPERTS_DATA_PREFIX)
|
||||
stripped, kept_ids_data = _strip_base64_field(stripped, KEPT_TOKENS_IDS_PREFIX)
|
||||
payload: dict[str, Any] = json.loads(stripped)
|
||||
if routed_data is not None:
|
||||
payload["choices"][0]["routed_experts"]["data"] = routed_data
|
||||
if kept_ids_data is not None:
|
||||
payload["choices"][0]["kept_tokens"]["ids"] = kept_ids_data
|
||||
return payload
|
||||
|
||||
|
||||
async def generate(
|
||||
*,
|
||||
client: AsyncOpenAI,
|
||||
@@ -53,11 +158,13 @@ async def generate(
|
||||
model: str,
|
||||
prompt_ids: list[int] | None = None,
|
||||
multi_modal_data: MultiModalData | None = None,
|
||||
prompt_attribution: RenderedTokens | None = None,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
sampling_params: dict[str, Any] | None = None,
|
||||
cache_salt: str | None = None,
|
||||
priority: int | None = None,
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
max_prompt_len: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Tokenize messages, call vLLM /inference/v1/generate, parse the response.
|
||||
|
||||
@@ -66,7 +173,11 @@ async def generate(
|
||||
renderer) and ``logprobs=1`` (we always emit completion_logprobs). Pass
|
||||
``prompt_ids`` to skip rendering and use a prebuilt token sequence —
|
||||
pair it with ``multi_modal_data`` when the prebuilt prompt has image /
|
||||
video placeholders that need engine-side mm payload.
|
||||
video placeholders that need engine-side mm payload, and with
|
||||
``prompt_attribution`` (a :class:`RenderedTokens` whose ``token_ids``
|
||||
match the passed-in ``prompt_ids``) to carry the renderer's per-token
|
||||
attribution (``is_content`` / ``sampled_mask`` / ``message_indices`` /
|
||||
``message_roles``) into the result without re-rendering.
|
||||
|
||||
For multimodal renderers (e.g. ``Qwen3VLRenderer``), the call goes
|
||||
through ``renderer.render(...)`` to recover the ``multi_modal_data``
|
||||
@@ -74,9 +185,31 @@ async def generate(
|
||||
mm_placeholders, kwargs_data) before POSTing. The serializer imports
|
||||
``vllm.*`` lazily so text-only consumers never pay for the import.
|
||||
|
||||
``max_prompt_len`` controls the pre-flight overflow check. When the
|
||||
rendered prompt is strictly longer than the cap, the request is never
|
||||
sent and ``OverlongPromptError`` is raised. If ``max_prompt_len`` is
|
||||
``None`` (the default), the cap is auto-discovered once per
|
||||
``(base_url, model)`` via ``GET /v1/models`` (vLLM's
|
||||
``ModelCard.max_model_len`` extension); engines that don't expose it
|
||||
cache a ``None`` cap and the pre-flight silently disables. Engine 4xx
|
||||
that still slip through propagate raw — converting them into a domain
|
||||
error is the calling client's job (its error shape is engine-specific).
|
||||
|
||||
Returns a dict with: request_id, prompt_ids, completion_ids,
|
||||
completion_logprobs, content, reasoning_content, tool_calls,
|
||||
finish_reason, routed_experts.
|
||||
finish_reason, routed_experts, multi_modal_data, prompt_attribution.
|
||||
|
||||
``prompt_attribution`` is the renderer's :class:`RenderedTokens` for
|
||||
the prompt — either the one this call computed via
|
||||
``renderer.render(...)`` or the one the caller threaded in alongside
|
||||
``prompt_ids``. Carries ``token_ids``, ``message_indices``,
|
||||
``sampled_mask``, ``is_content``, ``message_roles``, and
|
||||
``multi_modal_data``, so downstream consumers (verifiers
|
||||
``RendererClient`` → prime-rl) can build per-token loss masks
|
||||
(``content_mask_for_roles({"tool"})`` for SFT-on-tool-body,
|
||||
``sampled_mask`` for RL trainable spans) without a second render
|
||||
pass. ``None`` when the caller passed pre-built ``prompt_ids``
|
||||
without attribution.
|
||||
"""
|
||||
if tools and not getattr(renderer, "supports_tools", True):
|
||||
raise ValueError(
|
||||
@@ -86,15 +219,33 @@ async def generate(
|
||||
|
||||
def _prepare():
|
||||
if prompt_ids is not None:
|
||||
return list(prompt_ids), renderer.get_stop_token_ids(), multi_modal_data
|
||||
# Caller-supplied prompt; if they also gave us pre-computed
|
||||
# attribution (e.g. the bridge path in verifiers), thread it
|
||||
# through unchanged.
|
||||
return (
|
||||
list(prompt_ids),
|
||||
renderer.get_stop_token_ids(),
|
||||
multi_modal_data,
|
||||
prompt_attribution,
|
||||
)
|
||||
rendered = renderer.render(messages, tools=tools, add_generation_prompt=True)
|
||||
return (
|
||||
rendered.token_ids,
|
||||
renderer.get_stop_token_ids(),
|
||||
rendered.multi_modal_data,
|
||||
rendered,
|
||||
)
|
||||
|
||||
prompt_ids, stop_token_ids, mm_data = await _maybe_offload(renderer, _prepare)
|
||||
prompt_ids, stop_token_ids, mm_data, prompt_attr = await _maybe_offload(
|
||||
renderer, _prepare
|
||||
)
|
||||
|
||||
if max_prompt_len is None:
|
||||
max_prompt_len = await _resolve_max_prompt_len(client, model)
|
||||
if max_prompt_len is not None and len(prompt_ids) > max_prompt_len:
|
||||
raise OverlongPromptError(
|
||||
prompt_len=len(prompt_ids), max_prompt_len=max_prompt_len
|
||||
)
|
||||
|
||||
sp: dict[str, Any] = dict(sampling_params or {})
|
||||
sp["stop_token_ids"] = stop_token_ids
|
||||
@@ -130,21 +281,13 @@ async def generate(
|
||||
sp.get("max_tokens"),
|
||||
)
|
||||
post_kwargs: dict[str, Any] = {
|
||||
"cast_to": cast(Any, dict[str, Any]),
|
||||
"cast_to": httpx.Response,
|
||||
"body": body,
|
||||
}
|
||||
if extra_headers:
|
||||
post_kwargs["options"] = cast(Any, {"headers": extra_headers})
|
||||
try:
|
||||
data = await client.post(endpoint, **post_kwargs)
|
||||
except BadRequestError as exc:
|
||||
_log_overlong_prompt_diagnostic(
|
||||
prompt_ids=prompt_ids,
|
||||
messages=messages,
|
||||
max_tokens=sp.get("max_tokens"),
|
||||
exc=exc,
|
||||
)
|
||||
raise
|
||||
raw_response = await client.post(endpoint, **post_kwargs)
|
||||
data = parse_generate_response(raw_response.content)
|
||||
|
||||
choice = (data.get("choices") or [{}])[0]
|
||||
completion_ids = choice.get("token_ids") or []
|
||||
@@ -158,14 +301,8 @@ async def generate(
|
||||
content_lp = raw_logprobs.get("content") if isinstance(raw_logprobs, dict) else None
|
||||
completion_logprobs = [float(c.get("logprob") or 0.0) for c in content_lp or []]
|
||||
|
||||
routed_experts = None
|
||||
raw_re = choice.get("routed_experts")
|
||||
if isinstance(raw_re, dict) and "data" in raw_re and "shape" in raw_re:
|
||||
routed_experts = (
|
||||
np.frombuffer(base64.b85decode(raw_re["data"]), dtype=np.int32)
|
||||
.reshape(raw_re["shape"])
|
||||
.tolist()
|
||||
)
|
||||
routed_experts = choice.get("routed_experts")
|
||||
kept_tokens = choice.get("kept_tokens")
|
||||
|
||||
# /inference/v1/generate returns finish_reason in {"stop","length",...} —
|
||||
# never "tool_calls" (a chat-completions concept). Promote stop→tool_calls
|
||||
@@ -192,10 +329,19 @@ async def generate(
|
||||
"tool_calls": parsed.tool_calls,
|
||||
"finish_reason": finish_reason,
|
||||
"routed_experts": routed_experts,
|
||||
"kept_tokens": kept_tokens,
|
||||
# The mm sidecar consumed on the request side, surfaced back so
|
||||
# callers can persist it on the trajectory step for downstream
|
||||
# multi-turn bridging and training-sample construction.
|
||||
"multi_modal_data": mm_data,
|
||||
# The renderer's per-token attribution for the prompt — either
|
||||
# the RenderedTokens computed here via renderer.render(...) or
|
||||
# the one threaded in by the caller alongside prompt_ids (the
|
||||
# bridge path). Lets downstream consumers (verifiers
|
||||
# RendererClient → prime-rl) build SFT-on-tool-body and other
|
||||
# selective loss masks without a second render pass. ``None``
|
||||
# when the caller passed prompt_ids without attribution.
|
||||
"prompt_attribution": prompt_attr,
|
||||
}
|
||||
|
||||
|
||||
@@ -225,6 +371,7 @@ def _build_mm_features(
|
||||
to change. Don't pre-build the abstraction with one engine in tree.
|
||||
"""
|
||||
from renderers.qwen3_vl import Qwen3VLRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
|
||||
# Type dispatch only needs the renderer class. Pools expose
|
||||
# ``renderer_cls`` as a snapshot attribute, so we don't have to check
|
||||
@@ -233,7 +380,10 @@ def _build_mm_features(
|
||||
renderer.renderer_cls if isinstance(renderer, RendererPool) else type(renderer)
|
||||
)
|
||||
|
||||
if issubclass(renderer_cls, Qwen3VLRenderer):
|
||||
# Qwen3-VL and Qwen3.5 both ship ``pixel_values`` + ``image_grid_thw``
|
||||
# via the shared Qwen2-VL field factory. ``spatial_merge_size=2`` is
|
||||
# the family default and matches every Qwen-VL processor in tree.
|
||||
if issubclass(renderer_cls, (Qwen3VLRenderer, Qwen35Renderer)):
|
||||
return _build_qwen_vl_features(mm_data, spatial_merge_size=2)
|
||||
|
||||
raise NotImplementedError(
|
||||
@@ -305,44 +455,3 @@ def _build_qwen_vl_features(
|
||||
out["kwargs_data"] = None
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def _log_overlong_prompt_diagnostic(
|
||||
*,
|
||||
prompt_ids: list[int],
|
||||
messages: list[Message],
|
||||
max_tokens: int | None,
|
||||
exc: BadRequestError,
|
||||
) -> None:
|
||||
"""Log a structured snapshot when vLLM rejects with 4xx — usually overlong.
|
||||
|
||||
Captures total prompt length, per-message role + character count, and
|
||||
the first chunk of the response body.
|
||||
"""
|
||||
body_text = ""
|
||||
response = getattr(exc, "response", None)
|
||||
if response is not None:
|
||||
body_text = (response.text or "")[:500].replace("\n", " ")
|
||||
msg_summary = []
|
||||
for i, m in enumerate(messages):
|
||||
role = m.get("role", "?")
|
||||
content = m.get("content")
|
||||
if isinstance(content, str):
|
||||
content_len = len(content)
|
||||
elif isinstance(content, list):
|
||||
content_len = sum(
|
||||
len(p.get("text", "")) if isinstance(p, dict) else 0 for p in content
|
||||
)
|
||||
else:
|
||||
content_len = 0
|
||||
tool_calls = m.get("tool_calls")
|
||||
tc_count = len(tool_calls) if tool_calls else 0
|
||||
msg_summary.append(f"[{i}]{role}(c={content_len},tc={tc_count})")
|
||||
_request_logger.warning(
|
||||
"vllm 4xx prompt_len=%d messages=%d max_tokens=%s per_msg=%s response_body=%s",
|
||||
len(prompt_ids),
|
||||
len(messages),
|
||||
max_tokens,
|
||||
" ".join(msg_summary),
|
||||
body_text,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,772 @@
|
||||
"""Typed renderer configs — one pydantic model per renderer, unified by a
|
||||
discriminated union (``RendererConfig``).
|
||||
|
||||
Each renderer accepts its own typed config; bad combinations (e.g.
|
||||
``add_vision_id`` under ``name="qwen3"``) fail at config-load time with a
|
||||
pydantic ``ValidationError`` rather than at runtime via an allowlist
|
||||
check. The shared ``thinking_retention`` flag is optional: ``None`` means
|
||||
"derive bridge policy from this renderer's chat-template knobs"; an
|
||||
explicit value is a bridge-policy override.
|
||||
|
||||
``AutoRendererConfig`` is a placeholder variant: ``create_renderer``
|
||||
resolves it via ``MODEL_RENDERER_MAP`` and constructs the matching
|
||||
typed config with the auto config's ``thinking_retention`` field carried
|
||||
over when one was explicitly supplied.
|
||||
|
||||
``DefaultRendererConfig`` uses ``extra="allow"`` to accept arbitrary
|
||||
Jinja kwargs as ``model_extra`` — ``DefaultRenderer`` doesn't know which
|
||||
keys its tokenizer's template will honour, so it can't enumerate them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated, ClassVar, Literal, Union
|
||||
|
||||
from pydantic import ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
|
||||
def _reject_thinking_retention_conflict(
|
||||
config: BaseConfig,
|
||||
kwarg_name: str,
|
||||
*,
|
||||
true_implies: "ResolvedThinkingRetention",
|
||||
false_implies: "ResolvedThinkingRetention",
|
||||
) -> None:
|
||||
"""Raise if explicit template and renderer retention knobs disagree."""
|
||||
fields_set = config.__pydantic_fields_set__
|
||||
requested = getattr(config, "thinking_retention", None)
|
||||
if kwarg_name in fields_set and requested is not None:
|
||||
implied = (
|
||||
false_implies if getattr(config, kwarg_name) is False else true_implies
|
||||
)
|
||||
if requested == implied:
|
||||
return
|
||||
raise ValueError(
|
||||
f"{kwarg_name}={getattr(config, kwarg_name)!r} implies "
|
||||
f"thinking_retention={implied!r}, which conflicts with explicit "
|
||||
f"thinking_retention={requested!r}."
|
||||
)
|
||||
|
||||
|
||||
ThinkingRetention = Literal["tool_cycle", "all"]
|
||||
"""User-facing historical thinking/analysis retention override."""
|
||||
|
||||
ResolvedThinkingRetention = Literal["template", "tool_cycle", "all"]
|
||||
"""Internal bridge policy after template kwargs have been resolved."""
|
||||
|
||||
|
||||
class BaseRendererConfig(BaseConfig):
|
||||
"""Shared fields and config for every renderer config variant.
|
||||
|
||||
Inherits from ``pydantic_config.BaseConfig`` so the typed-config
|
||||
surface stays uniform with prime-rl / verifiers config bases. The
|
||||
BaseConfig contract includes ``extra="forbid"`` (preserved here);
|
||||
this class adds ``frozen=True`` so configs are hashable value
|
||||
objects.
|
||||
|
||||
``thinking_retention`` is an optional renderer-level retention override.
|
||||
Leave it ``None`` to derive the effective policy from the renderer's own
|
||||
chat-template knobs. Set it explicitly to request retention beyond the
|
||||
template default; renderers fail loudly when an explicit template knob says
|
||||
the opposite thing.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
thinking_retention: ThinkingRetention | None = None
|
||||
"""Explicit retention override, or ``None`` to derive from template knobs:
|
||||
|
||||
- ``None`` — derive the effective bridge policy from this renderer's
|
||||
chat-template knobs while keeping full renders template-faithful.
|
||||
- ``"tool_cycle"`` — bridge within the current tool cycle; re-render when
|
||||
a new user query arrives.
|
||||
- ``"all"`` — allow bridges across user-query boundaries.
|
||||
|
||||
This does not change full ``render()`` output; full renders stay faithful
|
||||
to the Python chat-template implementation and its explicit template
|
||||
kwargs."""
|
||||
|
||||
# Fields that are renderer-internal — not forwarded to (or mirrored
|
||||
# by) ``apply_chat_template``. Override in subclasses that hold
|
||||
# non-template config (e.g. ``image_cache_max``, GptOss's
|
||||
# ``use_system_prompt`` / ``knowledge_cutoff`` / ``model_identity``,
|
||||
# or fields that exist as renderer conventions without a Jinja
|
||||
# analogue like DeepSeek V3 / Kimi K2 ``enable_thinking``).
|
||||
#
|
||||
# Used by parity tests to compute the field subset that, when
|
||||
# changed, must produce token streams matching
|
||||
# ``apply_chat_template`` — see :meth:`template_field_names`. The
|
||||
# renderer is the only end-to-end consumer of these fields, so this
|
||||
# is a renderer-side bookkeeping concern rather than a public API.
|
||||
_internal_fields: ClassVar[frozenset[str]] = frozenset()
|
||||
|
||||
@classmethod
|
||||
def template_field_names(cls) -> frozenset[str]:
|
||||
"""Subset of fields that mirror Jinja chat-template kwargs.
|
||||
|
||||
Default: every non-base field except ``name`` and any field
|
||||
listed in ``_internal_fields``. Used by the parity test matrix
|
||||
(``tests/test_renderer_config_parity.py``) to discover the
|
||||
cells that must agree with ``apply_chat_template``.
|
||||
"""
|
||||
base = frozenset(BaseRendererConfig.model_fields)
|
||||
return frozenset(cls.model_fields) - base - {"name"} - cls._internal_fields
|
||||
|
||||
|
||||
class AutoRendererConfig(BaseRendererConfig):
|
||||
"""Resolve the renderer from ``tokenizer.name_or_path`` at construction
|
||||
time via ``MODEL_RENDERER_MAP``. Carries only the shared
|
||||
``thinking_retention`` field when explicitly set; template kwargs require
|
||||
an explicit renderer choice so template-dependent behaviour stays visible
|
||||
at the call site."""
|
||||
|
||||
name: Literal["auto"] = "auto"
|
||||
|
||||
|
||||
class DefaultRendererConfig(BaseRendererConfig):
|
||||
"""Config for ``DefaultRenderer`` — the fallback wrapping
|
||||
``tokenizer.apply_chat_template``. Accepts arbitrary extra fields
|
||||
via ``extra="allow"`` because the underlying Jinja template's kwargs
|
||||
are unknown to us. ``DefaultRenderer`` forwards ``model_extra`` to
|
||||
``apply_chat_template`` verbatim.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True, extra="allow")
|
||||
|
||||
name: Literal["default"] = "default"
|
||||
|
||||
tool_parser: str | None = None
|
||||
"""Name of a tool parser registered in ``renderers.parsers`` (e.g.
|
||||
``"qwen3"``, ``"glm"``). Consumed only by ``DefaultRenderer``."""
|
||||
|
||||
reasoning_parser: str | None = None
|
||||
"""Name of a reasoning parser registered in ``renderers.parsers``
|
||||
(e.g. ``"think"``). Consumed only by ``DefaultRenderer``."""
|
||||
|
||||
# tool_parser / reasoning_parser are renderer-internal — they configure
|
||||
# DefaultRenderer's parsing pipeline, not the underlying Jinja
|
||||
# template. Jinja kwargs live in ``model_extra`` (extra="allow").
|
||||
_internal_fields = frozenset({"tool_parser", "reasoning_parser"})
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _reject_legacy_preserve_flags(self):
|
||||
# ``extra="allow"`` would otherwise swallow the removed ``preserve_*``
|
||||
# bools into ``model_extra`` and forward them to apply_chat_template,
|
||||
# silently dropping the user's intent (DefaultRenderer can't
|
||||
# selectively re-emit reasoning_content). Reject them like every other
|
||||
# config's ``extra="forbid"`` does, pointing at the replacement.
|
||||
legacy = {
|
||||
"preserve_all_thinking",
|
||||
"preserve_thinking_between_tool_calls",
|
||||
} & set(self.model_extra or {})
|
||||
if legacy:
|
||||
raise ValueError(
|
||||
f"{sorted(legacy)} were replaced by thinking_retention. "
|
||||
"DefaultRenderer falls back to apply_chat_template and can't "
|
||||
"selectively re-emit reasoning_content — use thinking_retention "
|
||||
"on a model-specific renderer."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class Qwen3RendererConfig(BaseRendererConfig):
|
||||
"""Qwen3 (text-only) renderer config."""
|
||||
|
||||
name: Literal["qwen3"] = "qwen3"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""When ``True``, the generation prompt includes ``<think>`` so the
|
||||
model continues into a thinking block. Mirrors the chat template's
|
||||
``enable_thinking`` kwarg."""
|
||||
|
||||
|
||||
class PrimeQwen3RendererConfig(BaseRendererConfig):
|
||||
"""PrimeIntellect Qwen3 renderer config."""
|
||||
|
||||
name: Literal["prime-qwen3"] = "prime-qwen3"
|
||||
|
||||
|
||||
class Qwen35RendererConfig(BaseRendererConfig):
|
||||
"""Qwen3.5 renderer config."""
|
||||
|
||||
name: Literal["qwen3.5"] = "qwen3.5"
|
||||
|
||||
enable_thinking: bool | None = None
|
||||
"""When ``True``, the generation prompt includes ``<think>``. ``None``
|
||||
auto-detects from the tokenizer's chat-template default — Instruct
|
||||
checkpoints default off, Thinking checkpoints default on. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
add_vision_id: bool = False
|
||||
"""When ``True``, prefix each ``<|vision_start|>`` placeholder with
|
||||
``"Picture N: "`` / ``"Video N: "`` where N is a 1-indexed counter
|
||||
running across the entire conversation. Mirrors the chat template's
|
||||
``add_vision_id`` toggle."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""FIFO bound on the per-renderer image processor cache. Renderer-
|
||||
internal — not a Jinja chat-template kwarg."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
|
||||
class Qwen36RendererConfig(BaseRendererConfig):
|
||||
"""Qwen3.6 renderer config. Inherits Qwen3.5's template surface."""
|
||||
|
||||
name: Literal["qwen3.6"] = "qwen3.6"
|
||||
|
||||
enable_thinking: bool | None = None
|
||||
"""See :class:`Qwen35RendererConfig.enable_thinking`."""
|
||||
|
||||
add_vision_id: bool = False
|
||||
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
|
||||
|
||||
preserve_thinking: bool = False
|
||||
"""When ``True``, keep historical ``<think>`` blocks even before the
|
||||
last real user query. Mirrors the Qwen3.6 chat template's native
|
||||
``preserve_thinking`` kwarg."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"preserve_thinking",
|
||||
true_implies="all",
|
||||
false_implies="tool_cycle",
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class Qwen3VLRendererConfig(BaseRendererConfig):
|
||||
"""Qwen3-VL renderer config."""
|
||||
|
||||
name: Literal["qwen3-vl"] = "qwen3-vl"
|
||||
|
||||
add_vision_id: bool = False
|
||||
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
|
||||
class GLM5RendererConfig(BaseRendererConfig):
|
||||
"""GLM-5 renderer config."""
|
||||
|
||||
name: Literal["glm-5"] = "glm-5"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
clear_thinking: bool = True
|
||||
"""When ``False``, the renderer keeps ``<think>{reasoning}</think>``
|
||||
on past-cycle assistant turns instead of dropping them. Mirrors the
|
||||
chat template's ``clear_thinking`` toggle and resolves bridge policy
|
||||
to ``"all"``."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"clear_thinking",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class GLM51RendererConfig(BaseRendererConfig):
|
||||
"""GLM-5.1 renderer config — same template surface as GLM-5, distinct
|
||||
discriminator so the registry can route to ``GLM51Renderer``."""
|
||||
|
||||
name: Literal["glm-5.1"] = "glm-5.1"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""See :class:`GLM5RendererConfig.enable_thinking`."""
|
||||
|
||||
clear_thinking: bool = True
|
||||
"""See :class:`GLM5RendererConfig.clear_thinking`."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"clear_thinking",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class GLM45RendererConfig(BaseRendererConfig):
|
||||
"""GLM-4.5 Air renderer config."""
|
||||
|
||||
name: Literal["glm-4.5"] = "glm-4.5"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
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.
|
||||
|
||||
Several fields here are renderer-internal: ``use_system_prompt``,
|
||||
``knowledge_cutoff``, and ``model_identity`` control how the renderer
|
||||
builds the harmony ``SystemContent`` preamble and don't have direct
|
||||
Jinja-kwarg analogues. They're typed config rather than Jinja kwargs
|
||||
because users still want to set them — the distinction only matters
|
||||
for downstream tooling that synthesises a Jinja-kwargs view (none
|
||||
today, since vLLM is invoked via the token-in endpoint).
|
||||
"""
|
||||
|
||||
name: Literal["gpt-oss"] = "gpt-oss"
|
||||
|
||||
reasoning_effort: Literal["low", "medium", "high"] = "medium"
|
||||
"""Harmony reasoning-effort tag. Mirrors the ``apply_chat_template``
|
||||
``reasoning_effort`` kwarg."""
|
||||
|
||||
conversation_start_date: str | None = None
|
||||
"""ISO date string for the harmony preamble. ``None`` defers to
|
||||
today's date at render time."""
|
||||
|
||||
use_system_prompt: bool = True
|
||||
"""Prepend the canonical harmony ``SystemContent`` preamble. Matches
|
||||
HF's ``apply_chat_template`` behaviour."""
|
||||
|
||||
knowledge_cutoff: str | None = None
|
||||
"""Override the model's knowledge-cutoff string in the preamble.
|
||||
``None`` uses harmony's built-in default."""
|
||||
|
||||
model_identity: str | None = None
|
||||
"""Override the model-identity line in the preamble. ``None`` uses
|
||||
harmony's built-in default."""
|
||||
|
||||
auto_drop_analysis: bool = True
|
||||
"""Harmony ``RenderConversationConfig.auto_drop_analysis`` behaviour.
|
||||
``True`` keeps live tool-cycle analysis but drops stale analysis from
|
||||
history; ``False`` keeps analysis in all history."""
|
||||
|
||||
_internal_fields = frozenset(
|
||||
{
|
||||
"use_system_prompt",
|
||||
"knowledge_cutoff",
|
||||
"model_identity",
|
||||
"auto_drop_analysis",
|
||||
}
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"auto_drop_analysis",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class KimiK2RendererConfig(BaseRendererConfig):
|
||||
"""Kimi K2 renderer config.
|
||||
|
||||
``enable_thinking`` is renderer-internal here — Kimi K2's chat
|
||||
template doesn't reference any thinking variable, so it's a no-op
|
||||
against ``apply_chat_template`` parity. The field is kept for
|
||||
protocol uniformity with the rest of the renderer family.
|
||||
"""
|
||||
|
||||
name: Literal["kimi-k2"] = "kimi-k2"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""No-op for Kimi K2 (template doesn't gate on it). Stored for
|
||||
introspection / cross-renderer uniformity."""
|
||||
|
||||
_internal_fields = frozenset({"enable_thinking"})
|
||||
|
||||
|
||||
class KimiK25RendererConfig(BaseRendererConfig):
|
||||
"""Kimi K2.5 renderer config."""
|
||||
|
||||
name: Literal["kimi-k2.5"] = "kimi-k2.5"
|
||||
|
||||
thinking: bool = True
|
||||
"""When ``True``, the generation prompt prefills ``<think>``; when
|
||||
``False`` it prefills ``<think></think>``. The kwarg is named
|
||||
``thinking`` (not ``enable_thinking``) to match the upstream chat
|
||||
template's native variable name."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
|
||||
class LagunaXS2RendererConfig(BaseRendererConfig):
|
||||
"""Laguna XS.2 renderer config."""
|
||||
|
||||
name: Literal["laguna-xs.2"] = "laguna-xs.2"
|
||||
|
||||
enable_thinking: bool = False
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg. Default ``False``
|
||||
matches the upstream Jinja default for Laguna XS.2."""
|
||||
|
||||
render_assistant_messages_raw: bool = False
|
||||
"""When ``True``, assistant messages render as a passthrough: the
|
||||
content bytes are emitted verbatim (no reasoning extraction, no
|
||||
tool-call XML synthesis), and the ``<think>``/``</think>`` prefix
|
||||
and ``</assistant>`` suffix are only added when missing. Mirrors the
|
||||
chat template's ``render_assistant_messages_raw`` gate."""
|
||||
|
||||
|
||||
class LagunaXS21RendererConfig(BaseRendererConfig):
|
||||
"""Laguna XS-2.1 renderer config.
|
||||
|
||||
XS-2.1's chat template reads a single kwarg, ``enable_thinking``,
|
||||
which gates both the generation prompt (``<think>`` vs ``</think>``)
|
||||
and whether assistant reasoning is rendered into the history at all.
|
||||
Served by :class:`renderers.laguna_xs2.LagunaXS21Renderer`.
|
||||
"""
|
||||
|
||||
name: Literal["laguna-xs-2.1"] = "laguna-xs-2.1"
|
||||
|
||||
enable_thinking: bool = False
|
||||
"""When ``True``, the generation prompt ends with ``<think>`` and
|
||||
every assistant turn renders ``<think>{reasoning}</think>``; when
|
||||
``False``, turns open with a bare ``</think>`` and reasoning is not
|
||||
rendered. Mirrors the template's ``enable_thinking`` kwarg and its
|
||||
upstream default."""
|
||||
|
||||
|
||||
class Llama3RendererConfig(BaseRendererConfig):
|
||||
"""Llama-3.x Instruct renderer config.
|
||||
|
||||
Llama-3 ships no reasoning channel, so the base ``thinking_retention``
|
||||
flag is a no-op: there's never any past-assistant thinking to retain
|
||||
or drop, so any level leaves the token stream unchanged (same contract
|
||||
as Kimi-K2 / Qwen3-VL). Both fields below mirror real
|
||||
``apply_chat_template``
|
||||
kwargs.
|
||||
"""
|
||||
|
||||
name: Literal["llama-3"] = "llama-3"
|
||||
|
||||
date_string: str = "26 Jul 2024"
|
||||
"""``Today Date`` value injected into the system preamble. Pinned to
|
||||
the chat template's ``strftime`` fallback by default so output stays
|
||||
deterministic; override per instance for production runs that want
|
||||
today's date. Mirrors the chat template's ``date_string`` kwarg."""
|
||||
|
||||
tools_in_user_message: bool = True
|
||||
"""When ``True`` (default), tool descriptions + JSON signatures inject
|
||||
into the first user message; ``False`` routes them into the system
|
||||
block instead. Mirrors the chat template's ``tools_in_user_message``
|
||||
kwarg."""
|
||||
|
||||
|
||||
class MiniMaxM2RendererConfig(BaseRendererConfig):
|
||||
"""MiniMax M2 / M2.5 renderer config."""
|
||||
|
||||
name: Literal["minimax-m2"] = "minimax-m2"
|
||||
|
||||
model_identity: str = "You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax."
|
||||
"""Fallback persona used when no system message is supplied. Mirrors
|
||||
the chat template's ``model_identity`` Jinja variable."""
|
||||
|
||||
|
||||
class Nemotron3RendererConfig(BaseRendererConfig):
|
||||
"""Nemotron-3 **Nano / Super** renderer config.
|
||||
|
||||
Nano and Super share one chat-template variant; the renderer routes both
|
||||
through :class:`renderers.nemotron3.Nemotron3Renderer`. The Ultra variant
|
||||
has its own template (different reasoning-block glue) and config —
|
||||
:class:`Nemotron3UltraRendererConfig` — and is reached via the
|
||||
``nemotron-3-ultra`` discriminator.
|
||||
"""
|
||||
|
||||
name: Literal["nemotron-3"] = "nemotron-3"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
truncate_history_thinking: bool = True
|
||||
"""When ``False``, keep ``<think>{reasoning}</think>`` on past-cycle
|
||||
assistant turns instead of dropping them. Mirrors the chat
|
||||
template's ``truncate_history_thinking`` toggle and resolves bridge
|
||||
policy to ``"all"``."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"truncate_history_thinking",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
low_effort: bool = False
|
||||
"""When ``True``, append ``\\n\\n{reasoning effort: low}`` to the last user
|
||||
message, nudging the model toward shorter reasoning. Mirrors the **Super**
|
||||
chat template's ``low_effort`` kwarg. A no-op on **Nano** (its template
|
||||
doesn't define it) — exactly as ``apply_chat_template`` ignores an undefined
|
||||
template variable; the renderer distinguishes the two by model name (see
|
||||
``renderers.nemotron3._is_super``)."""
|
||||
|
||||
|
||||
class Nemotron3UltraRendererConfig(BaseRendererConfig):
|
||||
"""Nemotron-3 **Ultra** renderer config — distinct discriminator so the
|
||||
registry routes Ultra checkpoints to the Ultra template variant.
|
||||
|
||||
Ultra's template differs from Nano/Super: the reasoning block is glued as
|
||||
``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around ``</think>``)
|
||||
and truncated historical turns collapse to ``<think></think>{content}``
|
||||
(no ``\\n``). It shares the :class:`renderers.nemotron3.Nemotron3Renderer`
|
||||
implementation, which selects the variant from ``config.name``.
|
||||
"""
|
||||
|
||||
name: Literal["nemotron-3-ultra"] = "nemotron-3-ultra"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""See :class:`Nemotron3RendererConfig.enable_thinking`."""
|
||||
|
||||
truncate_history_thinking: bool = True
|
||||
"""See :class:`Nemotron3RendererConfig.truncate_history_thinking`."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"truncate_history_thinking",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
medium_effort: bool = False
|
||||
"""When ``True``, append ``\\n\\n{reasoning effort: efficient}`` to the last
|
||||
user message. Mirrors the Ultra chat template's ``medium_effort`` kwarg."""
|
||||
|
||||
|
||||
class DeepSeekV3RendererConfig(BaseRendererConfig):
|
||||
"""DeepSeek-V3 renderer config (non-reasoning).
|
||||
|
||||
DeepSeek-V3 has no thinking concept: the generation prompt is a bare
|
||||
``<|Assistant|>`` and assistant content is emitted verbatim. For the
|
||||
reasoning variant use :class:`DeepSeekR1RendererConfig`.
|
||||
"""
|
||||
|
||||
name: Literal["deepseek-v3"] = "deepseek-v3"
|
||||
|
||||
|
||||
class DeepSeekR1RendererConfig(BaseRendererConfig):
|
||||
"""DeepSeek-R1 renderer config (reasoning).
|
||||
|
||||
R1 always reasons — its chat template unconditionally prefills
|
||||
``<think>\\n`` at the generation prompt and strips ``</think>`` from
|
||||
historical assistant turns. There is therefore no ``enable_thinking``
|
||||
knob (thinking is not optional). With ``thinking_retention=None`` the
|
||||
resolved bridge policy is ``"template"``; explicit ``"tool_cycle"`` /
|
||||
``"all"`` are bridge-policy overrides. Applies to full
|
||||
``deepseek-ai/DeepSeek-R1`` / ``-R1-0528``
|
||||
— NOT the R1-Distill-Qwen/Llama models, which use those base
|
||||
tokenizers and route to the Qwen3 / Llama-3 renderers.
|
||||
"""
|
||||
|
||||
name: Literal["deepseek-r1"] = "deepseek-r1"
|
||||
|
||||
|
||||
RendererConfig = Annotated[
|
||||
Union[
|
||||
AutoRendererConfig,
|
||||
DefaultRendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
PrimeQwen3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
Qwen36RendererConfig,
|
||||
Qwen3VLRendererConfig,
|
||||
GLM5RendererConfig,
|
||||
GLM51RendererConfig,
|
||||
GLM45RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
Hy3RendererConfig,
|
||||
KimiK2RendererConfig,
|
||||
KimiK25RendererConfig,
|
||||
LagunaXS2RendererConfig,
|
||||
LagunaXS21RendererConfig,
|
||||
Llama3RendererConfig,
|
||||
MiniMaxM2RendererConfig,
|
||||
Nemotron3RendererConfig,
|
||||
Nemotron3UltraRendererConfig,
|
||||
DeepSeekV3RendererConfig,
|
||||
DeepSeekR1RendererConfig,
|
||||
],
|
||||
Field(discriminator="name"),
|
||||
]
|
||||
"""Discriminated union over every renderer config variant.
|
||||
|
||||
Downstream pydantic configs (prime-rl orchestrator, verifiers
|
||||
``ClientConfig``) can hold a single field typed as ``RendererConfig``;
|
||||
deserialization dispatches on ``name`` and exposes strictly the kwargs
|
||||
that renderer supports. Bogus combinations (e.g. ``add_vision_id`` under
|
||||
``name="qwen3"``) raise ``ValidationError`` at config-load time.
|
||||
"""
|
||||
|
||||
|
||||
# Map discriminator → config class. Used by ``create_renderer`` when
|
||||
# resolving ``AutoRendererConfig`` against ``MODEL_RENDERER_MAP``: the
|
||||
# resolved renderer name picks the corresponding typed config, and the
|
||||
# auto config's ``thinking_retention`` field is carried over.
|
||||
_CONFIG_BY_NAME: dict[str, type[BaseRendererConfig]] = {
|
||||
"auto": AutoRendererConfig,
|
||||
"default": DefaultRendererConfig,
|
||||
"qwen3": Qwen3RendererConfig,
|
||||
"prime-qwen3": PrimeQwen3RendererConfig,
|
||||
"qwen3.5": Qwen35RendererConfig,
|
||||
"qwen3.6": Qwen36RendererConfig,
|
||||
"qwen3-vl": Qwen3VLRendererConfig,
|
||||
"glm-5": GLM5RendererConfig,
|
||||
"glm-5.1": GLM51RendererConfig,
|
||||
"glm-4.5": GLM45RendererConfig,
|
||||
"gpt-oss": GptOssRendererConfig,
|
||||
"hy3": Hy3RendererConfig,
|
||||
"kimi-k2": KimiK2RendererConfig,
|
||||
"kimi-k2.5": KimiK25RendererConfig,
|
||||
"laguna-xs.2": LagunaXS2RendererConfig,
|
||||
"laguna-xs-2.1": LagunaXS21RendererConfig,
|
||||
"llama-3": Llama3RendererConfig,
|
||||
"minimax-m2": MiniMaxM2RendererConfig,
|
||||
"nemotron-3": Nemotron3RendererConfig,
|
||||
"nemotron-3-ultra": Nemotron3UltraRendererConfig,
|
||||
"deepseek-v3": DeepSeekV3RendererConfig,
|
||||
"deepseek-r1": DeepSeekR1RendererConfig,
|
||||
}
|
||||
|
||||
|
||||
def _config_class_for(name: str) -> type[BaseRendererConfig]:
|
||||
cls = _CONFIG_BY_NAME.get(name)
|
||||
if cls is None:
|
||||
raise ValueError(
|
||||
f"No renderer config registered for name={name!r}. "
|
||||
f"Known: {sorted(_CONFIG_BY_NAME)}"
|
||||
)
|
||||
return cls
|
||||
|
||||
|
||||
def config_from_name(name: str) -> BaseRendererConfig | None:
|
||||
"""Construct a default-valued config for the given renderer name.
|
||||
|
||||
Convenience for callers that hold a renderer name as a string and
|
||||
want the matching typed config. ``"auto"`` returns ``None`` —
|
||||
:func:`renderers.create_renderer` interprets that as "run auto
|
||||
resolution against ``MODEL_RENDERER_MAP``", which is what callers
|
||||
expect from a bare-string name.
|
||||
"""
|
||||
if name == "auto":
|
||||
return None
|
||||
return _config_class_for(name)()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AutoRendererConfig",
|
||||
"BaseRendererConfig",
|
||||
"DefaultRendererConfig",
|
||||
"DeepSeekR1RendererConfig",
|
||||
"DeepSeekV3RendererConfig",
|
||||
"GLM45RendererConfig",
|
||||
"GLM51RendererConfig",
|
||||
"GLM5RendererConfig",
|
||||
"GptOssRendererConfig",
|
||||
"Hy3RendererConfig",
|
||||
"KimiK25RendererConfig",
|
||||
"KimiK2RendererConfig",
|
||||
"LagunaXS2RendererConfig",
|
||||
"LagunaXS21RendererConfig",
|
||||
"Llama3RendererConfig",
|
||||
"MiniMaxM2RendererConfig",
|
||||
"Nemotron3RendererConfig",
|
||||
"Nemotron3UltraRendererConfig",
|
||||
"PrimeQwen3RendererConfig",
|
||||
"Qwen35RendererConfig",
|
||||
"Qwen36RendererConfig",
|
||||
"Qwen3RendererConfig",
|
||||
"Qwen3VLRendererConfig",
|
||||
"RendererConfig",
|
||||
"ResolvedThinkingRetention",
|
||||
"ThinkingRetention",
|
||||
"config_from_name",
|
||||
]
|
||||
@@ -0,0 +1,59 @@
|
||||
"""DeepSeek-R1 Renderer — the reasoning variant of the DeepSeek format.
|
||||
|
||||
R1 shares DeepSeek-V3's special tokens, message structure, and tool-call
|
||||
wire format, so it subclasses :class:`renderers.deepseek_v3.DeepSeekV3Renderer`
|
||||
and overrides only the two places its chat template diverges:
|
||||
|
||||
1. Generation prompt — R1 unconditionally prefills ``<think>\\n``
|
||||
(``<|Assistant|><think>\\n``) to trigger reasoning, where V3 emits a bare
|
||||
``<|Assistant|>``. Handled by ``_GEN_THINK_PREFILL``.
|
||||
2. Historical assistant turns — R1 strips the reasoning trace, keeping only
|
||||
the text after ``</think>`` (``content.split('</think>')[-1]``), where V3
|
||||
emits content verbatim. Handled by ``_prepare_assistant_content``.
|
||||
|
||||
Everything else — system handling, tool-call / tool-output rendering,
|
||||
special-token resolution, and ``parse_response`` (``parse_deepseek_v3``,
|
||||
shared) — is inherited unchanged.
|
||||
|
||||
Scope: full ``deepseek-ai/DeepSeek-R1`` and ``-R1-0528``. The R1-Distill
|
||||
models (``DeepSeek-R1-Distill-Qwen/Llama``) use their base models'
|
||||
tokenizers and route to the Qwen3 / Llama-3 renderers, not this one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from renderers.base import Message
|
||||
from renderers.configs import DeepSeekR1RendererConfig
|
||||
from renderers.deepseek_v3 import DeepSeekV3Renderer
|
||||
|
||||
|
||||
class DeepSeekR1Renderer(DeepSeekV3Renderer):
|
||||
"""Deterministic message → token renderer for DeepSeek-R1 models."""
|
||||
|
||||
_config_cls: type = DeepSeekR1RendererConfig
|
||||
_implied_thinking_retention = "template"
|
||||
_GEN_THINK_PREFILL: str = "<think>\n"
|
||||
|
||||
def _prepare_assistant_content(self, msg: Message) -> str:
|
||||
"""Assistant content with the reasoning trace stripped, mirroring the
|
||||
R1 template's ``content.split('</think>')[-1]`` on historical turns.
|
||||
|
||||
Structured ``thinking``/``text`` parts are reconstructed inline first
|
||||
so the same ``</think>`` split applies. The separate
|
||||
``reasoning_content`` field is ignored — the R1 chat template never
|
||||
reads it, and history reasoning is dropped regardless.
|
||||
"""
|
||||
content = msg.get("content") or ""
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for p in content:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
if p.get("type") == "thinking":
|
||||
parts.append(f"<think>{p.get('thinking', '')}</think>")
|
||||
elif p.get("type") == "text":
|
||||
parts.append(p.get("text", ""))
|
||||
content = "".join(parts)
|
||||
if "</think>" in content:
|
||||
content = content.split("</think>")[-1]
|
||||
return content
|
||||
+186
-77
@@ -21,9 +21,14 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import DeepSeekV3RendererConfig
|
||||
from renderers.parsing import parse_deepseek_v3
|
||||
|
||||
# Fullwidth vertical bar used in DeepSeek special token names.
|
||||
@@ -38,24 +43,34 @@ def _ds_token(name: str) -> str:
|
||||
|
||||
|
||||
class DeepSeekV3Renderer:
|
||||
"""Deterministic message → token renderer for DeepSeek V3 models."""
|
||||
"""Deterministic message → token renderer for DeepSeek-V3 models.
|
||||
|
||||
DeepSeek-V3 is non-reasoning: its chat template has no ``<think>``
|
||||
concept — the generation prompt is a bare ``<|Assistant|>`` and past
|
||||
assistant content is emitted verbatim. The reasoning variant
|
||||
(``<think>``-prefilled prompt, history reasoning stripped) lives in
|
||||
:class:`renderers.deepseek_r1.DeepSeekR1Renderer`, which subclasses
|
||||
this one. ``thinking_retention`` is a no-op here (no reasoning channel),
|
||||
stored for protocol uniformity.
|
||||
"""
|
||||
|
||||
#: Default typed config; the R1 subclass overrides this.
|
||||
_config_cls: type = DeepSeekV3RendererConfig
|
||||
_implied_thinking_retention = "all"
|
||||
#: Generation-prompt reasoning prefill. Empty for V3 (bare
|
||||
#: ``<|Assistant|>``); the R1 subclass overrides to ``"<think>\n"``.
|
||||
_GEN_THINK_PREFILL: str = ""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: DeepSeekV3RendererConfig | None = None,
|
||||
):
|
||||
# DeepSeek-V3's chat template always emits ``<think>{reasoning}</think>``
|
||||
# when ``reasoning_content`` is provided — no drop, so the override
|
||||
# flags are no-ops. Stored for introspection / Protocol parity only.
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or type(self)._config_cls()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
self._implied_thinking_retention,
|
||||
)
|
||||
|
||||
# ── BOS / EOS ────────────────────────────────────────────────
|
||||
@@ -114,22 +129,47 @@ class DeepSeekV3Renderer:
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
|
||||
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) -> None:
|
||||
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
# ── 1. BOS token ─────────────────────────────────────────────
|
||||
emit_special(self._bos, -1, is_sampled=False)
|
||||
emit_special(self._bos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Collect system messages at the start ───────────────────
|
||||
# All leading system messages are concatenated with "\n\n" and emitted
|
||||
@@ -151,7 +191,8 @@ class DeepSeekV3Renderer:
|
||||
|
||||
if sys_parts:
|
||||
# Attribute the concatenated system text to the first system message (index 0).
|
||||
emit_text("\n\n".join(sys_parts), 0, is_sampled=False)
|
||||
# The system content is the caller's body — mark is_content=True.
|
||||
emit_text("\n\n".join(sys_parts), 0, is_sampled=False, is_content=True)
|
||||
|
||||
# ── 3. Render non-system messages ─────────────────────────────
|
||||
num_messages = len(messages)
|
||||
@@ -166,8 +207,8 @@ class DeepSeekV3Renderer:
|
||||
content = "".join(
|
||||
p.get("text", "") for p in content if isinstance(p, dict)
|
||||
)
|
||||
emit_special(self._user_token, i, is_sampled=False)
|
||||
emit_text(str(content), i, is_sampled=False)
|
||||
emit_special(self._user_token, i, is_sampled=False, is_content=False)
|
||||
emit_text(str(content), i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "user":
|
||||
content = msg.get("content") or ""
|
||||
@@ -180,8 +221,8 @@ class DeepSeekV3Renderer:
|
||||
else ""
|
||||
for p in content
|
||||
)
|
||||
emit_special(self._user_token, i, is_sampled=False)
|
||||
emit_text(str(content), i, is_sampled=False)
|
||||
emit_special(self._user_token, i, is_sampled=False, is_content=False)
|
||||
emit_text(str(content), i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "assistant":
|
||||
self._render_assistant(
|
||||
@@ -190,6 +231,7 @@ class DeepSeekV3Renderer:
|
||||
messages,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
@@ -198,6 +240,7 @@ class DeepSeekV3Renderer:
|
||||
i,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
# ── 4. Generation prompt ──────────────────────────────────────
|
||||
@@ -205,12 +248,21 @@ class DeepSeekV3Renderer:
|
||||
# Don't add <|Assistant|> after tool outputs — content flows directly.
|
||||
last_role = messages[-1]["role"] if messages else None
|
||||
if last_role != "tool":
|
||||
emit_special(self._assistant_token, -1, is_sampled=False)
|
||||
if self._enable_thinking:
|
||||
emit_text("<think>\n", -1, is_sampled=False)
|
||||
emit_special(
|
||||
self._assistant_token, -1, is_sampled=False, is_content=False
|
||||
)
|
||||
if self._GEN_THINK_PREFILL:
|
||||
emit_text(
|
||||
self._GEN_THINK_PREFILL, -1, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -260,6 +312,11 @@ class DeepSeekV3Renderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
@@ -271,22 +328,40 @@ class DeepSeekV3Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't track sampled_mask here. Local helpers accept the kwarg
|
||||
# for signature compatibility with ``_render_tool`` and ignore
|
||||
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
|
||||
# empty.
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
@@ -299,11 +374,11 @@ class DeepSeekV3Renderer:
|
||||
|
||||
if role == "user":
|
||||
emit_special(self._user_token, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
elif role == "system":
|
||||
# Post-initial system messages render as user turns.
|
||||
emit_special(self._user_token, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
elif role == "tool":
|
||||
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
|
||||
next_is_tool = (
|
||||
@@ -313,7 +388,7 @@ class DeepSeekV3Renderer:
|
||||
if not prev_is_tool:
|
||||
emit_special(self._tool_outputs_begin, i)
|
||||
emit_special(self._tool_output_begin, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
emit_special(self._tool_output_end, i)
|
||||
if not next_is_tool:
|
||||
emit_special(self._tool_outputs_end, i)
|
||||
@@ -326,15 +401,40 @@ class DeepSeekV3Renderer:
|
||||
last_role = new_messages[-1].get("role") if new_messages else None
|
||||
if last_role != "tool":
|
||||
emit_special(self._assistant_token, -1)
|
||||
if self._enable_thinking:
|
||||
emit_text("<think>\n", -1)
|
||||
if self._GEN_THINK_PREFILL:
|
||||
emit_text(self._GEN_THINK_PREFILL, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Assistant rendering
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _prepare_assistant_content(self, msg: Message) -> str:
|
||||
"""Assistant content as the V3 template would emit it: verbatim.
|
||||
|
||||
V3 is non-reasoning — its template emits ``message['content']`` as-is
|
||||
and never reads ``reasoning_content``. A structured content list is
|
||||
flattened to its ``text`` parts. The R1 subclass overrides this to
|
||||
strip ``</think>`` from history.
|
||||
"""
|
||||
content = msg.get("content") or ""
|
||||
if isinstance(content, list):
|
||||
content = "".join(
|
||||
p.get("text", "")
|
||||
for p in content
|
||||
if isinstance(p, dict) and p.get("type") == "text"
|
||||
)
|
||||
return content
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
msg: Message,
|
||||
@@ -343,30 +443,14 @@ class DeepSeekV3Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Determine whether this message follows a tool output sequence.
|
||||
# The HF template emits <|tool▁outputs▁end|> before the assistant content
|
||||
# without a new <|Assistant|> token in that case.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
|
||||
content = msg.get("content") or ""
|
||||
# Support structured content (ThinkingPart / TextPart list).
|
||||
if isinstance(content, list):
|
||||
parts_text: list[str] = []
|
||||
for p in content:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
if p.get("type") == "thinking":
|
||||
thinking = p.get("thinking", "")
|
||||
parts_text.append(f"<think>{thinking}</think>")
|
||||
elif p.get("type") == "text":
|
||||
parts_text.append(p.get("text", ""))
|
||||
content = "".join(parts_text)
|
||||
# Also accept reasoning_content stored separately (OpenAI-style).
|
||||
elif isinstance(msg.get("reasoning_content"), str) and msg["reasoning_content"]:
|
||||
reasoning = msg["reasoning_content"]
|
||||
content = f"<think>{reasoning}</think>{content}"
|
||||
|
||||
content = self._prepare_assistant_content(msg)
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
|
||||
# ``<|Assistant|>`` is template-injected scaffolding — at
|
||||
@@ -375,18 +459,23 @@ class DeepSeekV3Renderer:
|
||||
# keeps the SFT loss mask aligned with what the model would
|
||||
# actually have produced. When the previous message is a tool
|
||||
# response, the template skips this token entirely (content
|
||||
# flows directly out of ``<|tool▁outputs▁end|>``).
|
||||
# flows directly out of ``<|tool▁outputs▁end|>``). On assistant
|
||||
# the invariant ``is_content == sampled_mask`` holds.
|
||||
if not prev_is_tool:
|
||||
emit_special(self._assistant_token, msg_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._assistant_token, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
if not tool_calls:
|
||||
emit_text(content, msg_idx, is_sampled=True)
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
# Emit any pre-tool-call content first.
|
||||
emit_text(content, msg_idx, is_sampled=True)
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool call section.
|
||||
emit_special(self._tool_calls_begin, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._tool_calls_begin, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
@@ -398,17 +487,28 @@ class DeepSeekV3Renderer:
|
||||
)
|
||||
# Format: <|tool▁call▁begin|>function<|tool▁sep|>{name}\n```json\n{args}\n```<|tool▁call▁end|>
|
||||
# tool_sep is a special token; type ("function") and name+args are plain text.
|
||||
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
|
||||
emit_text("function", msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_sep, msg_idx, is_sampled=True)
|
||||
emit_text(f"{name}\n```json\n{args_str}\n```", msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_calls_end, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._tool_call_begin, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text("function", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_sep, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
f"{name}\n```json\n{args_str}\n```",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(
|
||||
self._tool_calls_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
# ``<|end▁of▁sentence|>`` is the model's stop signal — it
|
||||
# samples this to end its turn, so it is part of the sampled
|
||||
# stream.
|
||||
emit_special(self._eos, msg_idx, is_sampled=True)
|
||||
emit_special(self._eos, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Tool (tool-response) rendering
|
||||
@@ -421,10 +521,13 @@ class DeepSeekV3Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False.
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# body bytes get ``is_content=True``; the surrounding section
|
||||
# specials are scaffold.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
@@ -435,11 +538,17 @@ class DeepSeekV3Renderer:
|
||||
content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._tool_outputs_begin, msg_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._tool_outputs_begin, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
emit_special(self._tool_output_begin, msg_idx, is_sampled=False)
|
||||
emit_text(str(content), msg_idx, is_sampled=False)
|
||||
emit_special(self._tool_output_end, msg_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._tool_output_begin, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text(str(content), msg_idx, is_sampled=False, is_content=True)
|
||||
emit_special(self._tool_output_end, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if not next_is_tool:
|
||||
emit_special(self._tool_outputs_end, msg_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._tool_outputs_end, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
+34
-26
@@ -18,10 +18,12 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
resolve_thinking_retention,
|
||||
)
|
||||
from renderers.configs import DefaultRendererConfig
|
||||
from renderers.hermes import HermesToolParser
|
||||
from renderers.parsers import (
|
||||
ReasoningParser,
|
||||
ToolParser,
|
||||
get_reasoning_parser,
|
||||
get_tool_parser,
|
||||
)
|
||||
@@ -82,36 +84,36 @@ def _decode_tool_call_arguments(messages: list) -> list:
|
||||
class DefaultRenderer:
|
||||
"""Fallback renderer using tokenizer.apply_chat_template().
|
||||
|
||||
Works with any model. Pass ``tool_parser`` and/or ``reasoning_parser``
|
||||
(by name, resolved against the registries in ``renderers.parsers``) to
|
||||
enable structured output extraction.
|
||||
Works with any model. The config can carry ``tool_parser`` and/or
|
||||
``reasoning_parser`` (resolved against ``renderers.parsers``) to
|
||||
enable structured output extraction, plus arbitrary additional Jinja
|
||||
template kwargs captured as ``model_extra`` (``extra="allow"`` on
|
||||
:class:`renderers.DefaultRendererConfig`).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
tool_parser: str | ToolParser | None = None,
|
||||
reasoning_parser: str | ReasoningParser | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
**chat_template_kwargs,
|
||||
config: DefaultRendererConfig | None = None,
|
||||
):
|
||||
if preserve_all_thinking or preserve_thinking_between_tool_calls:
|
||||
raise NotImplementedError(
|
||||
"DefaultRenderer falls back to apply_chat_template and can't "
|
||||
"selectively re-emit dropped reasoning_content. Configure a "
|
||||
"model-specific renderer if you need preserve_*_thinking."
|
||||
cfg = config or DefaultRendererConfig()
|
||||
if cfg.thinking_retention is not None:
|
||||
raise ValueError(
|
||||
"DefaultRenderer cannot implement explicit thinking_retention "
|
||||
"bridge policy because its template close/turn structure is "
|
||||
"opaque. Use a typed renderer for this model."
|
||||
)
|
||||
self._tokenizer = tokenizer
|
||||
self._chat_template_kwargs = chat_template_kwargs
|
||||
self._tool_parser = _resolve_parser(tool_parser, tokenizer, get_tool_parser)
|
||||
self._reasoning_parser = _resolve_parser(
|
||||
reasoning_parser, tokenizer, get_reasoning_parser
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
cfg,
|
||||
"template",
|
||||
)
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self._tokenizer = tokenizer
|
||||
self.config = cfg
|
||||
self._tool_parser = _resolve_parser(cfg.tool_parser, tokenizer, get_tool_parser)
|
||||
if isinstance(self._tool_parser, HermesToolParser):
|
||||
self._tool_parser.configure_prefill(dict(cfg.model_extra or {}))
|
||||
self._reasoning_parser = _resolve_parser(
|
||||
cfg.reasoning_parser, tokenizer, get_reasoning_parser
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -143,10 +145,16 @@ class DefaultRenderer:
|
||||
token_ids = full_ids
|
||||
message_indices.extend([-1] * len(gen_tokens))
|
||||
|
||||
return RenderedTokens(token_ids=token_ids, message_indices=message_indices)
|
||||
message_roles = [m.get("role") or "" for m in messages]
|
||||
return RenderedTokens(
|
||||
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]:
|
||||
kwargs = dict(self._chat_template_kwargs)
|
||||
kwargs = dict(self.config.model_extra or {})
|
||||
kwargs["add_generation_prompt"] = add_generation_prompt
|
||||
kwargs["tokenize"] = True
|
||||
if tools is not None:
|
||||
|
||||
+253
-84
@@ -20,9 +20,13 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
)
|
||||
from renderers.configs import GLM45RendererConfig
|
||||
from renderers.parsing import parse_glm
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
@@ -52,16 +56,13 @@ class GLM45Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: GLM45RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or GLM45RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all" if not self.config.enable_thinking else "tool_cycle",
|
||||
)
|
||||
|
||||
self._gmask = self._token_id("[gMASK]")
|
||||
@@ -128,30 +129,58 @@ class GLM45Renderer:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated segments as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment.
|
||||
|
||||
Lets call sites express "this wrap + this body, joined the
|
||||
same way as the chat template, but attributed separately"
|
||||
without splitting the encode call (which could shift BPE
|
||||
merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── Prefix ──────────────────────────────────────────────────
|
||||
emit_special(self._gmask, -1, is_sampled=False)
|
||||
emit_special(self._sop, -1, is_sampled=False)
|
||||
emit_special(self._gmask, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._sop, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Tools in system prompt ──────────────────────────────────
|
||||
# The tools-header block is all scaffold by design — the tools
|
||||
# dict is recoverable from the ``tools`` argument; don't
|
||||
# re-attribute the embedded JSON specs as message body.
|
||||
if tools:
|
||||
emit_special(self._system, -1, is_sampled=False)
|
||||
emit_special(self._system, -1, is_sampled=False, is_content=False)
|
||||
tool_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
|
||||
tool_text += _TOOLS_FOOTER
|
||||
emit_text(tool_text, -1, is_sampled=False)
|
||||
emit_text(tool_text, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Compute last_user_index ─────────────────────────────────
|
||||
last_ui = self._last_user_index(messages)
|
||||
@@ -161,49 +190,81 @@ class GLM45Renderer:
|
||||
role = msg["role"]
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
# When the previous message is an assistant, this message's
|
||||
# role-opening token (``<|user|>`` / ``<|observation|>``) is
|
||||
# the inference-time stop signal that closes the assistant's
|
||||
# turn (see ``get_stop_token_ids``). Mark it
|
||||
# ``is_sampled=True`` so the loss-mask pipeline trains the
|
||||
# model to emit it after ``</tool_call>`` (instead of
|
||||
# continuing with another ``<tool_call>`` block). The token
|
||||
# stays attributed to this message (msg_idx=i) and remains
|
||||
# ``is_content=False`` — it's a role-marker / scaffold, not
|
||||
# body bytes, so ``content_mask_for_roles({"tool"})`` and
|
||||
# ``content_token_spans_by_role()`` correctly exclude it
|
||||
# from "tool body" views. Byte stream is unchanged.
|
||||
# ``system`` only appears at the start of a GLM conversation,
|
||||
# so its opener is never the closer of an assistant turn.
|
||||
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
|
||||
|
||||
if role == "system":
|
||||
emit_special(self._system, i, is_sampled=False)
|
||||
emit_text("\n" + content, i, is_sampled=False)
|
||||
emit_special(self._system, i, is_sampled=False, is_content=False)
|
||||
# ``\n`` is the scaffold separator after the role tag;
|
||||
# the body proper is the caller-provided content.
|
||||
emit_text_segments(
|
||||
[("\n", False), (content, True)], i, is_sampled=False
|
||||
)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._user, i, is_sampled=False)
|
||||
user_text = "\n" + content
|
||||
if not self._enable_thinking and not content.endswith("/nothink"):
|
||||
user_text += "/nothink"
|
||||
emit_text(user_text, i, is_sampled=False)
|
||||
emit_special(
|
||||
self._user,
|
||||
i,
|
||||
is_sampled=closes_assistant_turn,
|
||||
is_content=False,
|
||||
)
|
||||
# ``\n`` is scaffold; ``content`` is body; the optional
|
||||
# ``/nothink`` suffix is scaffold the renderer injects
|
||||
# when ``enable_thinking=False``.
|
||||
user_segments: list[tuple[str, bool]] = [("\n", False), (content, True)]
|
||||
if not self.config.enable_thinking and not content.endswith("/nothink"):
|
||||
user_segments.append(("/nothink", False))
|
||||
emit_text_segments(user_segments, i, is_sampled=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
last_ui,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
messages, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
# ── Generation prompt ───────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1, is_sampled=False)
|
||||
if not self._enable_thinking:
|
||||
emit_text("\n", -1, is_sampled=False)
|
||||
emit_special(self._think, -1, is_sampled=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False)
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
if not self.config.enable_thinking:
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -258,6 +319,12 @@ class GLM45Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# Same next-turn-marker scheme as GLM-5, but role markers are
|
||||
# followed by a literal ``\n`` in the prompt text.
|
||||
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
|
||||
@@ -271,54 +338,121 @@ class GLM45Renderer:
|
||||
last_prev = previous_ids[-1]
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't track sampled_mask here. Local helpers accept the kwarg
|
||||
# for signature compatibility with ``_render_tool`` and ignore
|
||||
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
|
||||
# empty.
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
# The opener-token of the first new_message may also serve as
|
||||
# the close of the previous assistant turn (when the model
|
||||
# failed to sample the stop token itself and the bridge has to
|
||||
# synthesize the boundary above). Unlike :meth:`render`, the
|
||||
# bridge emits these with ``is_sampled=False, is_content=False``
|
||||
# — they are template scaffolding for the *next* step's prompt,
|
||||
# not tokens the model produced *in this* step. The RL loss
|
||||
# operates on ``previous_completion_ids`` (what the model
|
||||
# actually sampled this round); bridge tokens belong to the
|
||||
# subsequent prompt and must not be counted as "model output"
|
||||
# by downstream mask consumers. This deliberate disagreement
|
||||
# with ``render()`` reflects the SFT vs RL semantics: render's
|
||||
# masks describe what the model *should* produce given a
|
||||
# complete conversation; bridge's masks describe what it
|
||||
# *actually* produced this step.
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
if role == "user":
|
||||
if not (i == 0 and last_prev == self._user):
|
||||
emit_special(self._user, i)
|
||||
user_text = "\n" + content
|
||||
if not self._enable_thinking and not content.endswith("/nothink"):
|
||||
user_text += "/nothink"
|
||||
emit_text(user_text, i)
|
||||
user_segments: list[tuple[str, bool]] = [
|
||||
("\n", False),
|
||||
(content, True),
|
||||
]
|
||||
if not self.config.enable_thinking and not content.endswith("/nothink"):
|
||||
user_segments.append(("/nothink", False))
|
||||
emit_text_segments(user_segments, i)
|
||||
elif role == "system":
|
||||
emit_special(self._system, i)
|
||||
emit_text("\n" + content, i)
|
||||
emit_text_segments([("\n", False), (content, True)], i)
|
||||
elif role == "tool":
|
||||
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
|
||||
if i == 0 and last_prev == self._observation:
|
||||
pass
|
||||
elif not prev_is_tool:
|
||||
emit_special(self._observation, i)
|
||||
emit_text("\n<tool_response>\n" + content + "\n</tool_response>", i)
|
||||
emit_text_segments(
|
||||
[
|
||||
("\n<tool_response>\n", False),
|
||||
(content, True),
|
||||
("\n</tool_response>", False),
|
||||
],
|
||||
i,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
# Generation prompt.
|
||||
emit_special(self._assistant, -1)
|
||||
if not self._enable_thinking:
|
||||
if not self.config.enable_thinking:
|
||||
emit_text("\n", -1)
|
||||
emit_special(self._think, -1)
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -327,9 +461,9 @@ class GLM45Renderer:
|
||||
content,
|
||||
last_user_index,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
):
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
@@ -357,23 +491,31 @@ class GLM45Renderer:
|
||||
# turn). So no sampled stop-signal token lives inside this
|
||||
# assistant span — content / think / tool_calls carry the
|
||||
# is_sampled=True signal.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
#
|
||||
# Invariant on assistant tokens: ``is_content == sampled_mask``.
|
||||
# Every scaffold token here gets ``is_sampled=False/is_content=False``;
|
||||
# every model-sampled emit gets both True.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if (msg_idx > last_user_index or preserve_thinking) and reasoning_content:
|
||||
emit_special(self._think, msg_idx, is_sampled=True)
|
||||
emit_text(reasoning_content.strip(), msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
if msg_idx > last_user_index and reasoning_content:
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
reasoning_content.strip(), msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_special(self._think, msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
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)
|
||||
|
||||
# Tool calls — keep content + \n contiguous to preserve BPE merges
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
if content.strip() and tool_calls:
|
||||
emit_text("\n" + content.strip() + "\n", msg_idx, is_sampled=True)
|
||||
emit_text(
|
||||
"\n" + content.strip() + "\n", msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
elif content.strip():
|
||||
emit_text("\n" + content.strip(), msg_idx, is_sampled=True)
|
||||
emit_text("\n" + content.strip(), msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
@@ -381,9 +523,9 @@ class GLM45Renderer:
|
||||
arguments = func.get("arguments", {})
|
||||
|
||||
if not content.strip():
|
||||
emit_text("\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_tok, msg_idx, is_sampled=True)
|
||||
emit_text(name + "\n", msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_call_tok, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(name + "\n", msg_idx, is_sampled=True, is_content=True)
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
# per-argument rendering below still works.
|
||||
if isinstance(arguments, str):
|
||||
@@ -393,22 +535,33 @@ class GLM45Renderer:
|
||||
arguments = {}
|
||||
if isinstance(arguments, dict):
|
||||
for arg_name, arg_value in arguments.items():
|
||||
emit_special(self._arg_key, msg_idx, is_sampled=True)
|
||||
emit_text(arg_name, msg_idx, is_sampled=True)
|
||||
emit_special(self._arg_key_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._arg_value, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._arg_key, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text(arg_name, 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(arg_value, str):
|
||||
emit_text(arg_value, msg_idx, is_sampled=True)
|
||||
emit_text(arg_value, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_text(
|
||||
json.dumps(arg_value, ensure_ascii=False),
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._arg_value_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end_tok, msg_idx, is_sampled=True)
|
||||
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_tok, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -418,17 +571,33 @@ class GLM45Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
# Tool body bytes get ``is_content=True``; the wraps are
|
||||
# scaffold. The ``<|observation|>`` role tag is scaffold too
|
||||
# (``is_content=False`` so ``content_mask_for_roles({"tool"})``
|
||||
# excludes it). When the previous message is an assistant it
|
||||
# doubles as the inference stop signal for that assistant's
|
||||
# turn — mark it ``is_sampled=True`` so SFT trains the model to
|
||||
# emit it after ``</tool_call>``. The token stays attributed to
|
||||
# this tool message; byte stream is unchanged.
|
||||
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
|
||||
closes_assistant_turn = prev_role == "assistant"
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._observation, msg_idx, is_sampled=False)
|
||||
if prev_role != "tool":
|
||||
emit_special(
|
||||
self._observation,
|
||||
msg_idx,
|
||||
is_sampled=closes_assistant_turn,
|
||||
is_content=False,
|
||||
)
|
||||
|
||||
emit_text(
|
||||
"\n<tool_response>\n" + content + "\n</tool_response>",
|
||||
emit_text_segments(
|
||||
[
|
||||
("\n<tool_response>\n", False),
|
||||
(content, True),
|
||||
("\n</tool_response>", False),
|
||||
],
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
)
|
||||
|
||||
+257
-82
@@ -21,9 +21,13 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
)
|
||||
from renderers.configs import GLM5RendererConfig, GLM51RendererConfig
|
||||
from renderers.parsing import parse_glm
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
@@ -53,19 +57,27 @@ class GLM5Renderer:
|
||||
# GLM51Renderer; GLM-5 proper keeps this off.
|
||||
empty_think_on_last_assistant: bool = False
|
||||
|
||||
# GLM-5.1 uses the same template surface and binds the same kwargs.
|
||||
# Subclassed in ``GLM51Renderer`` so the registry can dispatch on the
|
||||
# ``glm-5.1`` discriminator while sharing this implementation.
|
||||
_config_cls: type = GLM5RendererConfig
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: GLM5RendererConfig | GLM51RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or type(self)._config_cls()
|
||||
if not self.config.clear_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
elif not self.config.enable_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
else:
|
||||
implied_thinking_retention = "tool_cycle"
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
implied_thinking_retention,
|
||||
)
|
||||
|
||||
self._gmask = self._token_id("[gMASK]")
|
||||
@@ -143,32 +155,61 @@ class GLM5Renderer:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated segments as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment.
|
||||
|
||||
Lets call sites express "this wrap + this body, joined the
|
||||
same way as the chat template, but attributed separately"
|
||||
without splitting the encode call (which could shift BPE
|
||||
merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── Prefix ──────────────────────────────────────────────────
|
||||
# ``[gMASK]<sop>`` is unconditional template scaffolding at the
|
||||
# very start of the stream — the model never samples these.
|
||||
emit_special(self._gmask, -1, is_sampled=False)
|
||||
emit_special(self._sop, -1, is_sampled=False)
|
||||
# very start of the stream — the model never samples these and
|
||||
# they are not part of any message body.
|
||||
emit_special(self._gmask, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._sop, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Tools in system prompt ──────────────────────────────────
|
||||
# The tools-header block is all scaffold by design — the tools
|
||||
# dict is recoverable from the ``tools`` argument; don't
|
||||
# re-attribute the embedded JSON specs as message body.
|
||||
if tools:
|
||||
emit_special(self._system, -1, is_sampled=False)
|
||||
emit_special(self._system, -1, is_sampled=False, is_content=False)
|
||||
tool_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tool_text += self._format_tool_spec(tool) + "\n"
|
||||
tool_text += _TOOLS_FOOTER
|
||||
emit_text(tool_text, -1, is_sampled=False)
|
||||
emit_text(tool_text, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Compute last_user_index ─────────────────────────────────
|
||||
last_ui = self._last_user_index(messages)
|
||||
@@ -178,49 +219,74 @@ class GLM5Renderer:
|
||||
role = msg["role"]
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
# When the previous message is an assistant, this message's
|
||||
# role-opening token (``<|user|>`` / ``<|observation|>``) is
|
||||
# the inference-time stop signal that closes the assistant's
|
||||
# turn (see ``get_stop_token_ids``). Mark it
|
||||
# ``is_sampled=True`` so the loss-mask pipeline trains the
|
||||
# model to emit it after ``</tool_call>`` (instead of
|
||||
# continuing with another ``<tool_call>`` block). The token
|
||||
# stays attributed to this message (msg_idx=i) and remains
|
||||
# ``is_content=False`` — it's a role-marker / scaffold, not
|
||||
# body bytes, so ``content_mask_for_roles({"tool"})`` and
|
||||
# ``content_token_spans_by_role()`` correctly exclude it
|
||||
# from "tool body" views. Byte stream is unchanged.
|
||||
# ``system`` only appears at the start of a GLM conversation,
|
||||
# so its opener is never the closer of an assistant turn.
|
||||
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
|
||||
|
||||
if role == "system":
|
||||
emit_special(self._system, i, is_sampled=False)
|
||||
emit_text(content, i, is_sampled=False)
|
||||
emit_special(self._system, i, is_sampled=False, is_content=False)
|
||||
emit_text(content, i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._user, i, is_sampled=False)
|
||||
emit_text(content, i, is_sampled=False)
|
||||
emit_special(
|
||||
self._user,
|
||||
i,
|
||||
is_sampled=closes_assistant_turn,
|
||||
is_content=False,
|
||||
)
|
||||
emit_text(content, i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
last_ui,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
messages, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
# ── Generation prompt ───────────────────────────────────────
|
||||
# Gen prompt tokens are what the chat template prepends before
|
||||
# sampling starts — the model continues from these, never emits
|
||||
# them. Always is_sampled=False.
|
||||
# them. Always is_sampled=False / is_content=False.
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1, is_sampled=False)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False)
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._think_end, -1, is_sampled=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -275,6 +341,12 @@ class GLM5Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# GLM has no per-turn close token. An assistant turn ends when the
|
||||
# next turn's role marker appears, OR the model emits <|endoftext|>.
|
||||
# vLLM includes these in ``stop_token_ids`` so a clean stop leaves
|
||||
@@ -292,23 +364,72 @@ class GLM5Renderer:
|
||||
last_prev = previous_ids[-1]
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't track sampled_mask here. Local helpers accept the kwarg
|
||||
# for signature compatibility with ``_render_assistant`` /
|
||||
# ``_render_tool`` and ignore it; the returned ``RenderedTokens``
|
||||
# leaves ``sampled_mask`` empty.
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
# The opener-token of the first new_message may also serve as
|
||||
# the close of the previous assistant turn (when the model
|
||||
# failed to sample the stop token itself and the bridge has to
|
||||
# synthesize the boundary above). Unlike :meth:`render`, the
|
||||
# bridge emits these with ``is_sampled=False, is_content=False``
|
||||
# — they are template scaffolding for the *next* step's prompt,
|
||||
# not tokens the model produced *in this* step. The RL loss
|
||||
# operates on ``previous_completion_ids`` (what the model
|
||||
# actually sampled this round); bridge tokens belong to the
|
||||
# subsequent prompt and must not be counted as "model output"
|
||||
# by downstream mask consumers. This deliberate disagreement
|
||||
# with ``render()`` reflects the SFT vs RL semantics: render's
|
||||
# masks describe what the model *should* produce given a
|
||||
# complete conversation; bridge's masks describe what it
|
||||
# *actually* produced this step.
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
@@ -316,10 +437,10 @@ class GLM5Renderer:
|
||||
# Dedup: model already emitted <|user|> as its stop token.
|
||||
if not (i == 0 and last_prev == self._user):
|
||||
emit_special(self._user, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
elif role == "system":
|
||||
emit_special(self._system, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
elif role == "tool":
|
||||
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
|
||||
if i == 0 and last_prev == self._observation:
|
||||
@@ -328,19 +449,27 @@ class GLM5Renderer:
|
||||
elif not prev_is_tool:
|
||||
emit_special(self._observation, i)
|
||||
emit_special(self._tool_response_tok, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
emit_special(self._tool_response_end_tok, i)
|
||||
else:
|
||||
return None
|
||||
|
||||
# Generation prompt — match the gen-prompt branch of ``render()``.
|
||||
emit_special(self._assistant, -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
else:
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -349,9 +478,9 @@ class GLM5Renderer:
|
||||
content,
|
||||
last_user_index,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
):
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
@@ -370,16 +499,20 @@ class GLM5Renderer:
|
||||
# samples it. Same for the ``<think>`` open / standalone
|
||||
# ``</think>`` separator that the template wraps around the
|
||||
# assistant body — see the per-branch comments below.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False)
|
||||
#
|
||||
# Invariant on assistant tokens: ``is_content == sampled_mask``.
|
||||
# Every scaffold token here gets ``is_sampled=False/is_content=False``;
|
||||
# every model-sampled emit gets both True.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Chat-template default: keep ``<think>`` only on the in-flight cycle
|
||||
# (post-last-user). Past-cycle assistants drop their reasoning.
|
||||
# ``preserve_thinking`` is the override output of
|
||||
# ``should_preserve_past_thinking`` — it adds historical assistants
|
||||
# back when the renderer was constructed with
|
||||
# ``preserve_all_thinking=True``.
|
||||
# ``clear_thinking=False`` mirrors
|
||||
# the template's per-call ``clear_thinking is defined and not
|
||||
# clear_thinking`` gate: a chat_template_kwarg surface for the
|
||||
# same behaviour, gated explicitly by the caller per render.
|
||||
include_thinking = (
|
||||
msg_idx > last_user_index or preserve_thinking
|
||||
msg_idx > last_user_index or not self.config.clear_thinking
|
||||
) and reasoning_content
|
||||
|
||||
if include_thinking:
|
||||
@@ -387,36 +520,50 @@ class GLM5Renderer:
|
||||
# inference (gen prompt = ``<|assistant|><think>``), so it's
|
||||
# template-injected scaffolding. The reasoning text and the
|
||||
# closing ``</think>`` are what the model actually samples.
|
||||
emit_special(self._think, msg_idx, is_sampled=False)
|
||||
emit_text(reasoning_content.strip(), msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
elif self.empty_think_on_last_assistant and msg_idx > last_user_index:
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text(
|
||||
reasoning_content.strip(), msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
elif (
|
||||
self.empty_think_on_last_assistant
|
||||
and msg_idx > last_user_index
|
||||
and self.config.enable_thinking
|
||||
):
|
||||
# GLM-5.1: wrap the last assistant with an empty <think></think>
|
||||
# even without reasoning, matching the Jinja template. With
|
||||
# ``enable_thinking=True`` the gen prompt already includes
|
||||
# ``<think>``; the model then samples ``</think>`` to close an
|
||||
# empty think block. So ``<think>`` is scaffolding,
|
||||
# ``</think>`` is sampled.
|
||||
emit_special(self._think, msg_idx, is_sampled=False)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
#
|
||||
# When ``enable_thinking=False`` the GLM-5.1 template skips
|
||||
# the opening ``<think>`` for the most-recent assistant too
|
||||
# — it emits only the lone ``</think>`` separator (and the
|
||||
# gen prompt likewise switches to ``</think>``). Fall
|
||||
# through to the else branch below so we match.
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
# Lone ``</think>`` separator the template injects when no
|
||||
# reasoning is rendered (historical assistants, GLM-5 default
|
||||
# with no thinking). Not sampled.
|
||||
emit_special(self._think_end, msg_idx, is_sampled=False)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if content.strip():
|
||||
emit_text(content.strip(), msg_idx, is_sampled=True)
|
||||
emit_text(content.strip(), msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool calls (directly after content, no newlines)
|
||||
# Tool calls (directly after content, no newlines). All of these
|
||||
# are the model's sampled output — both is_sampled and is_content
|
||||
# are True across the entire tool-call span.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
|
||||
emit_special(self._tool_call_tok, msg_idx, is_sampled=True)
|
||||
emit_text(name, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_tok, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(name, msg_idx, is_sampled=True, is_content=True)
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
# per-argument rendering below still works.
|
||||
if isinstance(arguments, str):
|
||||
@@ -426,20 +573,31 @@ class GLM5Renderer:
|
||||
arguments = {}
|
||||
if isinstance(arguments, dict):
|
||||
for arg_name, arg_value in arguments.items():
|
||||
emit_special(self._arg_key, msg_idx, is_sampled=True)
|
||||
emit_text(arg_name, msg_idx, is_sampled=True)
|
||||
emit_special(self._arg_key_end, msg_idx, is_sampled=True)
|
||||
emit_special(self._arg_value, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._arg_key, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text(arg_name, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._arg_key_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(
|
||||
self._arg_value, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
if isinstance(arg_value, str):
|
||||
emit_text(arg_value, msg_idx, is_sampled=True)
|
||||
emit_text(arg_value, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_text(
|
||||
json.dumps(arg_value, ensure_ascii=False),
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._arg_value_end, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end_tok, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._arg_value_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(
|
||||
self._tool_call_end_tok, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -449,18 +607,34 @@ class GLM5Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
# Tool body bytes get ``is_content=True``; the wraps are
|
||||
# scaffold. The ``<|observation|>`` role tag is scaffold too
|
||||
# (``is_content=False`` so ``content_mask_for_roles({"tool"})``
|
||||
# excludes it). When the previous message is an assistant it
|
||||
# doubles as the inference stop signal for that assistant's
|
||||
# turn — mark it ``is_sampled=True`` so SFT trains the model to
|
||||
# emit it after ``</tool_call>``. The token stays attributed to
|
||||
# this tool message; byte stream is unchanged.
|
||||
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
|
||||
closes_assistant_turn = prev_role == "assistant"
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._observation, msg_idx, is_sampled=False)
|
||||
if prev_role != "tool":
|
||||
emit_special(
|
||||
self._observation,
|
||||
msg_idx,
|
||||
is_sampled=closes_assistant_turn,
|
||||
is_content=False,
|
||||
)
|
||||
|
||||
emit_special(self._tool_response_tok, msg_idx, is_sampled=False)
|
||||
emit_text(content, msg_idx, is_sampled=False)
|
||||
emit_special(self._tool_response_end_tok, msg_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._tool_response_tok, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text(content, msg_idx, is_sampled=False, is_content=True)
|
||||
emit_special(
|
||||
self._tool_response_end_tok, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
|
||||
class GLM51Renderer(GLM5Renderer):
|
||||
@@ -478,6 +652,7 @@ class GLM51Renderer(GLM5Renderer):
|
||||
"""
|
||||
|
||||
empty_think_on_last_assistant = True
|
||||
_config_cls = GLM51RendererConfig
|
||||
|
||||
@staticmethod
|
||||
def _format_tool_spec(tool: ToolSpec) -> str:
|
||||
|
||||
+267
-60
@@ -56,10 +56,13 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import GptOssRendererConfig
|
||||
from renderers.parsing import parse_gpt_oss
|
||||
|
||||
|
||||
@@ -121,44 +124,31 @@ class GptOssRenderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
use_system_prompt: bool = True,
|
||||
reasoning_effort: str | None = "medium",
|
||||
conversation_start_date: str | None = None,
|
||||
knowledge_cutoff: str | None = None,
|
||||
model_identity: str | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: GptOssRendererConfig | None = None,
|
||||
):
|
||||
"""Initialise the renderer.
|
||||
|
||||
Args:
|
||||
tokenizer: HuggingFace tokenizer.
|
||||
use_system_prompt: When True (default), prepend the canonical
|
||||
harmony SystemContent preamble. Matches HF's
|
||||
apply_chat_template behaviour.
|
||||
reasoning_effort: ``"low" | "medium" | "high"``. Default
|
||||
``"medium"`` (matches apply_chat_template).
|
||||
conversation_start_date: Optional ISO date for the preamble.
|
||||
Defaults to today's date in YYYY-MM-DD form.
|
||||
knowledge_cutoff: Optional knowledge cutoff string. Harmony's
|
||||
default is built into ``SystemContent.new()``.
|
||||
model_identity: Optional override for the model identity line.
|
||||
config: Typed renderer config (see
|
||||
:class:`renderers.GptOssRendererConfig`).
|
||||
"""
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or GptOssRendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"tool_cycle" if self.config.auto_drop_analysis else "all",
|
||||
)
|
||||
self._enc: HarmonyEncoding = load_harmony_encoding(
|
||||
HarmonyEncodingName.HARMONY_GPT_OSS
|
||||
)
|
||||
self._use_system_prompt = use_system_prompt
|
||||
self._reasoning_effort = _reasoning_effort(reasoning_effort)
|
||||
self._conversation_start_date = (
|
||||
conversation_start_date or datetime.now().strftime("%Y-%m-%d")
|
||||
)
|
||||
self._knowledge_cutoff = knowledge_cutoff
|
||||
self._model_identity = model_identity
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
# Materialised harmony-enum form of reasoning_effort.
|
||||
self._reasoning_effort_enum = _reasoning_effort(self.config.reasoning_effort)
|
||||
# ``conversation_start_date=None`` defers to today's date —
|
||||
# materialise once at construction so renders within the same
|
||||
# instance use a stable date.
|
||||
self._conversation_start_date_resolved = (
|
||||
self.config.conversation_start_date or datetime.now().strftime("%Y-%m-%d")
|
||||
)
|
||||
|
||||
# Cache special-token IDs for the bridge / generation-prompt path.
|
||||
@@ -184,6 +174,90 @@ class GptOssRenderer:
|
||||
return []
|
||||
return self._tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
def _prefix_content_mask(
|
||||
self,
|
||||
prefix_tokens: list[int],
|
||||
first_system_idx: int | None,
|
||||
messages: list[Message],
|
||||
tools: list[ToolSpec] | None,
|
||||
) -> list[bool]:
|
||||
"""Per-token is_content mask over the rendered system+developer prefix.
|
||||
|
||||
Harmony's prefix is one opaque block. The caller's system content
|
||||
lands inside the developer message as ``# Instructions\\n\\n{content}``.
|
||||
To attribute body bytes back, we render the same prefix with empty
|
||||
instructions and diff: the unique-to-with-instructions span is the
|
||||
body region. Falls back to all-False (whole prefix scaffold) if
|
||||
the caller didn't supply a system message — there's no body to
|
||||
attribute in that case.
|
||||
"""
|
||||
n = len(prefix_tokens)
|
||||
mask = [False] * n
|
||||
if first_system_idx is None:
|
||||
return mask
|
||||
instructions = _content_text(messages[first_system_idx].get("content"))
|
||||
if not instructions:
|
||||
return mask
|
||||
|
||||
# Build the same prefix with empty instructions.
|
||||
empty_prefix_msgs: list[HarmonyMessage] = []
|
||||
if self.config.use_system_prompt:
|
||||
sys_content = SystemContent.new().with_reasoning_effort(
|
||||
self._reasoning_effort_enum
|
||||
)
|
||||
sys_content = sys_content.with_conversation_start_date(
|
||||
self._conversation_start_date_resolved
|
||||
)
|
||||
if self.config.knowledge_cutoff is not None:
|
||||
sys_content = sys_content.with_knowledge_cutoff(
|
||||
self.config.knowledge_cutoff
|
||||
)
|
||||
if self.config.model_identity is not None:
|
||||
sys_content = sys_content.with_model_identity(
|
||||
self.config.model_identity
|
||||
)
|
||||
empty_prefix_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
|
||||
)
|
||||
dev = DeveloperContent.new()
|
||||
if tools:
|
||||
dev = dev.with_function_tools([_tool_to_description(t) for t in tools])
|
||||
empty_prefix_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev)
|
||||
)
|
||||
try:
|
||||
empty_tokens = self._enc.render_conversation(
|
||||
Conversation.from_messages(empty_prefix_msgs)
|
||||
)
|
||||
except Exception:
|
||||
return mask
|
||||
|
||||
# Longest common prefix.
|
||||
i_start = 0
|
||||
n_empty = len(empty_tokens)
|
||||
while (
|
||||
i_start < min(n, n_empty)
|
||||
and prefix_tokens[i_start] == empty_tokens[i_start]
|
||||
):
|
||||
i_start += 1
|
||||
# Longest common suffix.
|
||||
j_full = n
|
||||
j_empty = n_empty
|
||||
while (
|
||||
j_full > i_start
|
||||
and j_empty > i_start
|
||||
and prefix_tokens[j_full - 1] == empty_tokens[j_empty - 1]
|
||||
):
|
||||
j_full -= 1
|
||||
j_empty -= 1
|
||||
# Tokens [i_start:j_full] in prefix_tokens are unique to the
|
||||
# with-instructions render — that's the body span (includes the
|
||||
# ``# Instructions\n\n`` scaffolding header, which the substring
|
||||
# match in the body-decode test ignores).
|
||||
for k in range(i_start, j_full):
|
||||
mask[k] = True
|
||||
return mask
|
||||
|
||||
# ── public interface ─────────────────────────────────────────────────────
|
||||
|
||||
def render(
|
||||
@@ -199,11 +273,15 @@ class GptOssRenderer:
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
|
||||
def emit(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_harmony_message(
|
||||
hm_ids: list[int], msg_idx: int, *, is_assistant: bool
|
||||
@@ -225,18 +303,53 @@ class GptOssRenderer:
|
||||
developer, tool) the whole message is conversation history
|
||||
the model never samples — every token is
|
||||
``is_sampled=False``.
|
||||
|
||||
``is_content`` further splits the body: the trailing
|
||||
terminator (``<|end|>`` / ``<|return|>`` / ``<|call|>``) is
|
||||
scaffold on non-assistant turns; on assistant turns it's the
|
||||
model's stop signal, so ``is_content=True`` mirrors
|
||||
``sampled_mask`` as the invariant on assistant requires.
|
||||
The body bytes between ``<|message|>`` and the terminator
|
||||
are body (``is_content=True``) on every role — that's the
|
||||
caller-provided content (or, for assistant, the model's
|
||||
sampled emission). The header (``<|start|>`` ... ``<|message|>``)
|
||||
— including any ``functions.{name}`` recipient text on tool
|
||||
results, which comes from a prior assistant's tool_calls
|
||||
rather than this tool message's own content — is scaffold.
|
||||
"""
|
||||
try:
|
||||
msg_marker = hm_ids.index(self._message)
|
||||
except ValueError:
|
||||
# Defensive: a harmony message without <|message|> is
|
||||
# malformed. Treat the whole thing as scaffolding.
|
||||
emit(hm_ids, msg_idx, is_sampled=False)
|
||||
emit(hm_ids, msg_idx, is_sampled=False, is_content=False)
|
||||
return
|
||||
header = hm_ids[: msg_marker + 1]
|
||||
body = hm_ids[msg_marker + 1 :]
|
||||
emit(header, msg_idx, is_sampled=False)
|
||||
emit(body, msg_idx, is_sampled=is_assistant)
|
||||
emit(header, msg_idx, is_sampled=False, is_content=False)
|
||||
# Split body into content + terminator. The terminator (if
|
||||
# present) is the last token of the body and is one of the
|
||||
# three harmony stop tokens.
|
||||
terminator_ids = {self._end, self._return, self._call}
|
||||
if body and body[-1] in terminator_ids:
|
||||
body_content = body[:-1]
|
||||
terminator = body[-1:]
|
||||
else:
|
||||
body_content = body
|
||||
terminator = []
|
||||
emit(
|
||||
body_content,
|
||||
msg_idx,
|
||||
is_sampled=is_assistant,
|
||||
is_content=True,
|
||||
)
|
||||
if terminator:
|
||||
emit(
|
||||
terminator,
|
||||
msg_idx,
|
||||
is_sampled=is_assistant,
|
||||
is_content=is_assistant,
|
||||
)
|
||||
|
||||
# ── Build harmony prefix (system + developer) ───────────────────
|
||||
# When tools are present, harmony's conversation-level renderer
|
||||
@@ -250,17 +363,21 @@ class GptOssRenderer:
|
||||
None,
|
||||
)
|
||||
prefix_msgs: list[HarmonyMessage] = []
|
||||
if self._use_system_prompt:
|
||||
if self.config.use_system_prompt:
|
||||
sys_content = SystemContent.new().with_reasoning_effort(
|
||||
self._reasoning_effort
|
||||
self._reasoning_effort_enum
|
||||
)
|
||||
sys_content = sys_content.with_conversation_start_date(
|
||||
self._conversation_start_date
|
||||
self._conversation_start_date_resolved
|
||||
)
|
||||
if self._knowledge_cutoff is not None:
|
||||
sys_content = sys_content.with_knowledge_cutoff(self._knowledge_cutoff)
|
||||
if self._model_identity is not None:
|
||||
sys_content = sys_content.with_model_identity(self._model_identity)
|
||||
if self.config.knowledge_cutoff is not None:
|
||||
sys_content = sys_content.with_knowledge_cutoff(
|
||||
self.config.knowledge_cutoff
|
||||
)
|
||||
if self.config.model_identity is not None:
|
||||
sys_content = sys_content.with_model_identity(
|
||||
self.config.model_identity
|
||||
)
|
||||
prefix_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
|
||||
)
|
||||
@@ -285,7 +402,23 @@ class GptOssRenderer:
|
||||
# caller-relative attribution); otherwise to -1 (pure scaffolding).
|
||||
# The whole prefix is pure template scaffolding — never sampled.
|
||||
prefix_origin = first_system_idx if first_system_idx is not None else -1
|
||||
emit(prefix_tokens, prefix_origin, is_sampled=False)
|
||||
# Compute the body-token span inside the prefix by diffing
|
||||
# against the same render with empty developer instructions.
|
||||
# Tokens unique to the with-instructions render are the body
|
||||
# span (``# Instructions\n\n{caller_system_content}``). Marking
|
||||
# those is_content=True so the caller's system text is
|
||||
# recoverable from ``content_token_spans_by_role()["system"]``.
|
||||
# The scaffolding ``# Instructions\n\n`` prefix bleeds into
|
||||
# the body run; consumers reading the body do a substring
|
||||
# check rather than expecting an exact match.
|
||||
prefix_content_mask = self._prefix_content_mask(
|
||||
prefix_tokens, first_system_idx, messages, tools
|
||||
)
|
||||
for tid, is_content in zip(prefix_tokens, prefix_content_mask):
|
||||
tokens.append(tid)
|
||||
indices.append(prefix_origin)
|
||||
sampled.append(False)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── Iterate the rest of the messages ────────────────────────────
|
||||
last_idx = len(messages) - 1
|
||||
@@ -293,14 +426,7 @@ class GptOssRenderer:
|
||||
if i == first_system_idx:
|
||||
continue # already emitted as developer
|
||||
is_assistant = msg.get("role") == "assistant"
|
||||
preserve_thinking = is_assistant and (
|
||||
should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
)
|
||||
)
|
||||
preserve_thinking = is_assistant and self._should_emit_analysis(messages, i)
|
||||
for hm in self._to_harmony_messages(
|
||||
msg, preserve_thinking=preserve_thinking
|
||||
):
|
||||
@@ -326,14 +452,19 @@ class GptOssRenderer:
|
||||
# ── Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
|
||||
# Pure template scaffolding the model continues from — never sampled.
|
||||
if add_generation_prompt:
|
||||
emit([self._start], -1, is_sampled=False)
|
||||
emit(self._encode("assistant"), -1, is_sampled=False)
|
||||
emit([self._channel], -1, is_sampled=False)
|
||||
emit(self._encode("analysis"), -1, is_sampled=False)
|
||||
emit([self._message], -1, is_sampled=False)
|
||||
emit([self._start], -1, is_sampled=False, is_content=False)
|
||||
emit(self._encode("assistant"), -1, is_sampled=False, is_content=False)
|
||||
emit([self._channel], -1, is_sampled=False, is_content=False)
|
||||
emit(self._encode("analysis"), -1, is_sampled=False, is_content=False)
|
||||
emit([self._message], -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -391,6 +522,12 @@ class GptOssRenderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
@@ -400,25 +537,94 @@ class GptOssRenderer:
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False``). The harmony encoder
|
||||
# renders each ``new_messages[i]`` as a single block, so every
|
||||
# token in that block carries index ``i``; the trailing
|
||||
# generation prompt uses ``-1``. ``is_content`` follows the same
|
||||
# rules as :meth:`render`'s ``emit_harmony_message``: header is
|
||||
# scaffold, body bytes are body, terminator scaffold (the bridge
|
||||
# never carries assistant turns, so terminators are always
|
||||
# scaffold on the non-assistant roles the bridge accepts).
|
||||
terminator_ids = {self._end, self._return, self._call}
|
||||
ext: list[int] = []
|
||||
for msg in new_messages:
|
||||
ext_indices: list[int] = []
|
||||
ext_content: list[bool] = []
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
if role not in ("tool", "user", "system", "developer"):
|
||||
return None
|
||||
for hm in self._to_harmony_messages(msg):
|
||||
ext.extend(self._enc.render(hm))
|
||||
ids = self._enc.render(hm)
|
||||
try:
|
||||
msg_marker = ids.index(self._message)
|
||||
except ValueError:
|
||||
# Defensive: treat as scaffolding.
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([i] * len(ids))
|
||||
ext_content.extend([False] * len(ids))
|
||||
continue
|
||||
header = ids[: msg_marker + 1]
|
||||
body = ids[msg_marker + 1 :]
|
||||
ext.extend(header)
|
||||
ext_indices.extend([i] * len(header))
|
||||
ext_content.extend([False] * len(header))
|
||||
if body and body[-1] in terminator_ids:
|
||||
body_content = body[:-1]
|
||||
terminator = body[-1:]
|
||||
else:
|
||||
body_content = body
|
||||
terminator = []
|
||||
ext.extend(body_content)
|
||||
ext_indices.extend([i] * len(body_content))
|
||||
ext_content.extend([True] * len(body_content))
|
||||
if terminator:
|
||||
ext.extend(terminator)
|
||||
ext_indices.extend([i] * len(terminator))
|
||||
ext_content.extend([False] * len(terminator))
|
||||
|
||||
# Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
|
||||
gen_before = len(ext)
|
||||
ext.append(self._start)
|
||||
ext.extend(self._encode("assistant"))
|
||||
ext.append(self._channel)
|
||||
ext.extend(self._encode("analysis"))
|
||||
ext.append(self._message)
|
||||
ext_indices.extend([-1] * (len(ext) - gen_before))
|
||||
ext_content.extend([False] * (len(ext) - gen_before))
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
# ── message conversion ───────────────────────────────────────────────────
|
||||
|
||||
def _should_emit_analysis(self, messages: list[Message], msg_idx: int) -> bool:
|
||||
"""Whether to render ``reasoning_content`` as a harmony analysis message."""
|
||||
if not self.config.auto_drop_analysis:
|
||||
return True
|
||||
|
||||
msg = messages[msg_idx]
|
||||
if not msg.get("tool_calls"):
|
||||
return False
|
||||
|
||||
# Harmony keeps analysis for an unfinished tool-call cycle, but once a
|
||||
# later final assistant answer is present it drops the stale analysis.
|
||||
for later in messages[msg_idx + 1 :]:
|
||||
if later.get("role") != "assistant":
|
||||
continue
|
||||
if later.get("tool_calls"):
|
||||
continue
|
||||
if _content_text(later.get("content")):
|
||||
return False
|
||||
return True
|
||||
|
||||
def _to_harmony_messages(
|
||||
self, msg: Message, *, preserve_thinking: bool = False
|
||||
) -> list[HarmonyMessage]:
|
||||
@@ -488,8 +694,9 @@ class GptOssRenderer:
|
||||
its analysis block is dropped from context.
|
||||
|
||||
``preserve_thinking=True``: prepend an analysis-channel message
|
||||
carrying ``reasoning_content`` so callers that want the trace in
|
||||
history (e.g. tool-call-chain training) see it surface.
|
||||
carrying ``reasoning_content``. The render path sets this from
|
||||
harmony's own ``auto_drop_analysis`` behaviour, not from generic
|
||||
``thinking_retention``.
|
||||
"""
|
||||
out: list[HarmonyMessage] = []
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Text-level Hermes calls, excluding reasoning and Markdown code examples."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from renderers.base import ParsedToolCall, ToolCallParseStatus
|
||||
|
||||
_THINK = re.compile(r"</?think>", re.IGNORECASE)
|
||||
_OPEN = "<tool_call>"
|
||||
_CLOSE = "</tool_call>"
|
||||
|
||||
|
||||
def _reject_constant(value: str) -> None:
|
||||
raise ValueError(f"Non-JSON numeric constant: {value}")
|
||||
|
||||
|
||||
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError(f"Duplicate JSON key: {key}")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
_JSON = json.JSONDecoder(parse_constant=_reject_constant, object_pairs_hook=_unique_object)
|
||||
|
||||
|
||||
def _token_boundary(tokenizer, ids: list[int], offset: int, *, end: bool) -> int:
|
||||
"""Cover every token overlapping the character span, including boundary merges."""
|
||||
low, high = 0, len(ids)
|
||||
while low < high:
|
||||
mid = (low + high) // 2
|
||||
if len(tokenizer.decode(ids[:mid], skip_special_tokens=False)) < offset:
|
||||
low = mid + 1
|
||||
else:
|
||||
high = mid
|
||||
if not end and len(tokenizer.decode(ids[:low], skip_special_tokens=False)) > offset:
|
||||
return max(0, low - 1)
|
||||
return low
|
||||
|
||||
|
||||
def _skip_reasoning(text: str, start: int) -> int:
|
||||
depth = 0
|
||||
for match in _THINK.finditer(text, start):
|
||||
depth += -1 if match.group().startswith("</") else 1
|
||||
if depth == 0:
|
||||
return match.end()
|
||||
return len(text)
|
||||
|
||||
|
||||
def _read_block(text: str, start: int) -> tuple[int, str, Any, ToolCallParseStatus]:
|
||||
body = start + len(_OPEN)
|
||||
while body < len(text) and text[body].isspace():
|
||||
body += 1
|
||||
try:
|
||||
payload, json_end = _JSON.raw_decode(text, body)
|
||||
except ValueError:
|
||||
close = text.find(_CLOSE, body)
|
||||
if close < 0:
|
||||
return len(text), text[body:].strip(), None, ToolCallParseStatus.UNCLOSED_BLOCK
|
||||
return close + len(_CLOSE), text[body:close].strip(), None, ToolCallParseStatus.INVALID_JSON
|
||||
close = json_end
|
||||
while close < len(text) and text[close].isspace():
|
||||
close += 1
|
||||
if not text.startswith(_CLOSE, close):
|
||||
closing = text.find(_CLOSE, close)
|
||||
if closing < 0:
|
||||
return len(text), text[body:].strip(), None, ToolCallParseStatus.UNCLOSED_BLOCK
|
||||
return closing + len(_CLOSE), text[body:closing].strip(), None, ToolCallParseStatus.MALFORMED_STRUCTURE
|
||||
status = ToolCallParseStatus.OK
|
||||
if (
|
||||
not isinstance(payload, dict)
|
||||
or not isinstance(payload.get("name"), str)
|
||||
or not payload["name"].strip()
|
||||
or not isinstance(payload.get("arguments"), dict)
|
||||
):
|
||||
status = ToolCallParseStatus.MALFORMED_STRUCTURE
|
||||
return close + len(_CLOSE), text[body:json_end], payload, status
|
||||
|
||||
|
||||
class HermesToolParser:
|
||||
"""Parse native Hermes envelopes without promoting quoted examples into actions."""
|
||||
|
||||
def __init__(self, tokenizer):
|
||||
self._tokenizer = tokenizer
|
||||
self._starts_in_reasoning = False
|
||||
|
||||
def configure_prefill(self, template_kwargs: dict[str, Any]) -> None:
|
||||
"""Honor templates that put the opening reasoning tag in the prompt."""
|
||||
if not hasattr(self._tokenizer, "apply_chat_template"):
|
||||
return
|
||||
kwargs = {**template_kwargs, "add_generation_prompt": True, "tokenize": False, "return_dict": False}
|
||||
prompt = self._tokenizer.apply_chat_template([{"role": "user", "content": "Hello"}], **kwargs)
|
||||
self._starts_in_reasoning = bool(re.search(r"<think>\s*$", prompt, re.IGNORECASE))
|
||||
|
||||
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
|
||||
text = self._tokenizer.decode(ids, skip_special_tokens=False)
|
||||
if _OPEN not in text:
|
||||
return ids, []
|
||||
# Some chat templates prefill <think>; the generated tokens then start
|
||||
# inside reasoning and contain only its closing delimiter.
|
||||
first_think = _THINK.search(text)
|
||||
if self._starts_in_reasoning and first_think is None:
|
||||
return ids, []
|
||||
cursor = first_think.end() if first_think and first_think.group().startswith("</") else 0
|
||||
kept, calls = [], []
|
||||
previous = 0
|
||||
while cursor < len(text):
|
||||
if text[cursor : cursor + 7].lower() == "<think>":
|
||||
cursor = _skip_reasoning(text, cursor)
|
||||
continue
|
||||
if text[cursor] == "`" or text.startswith("~~~", cursor):
|
||||
end = cursor + 1
|
||||
while end < len(text) and text[end] == text[cursor]:
|
||||
end += 1
|
||||
marker = text[cursor:end]
|
||||
close = text.find(marker, end)
|
||||
cursor = len(text) if close < 0 else close + len(marker)
|
||||
continue
|
||||
if not text.startswith(_OPEN, cursor):
|
||||
cursor += 1
|
||||
continue
|
||||
end, raw, payload, status = _read_block(text, cursor)
|
||||
span = (
|
||||
_token_boundary(self._tokenizer, ids, cursor, end=False),
|
||||
_token_boundary(self._tokenizer, ids, end, end=True),
|
||||
)
|
||||
calls.append(
|
||||
ParsedToolCall(
|
||||
raw=raw,
|
||||
token_span=span,
|
||||
status=status,
|
||||
name=payload["name"] if status == ToolCallParseStatus.OK else None,
|
||||
arguments=payload["arguments"] if status == ToolCallParseStatus.OK else None,
|
||||
)
|
||||
)
|
||||
kept.append(text[previous:cursor])
|
||||
previous = cursor = end
|
||||
if not calls:
|
||||
return ids, []
|
||||
kept.append(text[previous:])
|
||||
# Re-encode retained text so BPE tokens crossing envelope boundaries do
|
||||
# not swallow adjacent text. Spans above always refer to the original ids.
|
||||
content_ids = self._tokenizer.encode("".join(kept), add_special_tokens=False)
|
||||
return content_ids, calls
|
||||
@@ -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),
|
||||
)
|
||||
+212
-87
@@ -23,33 +23,38 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import KimiK2RendererConfig
|
||||
from renderers.parsing import parse_kimi_k2
|
||||
|
||||
_DEFAULT_SYSTEM = "You are Kimi, an AI assistant created by Moonshot AI."
|
||||
|
||||
|
||||
class KimiK2Renderer:
|
||||
"""Deterministic message → token renderer for Kimi K2 models."""
|
||||
"""Deterministic message → token renderer for Kimi K2 models.
|
||||
|
||||
Kimi K2's chat template doesn't read any thinking-related variable —
|
||||
``content`` renders verbatim with no reasoning branch. The
|
||||
``enable_thinking`` / ``thinking_retention`` fields on the config are
|
||||
stored for protocol uniformity with the rest of the renderer family
|
||||
but have no effect on the byte-level output.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: KimiK2RendererConfig | None = None,
|
||||
):
|
||||
# Kimi-K2's chat template doesn't read ``reasoning_content`` for
|
||||
# past assistant turns, so the override flags are no-ops. Stored
|
||||
# for introspection / Protocol parity only.
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or KimiK2RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
|
||||
self._im_user = self._token_id("<|im_user|>")
|
||||
@@ -118,6 +123,11 @@ class KimiK2Renderer:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
# Preserve the caller's list — ``message_roles`` and per-token
|
||||
# attribution refer to this frame (not the post-normalisation
|
||||
# list that includes auto-injected system / tool_declare).
|
||||
caller_messages = list(messages)
|
||||
|
||||
# Inject tools as tool_declare message + ensure system message.
|
||||
# The Jinja template emits the tools list directly (no
|
||||
# ``{"type":"function","function":...}`` wrapper) using
|
||||
@@ -166,19 +176,33 @@ class KimiK2Renderer:
|
||||
token_ids: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
token_ids.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
token_ids.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) -> None:
|
||||
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
# Compute last non-tool-call assistant index to determine thinking preservation
|
||||
last_plain_assistant_idx = -1
|
||||
@@ -206,31 +230,40 @@ class KimiK2Renderer:
|
||||
content = "".join(parts)
|
||||
|
||||
oi = orig_idx(i)
|
||||
# Auto-injected system / tool_declare messages have ``oi == -1``.
|
||||
# Their text isn't from the caller's input, so we treat the
|
||||
# whole emission as scaffold (``is_content=False`` everywhere).
|
||||
# The test contract is that ``msg_idx == -1`` runs are
|
||||
# template-only and ``is_content=False``.
|
||||
body_is_content = oi >= 0
|
||||
|
||||
if role == "system":
|
||||
emit_special(self._im_system, oi, is_sampled=False)
|
||||
emit_text("system", oi, is_sampled=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False)
|
||||
emit_text(content, oi, is_sampled=False)
|
||||
emit_special(self._im_end, oi, is_sampled=False)
|
||||
emit_special(self._im_system, oi, is_sampled=False, is_content=False)
|
||||
emit_text("system", oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
|
||||
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
# Jinja emits a literal newline only after the auto-injected
|
||||
# system's <|im_end|> (see _ensure_system_message's contract).
|
||||
if i == auto_system_idx:
|
||||
emit_text("\n", oi, is_sampled=False)
|
||||
emit_text("\n", oi, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "tool_declare":
|
||||
emit_special(self._im_system, oi, is_sampled=False)
|
||||
emit_text("tool_declare", oi, is_sampled=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False)
|
||||
emit_text(content, oi, is_sampled=False)
|
||||
emit_special(self._im_end, oi, is_sampled=False)
|
||||
# The tool_declare body is the tools JSON — recoverable
|
||||
# from the caller's ``tools`` argument, so we treat it as
|
||||
# scaffold (consistent with Qwen3's tools-header block).
|
||||
emit_special(self._im_system, oi, is_sampled=False, is_content=False)
|
||||
emit_text("tool_declare", oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
|
||||
emit_text(content, oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._im_user, oi, is_sampled=False)
|
||||
emit_text("user", oi, is_sampled=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False)
|
||||
emit_text(content, oi, is_sampled=False)
|
||||
emit_special(self._im_end, oi, is_sampled=False)
|
||||
emit_special(self._im_user, oi, is_sampled=False, is_content=False)
|
||||
emit_text("user", oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
|
||||
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
# Kimi strips reasoning from historical assistant turns and
|
||||
@@ -250,27 +283,36 @@ class KimiK2Renderer:
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
msg, oi, content, emit_special=emit_special, emit_text=emit_text
|
||||
msg,
|
||||
oi,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
|
||||
else:
|
||||
# Unknown role: use system-style formatting. Not a sampled
|
||||
# assistant turn — every token is template-injected from the
|
||||
# caller's POV, so is_sampled=False across the whole emission.
|
||||
emit_special(self._im_system, oi, is_sampled=False)
|
||||
emit_text(role, oi, is_sampled=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False)
|
||||
emit_text(content, oi, is_sampled=False)
|
||||
emit_special(self._im_end, oi, is_sampled=False)
|
||||
emit_special(self._im_system, oi, is_sampled=False, is_content=False)
|
||||
emit_text(role, oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
|
||||
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
|
||||
# Generation prompt
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_assistant, -1, is_sampled=False)
|
||||
emit_text("assistant", -1, is_sampled=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False)
|
||||
emit_special(self._im_assistant, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=token_ids, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=token_ids,
|
||||
message_indices=indices,
|
||||
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(
|
||||
@@ -320,6 +362,11 @@ class KimiK2Renderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
@@ -331,21 +378,42 @@ class KimiK2Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the caller
|
||||
# blanket-masks it via ``prompt_mask=[False]*N``, so we don't track
|
||||
# sampled_mask here. Local helpers accept the kwarg for signature
|
||||
# compatibility with ``_render_tool`` and ignore it; the returned
|
||||
# ``RenderedTokens`` leaves ``sampled_mask`` empty.
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
@@ -365,30 +433,42 @@ class KimiK2Renderer:
|
||||
content = "".join(parts)
|
||||
|
||||
if role == "user":
|
||||
emit_special(self._im_user, i, is_sampled=False)
|
||||
emit_text("user", i, is_sampled=False)
|
||||
emit_special(self._im_middle, i, is_sampled=False)
|
||||
emit_text(content, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False)
|
||||
emit_special(self._im_user, i)
|
||||
emit_text("user", i)
|
||||
emit_special(self._im_middle, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
emit_special(self._im_end, i)
|
||||
elif role == "system":
|
||||
emit_special(self._im_system, i, is_sampled=False)
|
||||
emit_text("system", i, is_sampled=False)
|
||||
emit_special(self._im_middle, i, is_sampled=False)
|
||||
emit_text(content, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False)
|
||||
emit_special(self._im_system, i)
|
||||
emit_text("system", i)
|
||||
emit_special(self._im_middle, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
emit_special(self._im_end, i)
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
msg, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
# Generation prompt.
|
||||
emit_special(self._im_assistant, -1, is_sampled=False)
|
||||
emit_text("assistant", -1, is_sampled=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False)
|
||||
emit_special(self._im_assistant, -1)
|
||||
emit_text("assistant", -1)
|
||||
emit_special(self._im_middle, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -404,23 +484,32 @@ class KimiK2Renderer:
|
||||
# scaffolding — at inference the chat template emits these as the
|
||||
# generation prompt and the model never samples them. Marking the
|
||||
# role tag as ``is_sampled=False`` keeps the SFT loss mask aligned
|
||||
# with what the model would actually have produced.
|
||||
emit_special(self._im_assistant, msg_idx, is_sampled=False)
|
||||
emit_text("assistant", msg_idx, is_sampled=False)
|
||||
emit_special(self._im_middle, msg_idx, is_sampled=False)
|
||||
# with what the model would actually have produced. ``is_content``
|
||||
# is also False here — the role tag isn't part of any message's
|
||||
# body, on any role.
|
||||
emit_special(self._im_assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Kimi K2's Jinja template has no reasoning-content support: the
|
||||
# assistant turn renders its ``content`` verbatim, including any
|
||||
# inline ``<think>...</think>`` tags. The separate
|
||||
# ``reasoning_content`` field is dropped (the template never reads
|
||||
# it). ``is_last_turn`` is unused here for the same reason.
|
||||
# On assistant tokens, ``is_content == sampled_mask`` by construction
|
||||
# — every sampled token is body, every scaffold token isn't.
|
||||
_ = is_last_turn
|
||||
emit_text(content, msg_idx, is_sampled=True)
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool calls
|
||||
# Tool calls — model-sampled markup carrying caller / model body.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
if tool_calls:
|
||||
emit_special(self._tool_calls_section_begin, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._tool_calls_section_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
arguments = func.get("arguments", {})
|
||||
@@ -434,16 +523,37 @@ class KimiK2Renderer:
|
||||
# caller to provide an id in ``functions.{name}:{idx}`` form
|
||||
# (that's where the Kimi parser recovers the function name).
|
||||
tc_id = tc.get("id") or ""
|
||||
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
|
||||
emit_text(tc_id, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_argument_begin, msg_idx, is_sampled=True)
|
||||
emit_text(args_str, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_calls_section_end, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._tool_call_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_text(tc_id, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_argument_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_text(args_str, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_calls_section_end,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
# ``<|im_end|>`` is the model's stop signal — it samples this to
|
||||
# end its turn, so it is part of the sampled stream.
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True)
|
||||
# end its turn, so it is part of the sampled stream (and the
|
||||
# assistant's body).
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -456,13 +566,28 @@ class KimiK2Renderer:
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False.
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# field's body bytes get ``is_content=True``; everything else —
|
||||
# the ``<|im_system|>name<|im_middle|>`` wrap, the ``## Return of
|
||||
# …\n`` header (template-synthesised, not part of the body) —
|
||||
# is scaffold so the SFT mask for tool body never trains the
|
||||
# model to emit them.
|
||||
#
|
||||
# We keep the original kimi_k2 emit boundaries — the header and
|
||||
# the content are encoded separately, which preserves the
|
||||
# template's byte-identity since the original code also emitted
|
||||
# them as separate ``encode`` calls.
|
||||
name = msg.get("name") or "tool"
|
||||
tool_call_id = msg.get("tool_call_id") or ""
|
||||
|
||||
emit_special(self._im_system, msg_idx, is_sampled=False)
|
||||
emit_text(name, msg_idx, is_sampled=False)
|
||||
emit_special(self._im_middle, msg_idx, is_sampled=False)
|
||||
emit_text(f"## Return of {tool_call_id}\n", msg_idx, is_sampled=False)
|
||||
emit_text(content, msg_idx, is_sampled=False)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False)
|
||||
emit_special(self._im_system, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text(name, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text(
|
||||
f"## Return of {tool_call_id}\n",
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
emit_text(content, msg_idx, is_sampled=False, is_content=True)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+265
-105
@@ -36,11 +36,14 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolCallParseStatus,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.parsing import parse_kimi_k2_section
|
||||
from renderers.configs import KimiK25RendererConfig
|
||||
from renderers.parsing import _reasoning_end_token_index, parse_kimi_k2_section
|
||||
from renderers.qwen3_vl import (
|
||||
_image_hash,
|
||||
_is_image_part,
|
||||
@@ -213,7 +216,9 @@ class _EnumType(_BaseType):
|
||||
self.enum = schema["enum"]
|
||||
|
||||
def to_typescript_style(self, indent: str = "") -> str:
|
||||
return " | ".join(f'"{e}"' if isinstance(e, str) else str(e) for e in self.enum)
|
||||
return " | ".join(
|
||||
f'"{e}"' if isinstance(e, str) else json.dumps(e) for e in self.enum
|
||||
)
|
||||
|
||||
|
||||
class _AnyOfType(_BaseType):
|
||||
@@ -283,11 +288,7 @@ class _TypedParam:
|
||||
def to_typescript_style(self, indent: str = "") -> str:
|
||||
comments = self.type_.format_docstring(indent)
|
||||
if self.default is not None:
|
||||
default_repr = (
|
||||
json.dumps(self.default, ensure_ascii=False)
|
||||
if not isinstance(self.default, (int, float, bool))
|
||||
else repr(self.default)
|
||||
)
|
||||
default_repr = json.dumps(self.default, ensure_ascii=False)
|
||||
comments += f"{indent}// Default: {default_repr}\n"
|
||||
opt = "?" if self.optional else ""
|
||||
return (
|
||||
@@ -452,6 +453,13 @@ def _parse_kimi_k2_response(
|
||||
ids = ids[:i]
|
||||
break
|
||||
|
||||
# Reasoning first: a tool-call section the model drafts *inside* its
|
||||
# <think> trace must not be parsed as a real call (regression #78 — cf.
|
||||
# parse_qwen3). K2.5 renders </think> as text, so locate the boundary by
|
||||
# decoding; the section scan then starts past it. content_ids still begins
|
||||
# at 0, so the </think> text-split below recovers reasoning unchanged.
|
||||
reasoning_end = _reasoning_end_token_index(tokenizer, ids)
|
||||
|
||||
# Token-ID path — produces spans. Only run if every relevant special
|
||||
# token resolved at init (i.e. is in the tokenizer's vocab).
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
@@ -471,6 +479,7 @@ def _parse_kimi_k2_response(
|
||||
tool_call_begin_id=tool_call_begin_id,
|
||||
tool_call_argument_begin_id=tool_call_argument_begin_id,
|
||||
tool_call_end_id=tool_call_end_id,
|
||||
scan_start=reasoning_end,
|
||||
)
|
||||
text = (
|
||||
tokenizer.decode(content_ids, skip_special_tokens=False)
|
||||
@@ -481,9 +490,13 @@ def _parse_kimi_k2_response(
|
||||
text = tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
|
||||
|
||||
# Fallback path: model emitted literal-text section delimiters (singular
|
||||
# variant) rather than special tokens. Spans unavailable here.
|
||||
# variant) rather than special tokens. Spans unavailable here. Start the
|
||||
# search past the first </think> so a literal section drafted inside the
|
||||
# reasoning trace isn't matched as a real call (regression #78).
|
||||
if not tool_calls:
|
||||
tc_match = _TOOL_CALLS_SECTION_RE.search(text)
|
||||
think_close = text.find("</think>")
|
||||
search_from = think_close + len("</think>") if think_close != -1 else 0
|
||||
tc_match = _TOOL_CALLS_SECTION_RE.search(text, search_from)
|
||||
if tc_match:
|
||||
text = text[: tc_match.start()]
|
||||
tool_section = (
|
||||
@@ -564,8 +577,13 @@ class KimiK25Renderer:
|
||||
"""Deterministic message → token renderer for Kimi K2.5 models.
|
||||
|
||||
Renders to the same ``<|im_*|>`` format as Kimi K2 but adds:
|
||||
- Generation prompt prefills ``<think>`` (enable_thinking=True, default) or
|
||||
``<think></think>`` (enable_thinking=False) to control thinking mode.
|
||||
- Generation prompt prefills ``<think>`` (thinking=True, default) or
|
||||
``<think></think>`` (thinking=False) to control thinking mode. The
|
||||
template's native kwarg name is ``thinking`` (not the more common
|
||||
``enable_thinking``); we mirror it on
|
||||
:class:`renderers.KimiK25RendererConfig` so
|
||||
``KimiK25RendererConfig(thinking=False)`` produces the same tokens
|
||||
as ``apply_chat_template(..., thinking=False)``.
|
||||
- Image content rendering via ``<|media_begin|>image<|media_content|>...<|media_end|>``.
|
||||
- TypeScript-style tool declarations instead of JSON.
|
||||
|
||||
@@ -575,19 +593,16 @@ class KimiK25Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: KimiK25RendererConfig | None = None,
|
||||
*,
|
||||
processor: Any = None,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
image_cache_max: int = 256,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or KimiK25RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"tool_cycle" if self.config.thinking else "all",
|
||||
)
|
||||
|
||||
# Core structural tokens — all must be single special tokens in the vocab
|
||||
@@ -629,7 +644,6 @@ class KimiK25Renderer:
|
||||
# for Kimi (we emit a single placeholder regardless), but kept for
|
||||
# consistency / debugging.
|
||||
self._image_cache: dict[str, tuple[Any, int]] = {}
|
||||
self._image_cache_max = image_cache_max
|
||||
|
||||
@property
|
||||
def mm_token_type_id_map(self) -> dict[int, int]:
|
||||
@@ -681,7 +695,7 @@ class KimiK25Renderer:
|
||||
# Patch count via the processor's own calculator (matches the
|
||||
# model's per-patch attention count); kept for debugging.
|
||||
num_patches = int(img_proc.media_tokens_calculator(media_item))
|
||||
if len(self._image_cache) >= self._image_cache_max:
|
||||
if len(self._image_cache) >= self.config.image_cache_max:
|
||||
self._image_cache.pop(next(iter(self._image_cache)))
|
||||
self._image_cache[h] = (out, num_patches)
|
||||
return pil, out, num_patches, h
|
||||
@@ -749,24 +763,44 @@ class KimiK25Renderer:
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
mm_hashes: dict[str, list[str]] = {}
|
||||
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
mm_items: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
|
||||
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) -> None:
|
||||
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
def emit_image(part: dict[str, Any], msg_idx: int, *, is_sampled: bool) -> None:
|
||||
def emit_image(
|
||||
part: dict[str, Any],
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_sampled: bool,
|
||||
is_content: bool,
|
||||
) -> None:
|
||||
"""Emit Kimi K2.5's image wrap and accumulate ``mm_data``.
|
||||
|
||||
Template-equivalent expansion per image:
|
||||
@@ -779,15 +813,32 @@ class KimiK25Renderer:
|
||||
Kimi's chat template after every image — kept here verbatim
|
||||
for byte-parity, regardless of what follows (more images,
|
||||
text, or the ``<|im_end|>`` close).
|
||||
|
||||
``is_content`` attribution: ``<|media_pad|>`` represents
|
||||
caller-provided image data — body. The wrap tokens
|
||||
(``<|media_begin|>``, the literal ``"image"`` prose,
|
||||
``<|media_content|>``, ``<|media_end|>``, the trailing
|
||||
``\\n``) are template-injected scaffold.
|
||||
"""
|
||||
_, out, _num_patches, h = self._process_image(part)
|
||||
emit_special(self._media_begin, msg_idx, is_sampled=is_sampled)
|
||||
emit_text("image", msg_idx, is_sampled=is_sampled)
|
||||
emit_special(self._media_content, msg_idx, is_sampled=is_sampled)
|
||||
emit_special(
|
||||
self._media_begin, msg_idx, is_sampled=is_sampled, is_content=False
|
||||
)
|
||||
emit_text("image", msg_idx, is_sampled=is_sampled, is_content=False)
|
||||
emit_special(
|
||||
self._media_content, msg_idx, is_sampled=is_sampled, is_content=False
|
||||
)
|
||||
offset = len(tokens)
|
||||
emit_special(self._media_pad, msg_idx, is_sampled=is_sampled)
|
||||
emit_special(self._media_end, msg_idx, is_sampled=is_sampled)
|
||||
emit_text("\n", msg_idx, is_sampled=is_sampled)
|
||||
emit_special(
|
||||
self._media_pad,
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
emit_special(
|
||||
self._media_end, msg_idx, is_sampled=is_sampled, is_content=False
|
||||
)
|
||||
emit_text("\n", msg_idx, is_sampled=is_sampled, is_content=False)
|
||||
mm_hashes.setdefault("image", []).append(h)
|
||||
mm_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=1)
|
||||
@@ -807,13 +858,16 @@ class KimiK25Renderer:
|
||||
# K2.5/K2.6's tokenizer auto-computes ``tools_ts_str`` and threads
|
||||
# it into apply_chat_template, so the template's TS branch always
|
||||
# fires when tools are present. Match that with our own TS encoder.
|
||||
# The tools-TS body is recoverable from the ``tools`` argument, so
|
||||
# we attribute the entire tool_declare emission as scaffold —
|
||||
# consistent with Qwen3's tools-header treatment.
|
||||
if tools:
|
||||
tools_ts = _encode_tools_typescript(tools)
|
||||
emit_special(self._im_system, -1, is_sampled=False)
|
||||
emit_text("tool_declare", -1, is_sampled=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False)
|
||||
emit_text(tools_ts, -1, is_sampled=False)
|
||||
emit_special(self._im_end, -1, is_sampled=False)
|
||||
emit_special(self._im_system, -1, is_sampled=False, is_content=False)
|
||||
emit_text("tool_declare", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
|
||||
emit_text(tools_ts, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Iterate messages ─────────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
@@ -824,38 +878,31 @@ class KimiK25Renderer:
|
||||
# generation prompt emits them at inference for assistants;
|
||||
# user / system / tool roles are conversation history).
|
||||
if role == "user":
|
||||
emit_special(self._im_user, i, is_sampled=False)
|
||||
emit_special(self._im_user, i, is_sampled=False, is_content=False)
|
||||
elif role == "assistant":
|
||||
emit_special(self._im_assistant, i, is_sampled=False)
|
||||
emit_special(self._im_assistant, i, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._im_system, i, is_sampled=False)
|
||||
emit_special(self._im_system, i, is_sampled=False, is_content=False)
|
||||
role_name = msg.get("name") or role
|
||||
emit_text(role_name, i, is_sampled=False)
|
||||
emit_special(self._im_middle, i, is_sampled=False)
|
||||
emit_text(role_name, i, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, i, is_sampled=False, is_content=False)
|
||||
|
||||
# Body
|
||||
if role == "assistant":
|
||||
is_suffix = i > last_non_tc_assistant
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant_body(
|
||||
msg,
|
||||
i,
|
||||
is_suffix=is_suffix,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
# ``<|im_end|>`` is the model's stop signal — it samples
|
||||
# this to end its turn, so it is part of the sampled
|
||||
# stream. Kimi K2.5 has no inter-turn ``\n`` separator
|
||||
# (unlike Qwen3), so the turn-close token is the last
|
||||
# sampled token.
|
||||
emit_special(self._im_end, i, is_sampled=True)
|
||||
# stream (and the assistant's body). Kimi K2.5 has no
|
||||
# inter-turn ``\n`` separator (unlike Qwen3), so the
|
||||
# turn-close token is the last sampled token.
|
||||
emit_special(self._im_end, i, is_sampled=True, is_content=True)
|
||||
continue
|
||||
elif role == "tool":
|
||||
self._render_tool_body(
|
||||
@@ -869,7 +916,8 @@ class KimiK25Renderer:
|
||||
elif msg.get("content") is not None:
|
||||
# User / other content branches — images allowed. All
|
||||
# non-assistant content is conversation history, never
|
||||
# sampled by the model.
|
||||
# sampled by the model. The body is caller-provided, so
|
||||
# ``is_content=True`` over the content emit.
|
||||
self._emit_content(
|
||||
msg.get("content"),
|
||||
i,
|
||||
@@ -878,21 +926,22 @@ class KimiK25Renderer:
|
||||
emit_ids,
|
||||
emit_image=emit_image,
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
emit_special(self._im_end, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Generation prompt ────────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_assistant, -1, is_sampled=False)
|
||||
emit_text("assistant", -1, is_sampled=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._im_assistant, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
|
||||
if self.config.thinking:
|
||||
# Prefill open <think> tag to trigger thinking mode
|
||||
emit_text("<think>", -1, is_sampled=False)
|
||||
emit_text("<think>", -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
# Empty <think></think> to disable thinking
|
||||
emit_text("<think></think>", -1, is_sampled=False)
|
||||
emit_text("<think></think>", -1, is_sampled=False, is_content=False)
|
||||
|
||||
mm_data: MultiModalData | None = None
|
||||
if mm_hashes or mm_placeholders or mm_items:
|
||||
@@ -906,6 +955,9 @@ class KimiK25Renderer:
|
||||
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),
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -982,6 +1034,12 @@ class KimiK25Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
close_ids: set[int] = {self._im_end}
|
||||
if self._endoftext is not None:
|
||||
close_ids.add(self._endoftext)
|
||||
@@ -995,44 +1053,77 @@ class KimiK25Renderer:
|
||||
return None
|
||||
|
||||
# Seed combined-token list with prior turn so placeholder offsets
|
||||
# are absolute in the bridged sequence.
|
||||
# are absolute in the bridged sequence. Parallel
|
||||
# ``indices``/``sampled``/``content_mask`` are seeded with
|
||||
# ``-1``/``False``/``False`` for the prior portion — the bridge
|
||||
# has no attribution info for ``previous_ids``. Bridge-added
|
||||
# tokens get proper ``msg_idx`` (relative to ``new_messages``)
|
||||
# and uniformly ``False`` ``sampled``: nothing the bridge emits
|
||||
# was model-sampled. ``is_content`` follows the same rules as in
|
||||
# :meth:`render` so consumers can walk the trajectory and read
|
||||
# each step's own body mask.
|
||||
tokens: list[int] = list(previous_ids)
|
||||
indices: list[int] = [-1] * len(previous_ids)
|
||||
sampled: list[bool] = [False] * len(previous_ids)
|
||||
content_mask: list[bool] = [False] * len(previous_ids)
|
||||
new_hashes: dict[str, list[str]] = {}
|
||||
new_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
new_items: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the caller
|
||||
# blanket-masks it via ``prompt_mask=[False]*N``, so we don't track
|
||||
# sampled_mask here. Local helpers accept the kwarg for signature
|
||||
# compatibility with ``_render_tool_body`` / ``_emit_content`` and
|
||||
# ignore it; the returned ``RenderedTokens`` leaves ``sampled_mask``
|
||||
# empty.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> 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 = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
tokens.extend(self._encode(text))
|
||||
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_ids(
|
||||
ids: list[int], _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
ids: list[int],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_image(
|
||||
part: dict[str, Any], _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
part: dict[str, Any],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
_, out, _num_patches, h = self._process_image(part)
|
||||
emit_special(self._media_begin)
|
||||
emit_text("image")
|
||||
emit_special(self._media_content)
|
||||
emit_special(self._media_begin, msg_idx)
|
||||
emit_text("image", msg_idx)
|
||||
emit_special(self._media_content, msg_idx)
|
||||
offset = len(tokens)
|
||||
emit_special(self._media_pad)
|
||||
emit_special(self._media_end)
|
||||
emit_text("\n")
|
||||
# ``<|media_pad|>`` stands in for caller-provided image data —
|
||||
# mark it as body when the surrounding content is body.
|
||||
emit_special(self._media_pad, msg_idx, is_content=is_content)
|
||||
emit_special(self._media_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
new_hashes.setdefault("image", []).append(h)
|
||||
new_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=1)
|
||||
@@ -1077,6 +1168,7 @@ class KimiK25Renderer:
|
||||
emit_ids,
|
||||
emit_image=emit_image,
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
emit_special(self._im_end, i)
|
||||
@@ -1085,24 +1177,26 @@ class KimiK25Renderer:
|
||||
emit_special(self._im_assistant, -1)
|
||||
emit_text("assistant", -1)
|
||||
emit_special(self._im_middle, -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.thinking:
|
||||
emit_text("<think>", -1)
|
||||
else:
|
||||
emit_text("<think></think>", -1)
|
||||
|
||||
# Merge prev mm_data (earlier-turn images) with the new turn's items.
|
||||
# Copy the per-modality lists (not just the outer dict) so appending
|
||||
# below never mutates the caller's previous_multi_modal_data.
|
||||
merged_hashes: dict[str, list[str]] = (
|
||||
dict(previous_multi_modal_data.mm_hashes)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_placeholders: dict[str, list[PlaceholderRange]] = (
|
||||
dict(previous_multi_modal_data.mm_placeholders)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_items: dict[str, list[dict[str, Any]]] = (
|
||||
dict(previous_multi_modal_data.mm_items)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
@@ -1113,8 +1207,17 @@ class KimiK25Renderer:
|
||||
for modality, vals in new_items.items():
|
||||
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)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
)
|
||||
|
||||
mm_data = MultiModalData(
|
||||
mm_hashes=merged_hashes,
|
||||
@@ -1123,7 +1226,11 @@ class KimiK25Renderer:
|
||||
)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=[-1] * len(tokens),
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -1141,6 +1248,7 @@ class KimiK25Renderer:
|
||||
*,
|
||||
emit_image=None,
|
||||
is_sampled: bool,
|
||||
is_content: bool = True,
|
||||
) -> None:
|
||||
"""Emit message content, handling strings, multipart lists, and (when
|
||||
``emit_image`` is supplied) image parts.
|
||||
@@ -1155,11 +1263,15 @@ class KimiK25Renderer:
|
||||
``bridge_to_next_turn``), so consecutive images naturally
|
||||
produce the template's ``...<|media_end|>\\n<|media_begin|>...``
|
||||
pattern without an inter-image separator here.
|
||||
|
||||
``is_content`` propagates to text emits and to the
|
||||
``<|media_pad|>`` body token of each image; the surrounding
|
||||
media wrap tokens are always scaffold (handled by ``emit_image``).
|
||||
"""
|
||||
if content is None:
|
||||
return
|
||||
if isinstance(content, str):
|
||||
emit_text(content, msg_idx, is_sampled=is_sampled)
|
||||
emit_text(content, msg_idx, is_sampled=is_sampled, is_content=is_content)
|
||||
return
|
||||
if isinstance(content, list):
|
||||
for part in content:
|
||||
@@ -1172,20 +1284,30 @@ class KimiK25Renderer:
|
||||
if emit_image is None:
|
||||
# Silently drop — caller didn't opt into multimodal.
|
||||
continue
|
||||
emit_image(part, msg_idx, is_sampled=is_sampled)
|
||||
emit_image(
|
||||
part, msg_idx, is_sampled=is_sampled, is_content=is_content
|
||||
)
|
||||
continue
|
||||
if is_video:
|
||||
raise NotImplementedError(
|
||||
"Video parts are not yet supported by KimiK25Renderer."
|
||||
)
|
||||
if ptype == "text":
|
||||
emit_text(part.get("text", ""), msg_idx, is_sampled=is_sampled)
|
||||
emit_text(
|
||||
part.get("text", ""),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
elif ptype == "thinking":
|
||||
# Thinking parts in non-assistant roles are rendered as text
|
||||
thinking = part.get("thinking", "")
|
||||
if thinking:
|
||||
emit_text(
|
||||
f"<think>{thinking}</think>", msg_idx, is_sampled=is_sampled
|
||||
f"<think>{thinking}</think>",
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
# Other part types are silently skipped
|
||||
|
||||
@@ -1195,7 +1317,6 @@ class KimiK25Renderer:
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_suffix: bool,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
) -> None:
|
||||
@@ -1248,16 +1369,27 @@ class KimiK25Renderer:
|
||||
# block, text content, and any tool_calls section all live in
|
||||
# the sampled stream. The closing ``<|im_end|>`` is emitted by
|
||||
# ``render`` (also is_sampled=True; it's the model's stop
|
||||
# signal).
|
||||
if is_suffix or (preserve_thinking and reasoning_content):
|
||||
emit_text(f"<think>{reasoning_content}</think>", msg_idx, is_sampled=True)
|
||||
# signal). On assistant tokens ``is_content == sampled_mask`` by
|
||||
# construction.
|
||||
if is_suffix:
|
||||
emit_text(
|
||||
f"<think>{reasoning_content}</think>",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
else:
|
||||
emit_text("<think></think>", msg_idx, is_sampled=True)
|
||||
emit_text(text_content, msg_idx, is_sampled=True)
|
||||
emit_text("<think></think>", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(text_content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
if tool_calls:
|
||||
emit_special(self._tool_calls_section_begin, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._tool_calls_section_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
arguments = func.get("arguments", {})
|
||||
@@ -1271,12 +1403,32 @@ class KimiK25Renderer:
|
||||
# ``functions.{name}:{idx}`` form (Kimi's parser recovers
|
||||
# the function name from that field).
|
||||
tool_id = tc.get("id") or ""
|
||||
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
|
||||
emit_text(tool_id, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_argument_begin, msg_idx, is_sampled=True)
|
||||
emit_text(args_str, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_calls_section_end, msg_idx, is_sampled=True)
|
||||
emit_special(
|
||||
self._tool_call_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_text(tool_id, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_argument_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_text(args_str, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_calls_section_end,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
def _render_tool_body(
|
||||
self,
|
||||
@@ -1302,9 +1454,16 @@ class KimiK25Renderer:
|
||||
"""
|
||||
# Tool messages are conversation-history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False.
|
||||
# tokens, so every emission is is_sampled=False. The ``## Return
|
||||
# of …\n`` header is template-synthesised scaffold; the
|
||||
# ``content`` body bytes get ``is_content=True``.
|
||||
tool_call_id = msg.get("tool_call_id") or ""
|
||||
emit_text(f"## Return of {tool_call_id}\n", msg_idx, is_sampled=False)
|
||||
emit_text(
|
||||
f"## Return of {tool_call_id}\n",
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
content = msg.get("content")
|
||||
if content is not None:
|
||||
self._emit_content(
|
||||
@@ -1315,6 +1474,7 @@ class KimiK25Renderer:
|
||||
emit_ids,
|
||||
emit_image=emit_image,
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
def _normalize_response_tokens(self, response: list[int]) -> list[int]:
|
||||
|
||||
+635
-85
@@ -1,4 +1,4 @@
|
||||
"""Laguna-XS.2 Renderer.
|
||||
"""Laguna-XS.2 / XS-2.1 Renderer.
|
||||
|
||||
Main properties:
|
||||
- Prefix is the single token ``〈|EOS|〉`` (also the EOS / stop token).
|
||||
@@ -12,15 +12,30 @@ Main properties:
|
||||
- Tool calls: ``<tool_call>`` / ``</tool_call>`` ARE single tokens, but the
|
||||
inner ``<arg_key>`` / ``</arg_key>`` / ``<arg_value>`` / ``</arg_value>``
|
||||
markers are plain text — parsed via regex on the decoded inner block.
|
||||
- The template bakes in a default system prompt when ``messages[0]`` is not
|
||||
a system message. The system block also contains the tools section (under
|
||||
a ``### Tools`` header with an ``<available_tools>`` listing and prose
|
||||
format instructions that vary on ``enable_thinking``).
|
||||
- Both templates bake in the same default Poolside system prompt when
|
||||
``messages[0]`` is not a system message; a caller-supplied system
|
||||
message overrides it, and an *empty* one opts out of the ``<system>``
|
||||
block entirely (absent tools). The system block also contains the
|
||||
tools section (under a ``### Tools`` header with an
|
||||
``<available_tools>`` listing).
|
||||
- Reasoning is rendered for every assistant message — no last-user-index
|
||||
gating. ``preserve_all_thinking`` and
|
||||
``preserve_thinking_between_tool_calls`` are accepted for protocol
|
||||
uniformity but are effectively no-ops since past reasoning is preserved
|
||||
by default.
|
||||
gating. ``thinking_retention`` is accepted for protocol uniformity but
|
||||
is effectively a no-op since past reasoning is preserved by default.
|
||||
|
||||
XS-2.1's template (upstream rev ``575f0f28``) is served by the
|
||||
:class:`LagunaXS21Renderer` subclass below:
|
||||
|
||||
- Role tags hug their content: ``<user>{content}</user>``, no inner
|
||||
newlines.
|
||||
- Assistant reasoning is gated on ``enable_thinking``: on, the turn
|
||||
opens ``<think>{reasoning}</think>`` verbatim (empty reasoning
|
||||
included); off, it opens with a bare ``</think>`` and message
|
||||
reasoning is not rendered. Content and tool-call args render verbatim.
|
||||
- Tool-call args pack tightly
|
||||
(``<arg_key>k</arg_key><arg_value>v</arg_value>``) and the tools
|
||||
section ends at ``</available_tools>``.
|
||||
- The ``<system>`` block is emitted whenever there is system content,
|
||||
tools, or ``enable_thinking`` — even if that leaves it empty.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,8 +50,13 @@ from renderers.base import (
|
||||
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 LagunaXS2RendererConfig, LagunaXS21RendererConfig
|
||||
from renderers.parsing import parse_laguna_xs2
|
||||
|
||||
_DEFAULT_SYSTEM_MESSAGE = (
|
||||
@@ -73,25 +93,32 @@ _TOOLS_FOOTER_NO_THINKING = (
|
||||
"</tool_call>"
|
||||
)
|
||||
|
||||
# XS-2.1 tools section: this header, one tojson line per tool, then a
|
||||
# bare "</available_tools>" close.
|
||||
_TOOLS_HEADER_XS21 = (
|
||||
"### Tools\n\n"
|
||||
"You may call functions to assist with the user query.\n"
|
||||
"All available function signatures are listed below:\n"
|
||||
"<available_tools>\n"
|
||||
)
|
||||
|
||||
|
||||
class LagunaXS2Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = False,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: LagunaXS2RendererConfig | LagunaXS21RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
# Accepted for protocol uniformity. The chat template renders
|
||||
# reasoning on every assistant message regardless, so flipping
|
||||
# these flags has no effect on the byte-level output.
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or LagunaXS2RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
# Both templates bake in the same default Poolside system prompt;
|
||||
# an empty caller-supplied system message opts out of the
|
||||
# <system> block (each variant's render mirrors its own gate).
|
||||
self._default_system_message = _DEFAULT_SYSTEM_MESSAGE
|
||||
|
||||
self._eos = self._token_id("〈|EOS|〉")
|
||||
self._think = self._token_id("<think>")
|
||||
@@ -154,24 +181,43 @@ class LagunaXS2Renderer:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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))
|
||||
|
||||
emit_special(self._eos, -1, is_sampled=False)
|
||||
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)
|
||||
|
||||
emit_special(self._eos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── System header (absorbs messages[0] if it's a system message) ──
|
||||
system_content = _DEFAULT_SYSTEM_MESSAGE
|
||||
system_content = self._default_system_message
|
||||
system_msg_idx = -1
|
||||
if messages and messages[0].get("role") == "system":
|
||||
caller_has_system = bool(messages and messages[0].get("role") == "system")
|
||||
if caller_has_system:
|
||||
system_content = self._visible_text(messages[0].get("content"))
|
||||
system_msg_idx = 0
|
||||
|
||||
@@ -180,27 +226,37 @@ class LagunaXS2Renderer:
|
||||
# gate: when the caller passes an empty system message and no tools,
|
||||
# the whole ``<system>...</system>`` block is omitted.
|
||||
if has_sys_content or tools:
|
||||
# The template emits ``<system>\n`` then conditionally a second
|
||||
# ``\n``. Bundle those into one emit so BPE merges ``\n\n`` into
|
||||
# its single-token form (rather than two ``\n`` atoms).
|
||||
emit_text(
|
||||
"<system>\n\n" if has_sys_content else "<system>\n",
|
||||
-1,
|
||||
is_sampled=False,
|
||||
)
|
||||
if has_sys_content:
|
||||
emit_text(system_content.rstrip(), system_msg_idx, is_sampled=False)
|
||||
# The template emits ``<system>\n`` then a second ``\n``
|
||||
# before the system body. Bundle those into one emit so BPE
|
||||
# merges ``\n\n`` into its single-token form (rather than
|
||||
# two ``\n`` atoms).
|
||||
emit_text("<system>\n\n", -1, is_sampled=False, is_content=False)
|
||||
# If the caller provided system content, it's body bytes;
|
||||
# otherwise this is the default system prompt (scaffold).
|
||||
sys_is_content = caller_has_system
|
||||
emit_text(
|
||||
system_content.rstrip(),
|
||||
system_msg_idx,
|
||||
is_sampled=False,
|
||||
is_content=sys_is_content,
|
||||
)
|
||||
if tools:
|
||||
tool_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
|
||||
tool_text += (
|
||||
_TOOLS_FOOTER_THINKING
|
||||
if self._enable_thinking
|
||||
if self.config.enable_thinking
|
||||
else _TOOLS_FOOTER_NO_THINKING
|
||||
)
|
||||
emit_text(tool_text, -1, is_sampled=False)
|
||||
emit_text("\n</system>\n", -1, is_sampled=False)
|
||||
if not has_sys_content:
|
||||
# No system body: ``<system>\n`` runs straight into the
|
||||
# tools header's ``\n\n`` — encode them together so BPE
|
||||
# merges the ``\n\n\n`` seam as the template does.
|
||||
tool_text = "<system>\n" + tool_text
|
||||
emit_text(tool_text, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n</system>\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Per-message loop ──────────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
@@ -211,33 +267,51 @@ class LagunaXS2Renderer:
|
||||
# Already consumed in the header block.
|
||||
if i == 0:
|
||||
continue
|
||||
emit_text(
|
||||
"<system>\n" + content + "\n</system>\n", i, is_sampled=False
|
||||
)
|
||||
# Body = caller's content; the ``<system>...</system>``
|
||||
# wrap and surrounding ``\n``s are scaffold.
|
||||
sys_segs: list[tuple[str, bool]] = [("<system>\n", False)]
|
||||
if content:
|
||||
sys_segs.append((content, True))
|
||||
sys_segs.append(("\n</system>\n", False))
|
||||
emit_text_segments(sys_segs, i, is_sampled=False)
|
||||
case "user":
|
||||
emit_text("<user>\n" + content + "\n</user>\n", i, is_sampled=False)
|
||||
user_segs: list[tuple[str, bool]] = [("<user>\n", False)]
|
||||
if content:
|
||||
user_segs.append((content, True))
|
||||
user_segs.append(("\n</user>\n", False))
|
||||
emit_text_segments(user_segs, i, is_sampled=False)
|
||||
case "assistant":
|
||||
self._render_assistant(
|
||||
msg, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
case "tool":
|
||||
emit_text(
|
||||
"<tool_response>\n" + content + "\n</tool_response>\n",
|
||||
i,
|
||||
is_sampled=False,
|
||||
)
|
||||
tool_segs: list[tuple[str, bool]] = [("<tool_response>\n", False)]
|
||||
if content:
|
||||
tool_segs.append((content, True))
|
||||
tool_segs.append(("\n</tool_response>\n", False))
|
||||
emit_text_segments(tool_segs, i, is_sampled=False)
|
||||
|
||||
# ── Generation prompt ─────────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1, is_sampled=False)
|
||||
emit_text("\n", -1, is_sampled=False)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False)
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._think_end, -1, is_sampled=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -287,6 +361,11 @@ class LagunaXS2Renderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# The canonical assistant-turn close is ``</assistant>``. ``〈|EOS|〉``
|
||||
# also stops generation; either being the final token means the turn
|
||||
@@ -302,42 +381,95 @@ class LagunaXS2Renderer:
|
||||
previous_ids.extend(self._encode("\n"))
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't track sampled_mask here. Local helpers accept the kwarg
|
||||
# for signature compatibility and ignore it; the returned
|
||||
# ``RenderedTokens`` leaves ``sampled_mask`` empty.
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
for msg in new_messages:
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
if role == "user":
|
||||
emit_text("<user>\n" + content + "\n</user>\n")
|
||||
segs: list[tuple[str, bool]] = [("<user>\n", False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
segs.append(("\n</user>\n", False))
|
||||
emit_text_segments(segs, i)
|
||||
elif role == "system":
|
||||
emit_text("<system>\n" + content + "\n</system>\n")
|
||||
segs = [("<system>\n", False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
segs.append(("\n</system>\n", False))
|
||||
emit_text_segments(segs, i)
|
||||
elif role == "tool":
|
||||
emit_text("<tool_response>\n" + content + "\n</tool_response>\n")
|
||||
segs = [("<tool_response>\n", False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
segs.append(("\n</tool_response>\n", False))
|
||||
emit_text_segments(segs, i)
|
||||
else:
|
||||
return None
|
||||
|
||||
emit_special(self._assistant)
|
||||
emit_text("\n")
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think)
|
||||
emit_special(self._assistant, -1)
|
||||
emit_text("\n", -1)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
else:
|
||||
emit_special(self._think_end)
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -347,7 +479,22 @@ class LagunaXS2Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Raw passthrough is an XS.2-only template gate; the XS-2.1
|
||||
# config doesn't define it.
|
||||
if (
|
||||
isinstance(self.config, LagunaXS2RendererConfig)
|
||||
and self.config.render_assistant_messages_raw
|
||||
):
|
||||
self._render_assistant_raw(
|
||||
msg_idx,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
return
|
||||
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
reasoning_content = msg["reasoning_content"]
|
||||
@@ -363,23 +510,30 @@ class LagunaXS2Renderer:
|
||||
# template emits these as the generation prompt at inference and
|
||||
# the model never samples them. Marking the role tag as
|
||||
# ``is_sampled=False`` keeps the SFT loss mask aligned with what
|
||||
# the model would actually have produced.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
# the model would actually have produced. ``is_content`` is also
|
||||
# False on the role tag. On assistant the invariant
|
||||
# ``is_content == sampled_mask`` holds.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if reasoning_content:
|
||||
emit_special(self._think, msg_idx, is_sampled=True)
|
||||
emit_text("\n" + reasoning_content.strip() + "\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n" + reasoning_content.strip() + "\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Combined newline-after-</think> with optional content. Bundling
|
||||
# preserves BPE merges across the boundary.
|
||||
post_think_text = "\n"
|
||||
if content.strip():
|
||||
post_think_text += content.strip() + "\n"
|
||||
emit_text(post_think_text, msg_idx, is_sampled=True)
|
||||
emit_text(post_think_text, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
for tc in tool_calls:
|
||||
@@ -392,7 +546,7 @@ class LagunaXS2Renderer:
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
inner = name + "\n"
|
||||
if isinstance(arguments, dict):
|
||||
for k, v in arguments.items():
|
||||
@@ -402,13 +556,409 @@ class LagunaXS2Renderer:
|
||||
else:
|
||||
val_text = json.dumps(v, ensure_ascii=False)
|
||||
inner += "<arg_value>" + val_text + "</arg_value>\n"
|
||||
emit_text(inner, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True)
|
||||
emit_text(inner, 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)
|
||||
|
||||
# ``</assistant>`` is the model's stop signal (alongside
|
||||
# ``〈|EOS|〉``) — it samples this to end its turn, so it's part of
|
||||
# the sampled stream. The trailing ``\n`` is template-appended
|
||||
# between turns and never sampled.
|
||||
emit_special(self._assistant_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
def _render_assistant_raw(
|
||||
self,
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
) -> None:
|
||||
"""Passthrough assistant rendering matching the Jinja template's
|
||||
``render_assistant_messages_raw`` branch.
|
||||
|
||||
Three pieces, each conditional on the content's own bytes:
|
||||
|
||||
- Open the assistant turn (``<assistant>\\n``) — always.
|
||||
- Prepend the gen-prompt prefix (``<think>`` if
|
||||
``enable_thinking``, else ``</think>``) only when ``content``
|
||||
doesn't already start with it. This lets callers ship content
|
||||
that already includes the prefix (e.g. raw rollouts) without
|
||||
duplicating it.
|
||||
- Emit ``content`` verbatim. ``</think>`` and ``</assistant>``
|
||||
land inside the content as added-vocab specials via the
|
||||
tokenizer's default ``split_special_tokens=False`` behaviour,
|
||||
matching what ``apply_chat_template`` does when it tokenises
|
||||
the rendered string.
|
||||
- Append ``\\n</assistant>`` only when ``content`` doesn't end
|
||||
with ``</assistant>`` (or ``</assistant>\\n``), then always
|
||||
emit the inter-turn ``\\n``.
|
||||
|
||||
Tool calls are deliberately ignored in raw mode — the template
|
||||
also ignores ``message.tool_calls`` here. Callers shipping raw
|
||||
content are expected to embed any tool-call payload in the
|
||||
content string themselves.
|
||||
"""
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if self.config.enable_thinking:
|
||||
if not content.startswith("<think>"):
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
else:
|
||||
if not content.startswith("</think>"):
|
||||
emit_special(
|
||||
self._think_end, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
if not (content.endswith("</assistant>\n") or content.endswith("</assistant>")):
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
|
||||
class LagunaXS21Renderer(LagunaXS2Renderer):
|
||||
"""Laguna-XS-2.1 — mirrors the ``poolside/Laguna-XS-2.1`` chat
|
||||
template (upstream rev ``575f0f28``); see the module docstring for
|
||||
its format.
|
||||
|
||||
Token wiring, stop tokens, and the parsing skeleton are shared with
|
||||
:class:`LagunaXS2Renderer`; ``render``, ``bridge_to_next_turn``, and
|
||||
the assistant emit implement this template's format.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: LagunaXS21RendererConfig | None = None,
|
||||
):
|
||||
super().__init__(tokenizer, config or LagunaXS21RendererConfig())
|
||||
|
||||
def render(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> RenderedTokens:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
# Role tags hug the body with no whitespace, so a BPE merge
|
||||
# can pull wrap bytes and body bytes into one token —
|
||||
# overlap attribution keeps every body byte in the content
|
||||
# run.
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments, overlap_is_content=True
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
emit_special(self._eos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── System header (absorbs messages[0] if it's a system message) ──
|
||||
system_content = self._default_system_message
|
||||
caller_has_system = bool(messages and messages[0].get("role") == "system")
|
||||
if caller_has_system:
|
||||
system_content = self._visible_text(messages[0].get("content"))
|
||||
|
||||
has_sys_content = bool(system_content and system_content.strip())
|
||||
# The template's gate is ``has_sys or tools or enable_thinking`` —
|
||||
# an empty caller system message opts out of the default, and with
|
||||
# neither tools nor thinking the block vanishes entirely.
|
||||
if has_sys_content or tools or self.config.enable_thinking:
|
||||
# The whole header is one plain-text run — ``<system>`` glues
|
||||
# straight onto the body with no newline — so it must be
|
||||
# tokenized in a single BPE pass. In the header, content bytes
|
||||
# exist exactly when the caller supplied the system message
|
||||
# (the default prompt is scaffold), so the is_content bit also
|
||||
# selects the message index: body → 0, everything else → -1.
|
||||
header_segs: list[tuple[str, bool]] = [("<system>", False)]
|
||||
if has_sys_content:
|
||||
header_segs.append((system_content.rstrip(), caller_has_system))
|
||||
if tools:
|
||||
header_segs.append(("\n\n", False))
|
||||
if tools:
|
||||
tool_text = _TOOLS_HEADER_XS21
|
||||
for tool in tools:
|
||||
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
|
||||
tool_text += "</available_tools>"
|
||||
header_segs.append((tool_text, False))
|
||||
header_segs.append(("</system>\n", False))
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, header_segs, overlap_is_content=True
|
||||
):
|
||||
emit_special(
|
||||
tok_id,
|
||||
0 if is_content else -1,
|
||||
is_sampled=False,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
# ── Per-message loop ──────────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
match msg["role"]:
|
||||
case "system":
|
||||
# The template slices a leading system message off the
|
||||
# loop (it lives in the header); later ones render.
|
||||
if i == 0:
|
||||
continue
|
||||
sys_segs: list[tuple[str, bool]] = [("<system>", False)]
|
||||
if content:
|
||||
sys_segs.append((content, True))
|
||||
sys_segs.append(("</system>\n", False))
|
||||
emit_text_segments(sys_segs, i, is_sampled=False)
|
||||
case "user":
|
||||
user_segs: list[tuple[str, bool]] = [("<user>", False)]
|
||||
if content:
|
||||
user_segs.append((content, True))
|
||||
user_segs.append(("</user>\n", False))
|
||||
emit_text_segments(user_segs, i, is_sampled=False)
|
||||
case "assistant":
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
case "tool":
|
||||
tool_segs: list[tuple[str, bool]] = [("<tool_response>", False)]
|
||||
if content:
|
||||
tool_segs.append((content, True))
|
||||
tool_segs.append(("</tool_response>\n", False))
|
||||
emit_text_segments(tool_segs, i, is_sampled=False)
|
||||
|
||||
# ── Generation prompt (no newline after <assistant>) ──────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
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 parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
# The XS-2.1 template renders reasoning and content verbatim (no
|
||||
# newline wrapping), so the parse is verbatim too.
|
||||
return parse_laguna_xs2(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
stop_ids={self._assistant_end, self._eos},
|
||||
think_id=self._think,
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tools=tools,
|
||||
strip_newlines=False,
|
||||
)
|
||||
|
||||
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.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# ``</assistant>`` is the canonical turn close; ``〈|EOS|〉`` also
|
||||
# stops generation. Truncation (no stop token at the tail)
|
||||
# synthesises the close. The inter-turn ``\n`` the template puts
|
||||
# after ``</assistant>`` is prepended to the first extension
|
||||
# message below so the seam encodes with the tag run.
|
||||
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
|
||||
stop_ids = {self._assistant_end, self._eos}
|
||||
if (
|
||||
not previous_ids[len(previous_prompt_ids) :]
|
||||
or previous_ids[-1] not in stop_ids
|
||||
):
|
||||
previous_ids.append(self._assistant_end)
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments, overlap_is_content=True
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
_OPEN = {"user": "<user>", "system": "<system>", "tool": "<tool_response>"}
|
||||
_CLOSE = {
|
||||
"user": "</user>\n",
|
||||
"system": "</system>\n",
|
||||
"tool": "</tool_response>\n",
|
||||
}
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
if role not in _OPEN:
|
||||
return None
|
||||
content = self._visible_text(msg.get("content"))
|
||||
lead = "\n" if i == 0 else ""
|
||||
segs: list[tuple[str, bool]] = [(lead + _OPEN[role], False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
segs.append((_CLOSE[role], False))
|
||||
emit_text_segments(segs, i)
|
||||
|
||||
emit_special(self._assistant, -1)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
else:
|
||||
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),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
msg: Message,
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
reasoning_content = msg["reasoning_content"]
|
||||
else:
|
||||
part_thinking = self._thinking_text(msg.get("content"))
|
||||
if part_thinking:
|
||||
reasoning_content = part_thinking
|
||||
|
||||
# ``<assistant>`` plus the think tag that follows are exactly the
|
||||
# generation prompt for the active mode — template-injected
|
||||
# scaffolding the model never samples.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if self.config.enable_thinking:
|
||||
# ``<think>{reasoning}</think>`` renders verbatim, even when
|
||||
# the reasoning is empty; the opener is the gen-prompt
|
||||
# prefill, the rest the model sampled.
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
if reasoning_content:
|
||||
emit_text(reasoning_content, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
# Thinking off: any reasoning on the message is dropped and
|
||||
# the turn opens with the prefilled ``</think>``.
|
||||
emit_special(self._think_end, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if content:
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
inner = name
|
||||
if isinstance(arguments, dict):
|
||||
for k, v in arguments.items():
|
||||
inner += "<arg_key>" + k + "</arg_key>"
|
||||
if isinstance(v, str):
|
||||
val_text = v
|
||||
else:
|
||||
val_text = json.dumps(v, ensure_ascii=False)
|
||||
inner += "<arg_value>" + val_text + "</arg_value>"
|
||||
emit_text(inner, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
"""Llama-3 Renderer — hard-coded Python mirroring Meta's Llama-3 chat template.
|
||||
|
||||
Initial scope: Llama-3.2-1B-Instruct and Llama-3.2-3B-Instruct (and the
|
||||
unrestricted ``unsloth/Llama-3.2-{1B,3B}-Instruct`` mirror, which ships a
|
||||
byte-identical chat template). Other Llama-3.x sizes ship slightly
|
||||
different templates and are NOT covered by this renderer until parity is
|
||||
verified.
|
||||
|
||||
Notable differences from the Qwen / GLM family renderers:
|
||||
|
||||
* No ``<think>`` / reasoning channel — Llama-3 doesn't ship a
|
||||
reasoning-content concept, so the ``thinking_retention`` flag doesn't
|
||||
apply.
|
||||
* ``<|begin_of_text|>`` (BOS) is emitted at the very start of every
|
||||
render. The chat template never omits it.
|
||||
* The system block is emitted **unconditionally** with a fixed
|
||||
``Cutting Knowledge Date: December 2023\\nToday Date: <date>\\n\\n``
|
||||
preamble — even when no system message is supplied. Empty system
|
||||
message → block ends with ``\\n\\n<|eot_id|>``.
|
||||
* Tools default to "first-user-message" mode (matching the chat
|
||||
template's default ``tools_in_user_message=True``): tool descriptions
|
||||
+ JSON signatures are injected into the first user message rather
|
||||
than the system block. Set ``Llama3RendererConfig.tools_in_user_message
|
||||
= False`` to flip to system-block mode.
|
||||
* ``Llama3RendererConfig.date_string`` is pinned at ``"26 Jul 2024"`` by
|
||||
default to match the chat template's ``strftime`` fallback (and keep
|
||||
output deterministic). Override per instance for production runs that
|
||||
want today's date.
|
||||
* Tool calls: a single ``{"name": "...", "parameters": ...}`` JSON blob
|
||||
inside the assistant body. The chat template explicitly raises if
|
||||
``message.tool_calls | length != 1``; this renderer matches that.
|
||||
* Tool responses: rendered with role ``ipython`` regardless of whether
|
||||
the source message used ``role: "tool"`` or ``role: "ipython"``. The
|
||||
chat template runs ``content | tojson`` on any mapping/iterable
|
||||
content — and Jinja considers strings iterable, so plain string
|
||||
contents get JSON-quoted. We mirror that exactly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from renderers.base import (
|
||||
Message,
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Llama3RendererConfig
|
||||
from renderers.parsing import parse_llama_3
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants — must match the Jinja chat template's literal strings exactly.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_CUTTING_KNOWLEDGE_DATE = "December 2023"
|
||||
|
||||
# Tools-in-system intro: emitted into the system block when tools is set
|
||||
# AND tools_in_user_message=False. Note: the chat template puts these
|
||||
# three string literals back-to-back with NO newline between the second
|
||||
# and third, so there's no space before "Do not use variables.".
|
||||
_TOOLS_IN_SYSTEM_INTRO = (
|
||||
"You have access to the following functions. To call a function, "
|
||||
"please respond with JSON for a function call."
|
||||
'Respond in the format {"name": function name, "parameters": '
|
||||
"dictionary of argument name and its value}."
|
||||
"Do not use variables.\n\n"
|
||||
)
|
||||
|
||||
# Tools-in-user intro: emitted into the first user message when tools is
|
||||
# set AND tools_in_user_message=True (the default).
|
||||
_TOOLS_IN_USER_INTRO = (
|
||||
"Given the following functions, please respond with a JSON for a "
|
||||
"function call with its proper arguments that best answers the given "
|
||||
"prompt.\n\n"
|
||||
'Respond in the format {"name": function name, "parameters": '
|
||||
"dictionary of argument name and its value}."
|
||||
"Do not use variables.\n\n"
|
||||
)
|
||||
|
||||
|
||||
class Llama3Renderer:
|
||||
"""Deterministic message → token renderer for Llama-3.x Instruct models."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Llama3RendererConfig | None = None,
|
||||
):
|
||||
# ``thinking_retention`` is accepted but a no-op: Llama-3 ships no
|
||||
# reasoning_content channel, so there's never any past-assistant
|
||||
# thinking to retain or drop. The level is stored on ``self.config``
|
||||
# for cross-renderer uniformity but never changes the token stream —
|
||||
# the same contract as Kimi-K2 / Qwen3-VL (see the never-preserves
|
||||
# renderers in tests/test_preserve_thinking.py).
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or Llama3RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
|
||||
self._bos = self._token_id("<|begin_of_text|>")
|
||||
self._start_header = self._token_id("<|start_header_id|>")
|
||||
self._end_header = self._token_id("<|end_header_id|>")
|
||||
self._eot = self._token_id("<|eot_id|>")
|
||||
self._end_of_text = self._token_id("<|end_of_text|>")
|
||||
# ``<|eom_id|>`` shows up in some Llama-3 tool-calling traces (the
|
||||
# "ipython" / python-tag flow) but the standard 3.2 chat template
|
||||
# closes turns with ``<|eot_id|>``. We still treat eom as a stop
|
||||
# token so models that emit it terminate cleanly.
|
||||
self._eom = self._token_id("<|eom_id|>")
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
tid = self._tokenizer.convert_tokens_to_ids(token)
|
||||
assert isinstance(tid, int) and tid != self._tokenizer.unk_token_id, (
|
||||
f"Special token {token!r} not found in tokenizer vocabulary"
|
||||
)
|
||||
return tid
|
||||
|
||||
def _encode(self, text: str) -> list[int]:
|
||||
if not text:
|
||||
return []
|
||||
return self._tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
@staticmethod
|
||||
def _content_str(content: Any) -> str:
|
||||
"""Render content to a plain string. Handles ``str``, list-of-text-parts,
|
||||
and ``None``. Matches the chat template's ``message.content | trim``
|
||||
callers, which expect a string in."""
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
parts.append(item)
|
||||
elif isinstance(item, dict) and "text" in item:
|
||||
parts.append(item["text"])
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
return "".join(parts)
|
||||
raise TypeError(f"Unexpected content type: {type(content)}")
|
||||
|
||||
@staticmethod
|
||||
def _tool_response_str(content: Any) -> str:
|
||||
"""Mirror the chat template's tool-response branch:
|
||||
``{% if message.content is mapping or message.content is iterable %}
|
||||
{{ message.content | tojson }} {% else %} {{ message.content }}``.
|
||||
|
||||
In Jinja, **strings are iterable** — so plain-string tool contents
|
||||
also go through ``tojson`` (i.e. ``json.dumps``), wrapping them in
|
||||
quotes and escaping. Non-iterable scalars (numbers, bools, None)
|
||||
fall through to literal stringification.
|
||||
"""
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, (dict, list, str)):
|
||||
return json.dumps(content, ensure_ascii=False)
|
||||
return str(content)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# render
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def render(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> RenderedTokens:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated wrap + body as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment. Lets the
|
||||
scaffold/body split stay attributed without splitting the
|
||||
encode call (which could shift BPE merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── 0. BOS ──────────────────────────────────────────────────
|
||||
emit_special(self._bos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 1. System block (always emitted) ────────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
sys_idx = 0 if first_is_system else -1
|
||||
sys_text = (
|
||||
self._content_str(messages[0].get("content")).strip()
|
||||
if first_is_system
|
||||
else ""
|
||||
)
|
||||
|
||||
emit_special(self._start_header, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("system", sys_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._end_header, sys_idx, is_sampled=False, is_content=False)
|
||||
# The Cutting Knowledge / Today Date preamble (and any tools-in-system
|
||||
# block) is template scaffold; only the caller's system content is
|
||||
# body. Route both through one BPE pass so the wrap/body boundary
|
||||
# can't shift merges.
|
||||
preamble = "\n\n"
|
||||
if tools is not None:
|
||||
preamble += "Environment: ipython\n"
|
||||
preamble += f"Cutting Knowledge Date: {_CUTTING_KNOWLEDGE_DATE}\n"
|
||||
preamble += f"Today Date: {self.config.date_string}\n\n"
|
||||
if tools is not None and not self.config.tools_in_user_message:
|
||||
preamble += _TOOLS_IN_SYSTEM_INTRO
|
||||
for t in tools:
|
||||
preamble += json.dumps(t, indent=4, ensure_ascii=False) + "\n\n"
|
||||
sys_segments: list[tuple[str, bool]] = [(preamble, False)]
|
||||
if sys_text:
|
||||
sys_segments.append((sys_text, True))
|
||||
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._eot, sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Body messages ────────────────────────────────────────
|
||||
body_messages = messages[1:] if first_is_system else messages
|
||||
offset = 1 if first_is_system else 0
|
||||
|
||||
i = 0
|
||||
# 2a. tools_in_user_message mode pulls the first user message
|
||||
# into a special block with the tools description prepended.
|
||||
if tools is not None and self.config.tools_in_user_message:
|
||||
if i >= len(body_messages):
|
||||
raise ValueError(
|
||||
"Cannot place tools in the first user message — no user "
|
||||
"message was provided."
|
||||
)
|
||||
first_user = body_messages[i]
|
||||
if first_user.get("role") != "user":
|
||||
raise ValueError(
|
||||
"tools_in_user_message=True requires the first non-system "
|
||||
f"message to be 'user'; got {first_user.get('role')!r}."
|
||||
)
|
||||
user_idx = i + offset
|
||||
emit_special(
|
||||
self._start_header, user_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("user", user_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._end_header, user_idx, is_sampled=False, is_content=False)
|
||||
user_preamble = "\n\n" + _TOOLS_IN_USER_INTRO
|
||||
for t in tools:
|
||||
user_preamble += json.dumps(t, indent=4, ensure_ascii=False) + "\n\n"
|
||||
user_content = self._content_str(first_user.get("content")).strip()
|
||||
user_segments: list[tuple[str, bool]] = [(user_preamble, False)]
|
||||
if user_content:
|
||||
user_segments.append((user_content, True))
|
||||
emit_text_segments(user_segments, user_idx, is_sampled=False)
|
||||
emit_special(self._eot, user_idx, is_sampled=False, is_content=False)
|
||||
i += 1
|
||||
|
||||
# 2b. Remaining messages — plain user/assistant/tool/assistant-with-tool-calls.
|
||||
for j in range(i, len(body_messages)):
|
||||
msg = body_messages[j]
|
||||
msg_idx = j + offset
|
||||
role = msg.get("role")
|
||||
tool_calls = msg.get("tool_calls")
|
||||
|
||||
if role in ("tool", "ipython"):
|
||||
# Tool responses are conversation history the model never
|
||||
# samples; the response body is caller content, the wrap is
|
||||
# scaffold.
|
||||
emit_special(
|
||||
self._start_header, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("ipython", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(
|
||||
self._end_header, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
tool_body = self._tool_response_str(msg.get("content"))
|
||||
tool_segments: list[tuple[str, bool]] = [("\n\n", False)]
|
||||
if tool_body:
|
||||
tool_segments.append((tool_body, True))
|
||||
emit_text_segments(tool_segments, msg_idx, is_sampled=False)
|
||||
emit_special(self._eot, msg_idx, is_sampled=False, is_content=False)
|
||||
elif tool_calls:
|
||||
if len(tool_calls) != 1:
|
||||
raise ValueError(
|
||||
"Llama-3 chat template only supports a single tool call "
|
||||
"per assistant message."
|
||||
)
|
||||
tc = tool_calls[0]
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
if isinstance(arguments, str):
|
||||
args_str = arguments
|
||||
else:
|
||||
args_str = json.dumps(arguments, ensure_ascii=False)
|
||||
emit_special(
|
||||
self._start_header, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(
|
||||
self._end_header, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
# The ``\n\n`` after the header is gen-prompt scaffold the
|
||||
# model never samples; the JSON tool-call body and the
|
||||
# closing ``<|eot_id|>`` are the model's sampled emission.
|
||||
emit_text("\n\n", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text(
|
||||
'{"name": "' + name + '", "parameters": ' + args_str + "}",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._eot, msg_idx, is_sampled=True, is_content=True)
|
||||
elif role == "assistant":
|
||||
content = self._content_str(msg.get("content")).strip()
|
||||
emit_special(
|
||||
self._start_header, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(
|
||||
self._end_header, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
# ``\n\n`` separator is scaffold (it's the generation prompt);
|
||||
# the body and the closing ``<|eot_id|>`` are model-sampled.
|
||||
emit_text("\n\n", msg_idx, is_sampled=False, is_content=False)
|
||||
if content:
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._eot, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
# user / non-leading system: caller content, never sampled.
|
||||
content = self._content_str(msg.get("content")).strip()
|
||||
emit_special(
|
||||
self._start_header, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text(role or "", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(
|
||||
self._end_header, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
segments: list[tuple[str, bool]] = [("\n\n", False)]
|
||||
if content:
|
||||
segments.append((content, True))
|
||||
emit_text_segments(segments, msg_idx, is_sampled=False)
|
||||
emit_special(self._eot, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 3. Generation prompt ────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._start_header, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._end_header, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> list[int]:
|
||||
return self.render(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_llama_3(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
stop_ids={self._eot, self._end_of_text, self._eom},
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
return [self._eot, self._end_of_text, self._eom]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# bridge_to_next_turn
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def bridge_to_next_turn(
|
||||
self,
|
||||
previous_prompt_ids: list[int],
|
||||
previous_completion_ids: list[int],
|
||||
new_messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> RenderedTokens | None:
|
||||
if (
|
||||
not previous_prompt_ids
|
||||
or not new_messages
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
{self._eot, self._end_of_text, self._eom},
|
||||
synthesize_close=self._eot,
|
||||
)
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Every token the bridge emits is template scaffolding for the next
|
||||
# prompt — none of it is model-sampled — so ``sampled_mask`` is
|
||||
# uniformly ``False`` (applied over the whole sequence at return).
|
||||
# ``is_content`` follows the same rules as :meth:`render` so a
|
||||
# consumer can walk the trajectory and read each step's body mask.
|
||||
def emit_special(token_id: int, msg_idx: int = -1) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_content.append(False)
|
||||
|
||||
def emit_text(text: str, msg_idx: int = -1) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_content.extend([False] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int = -1
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_content.append(is_content)
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
if role in ("system", "user"):
|
||||
content = self._content_str(msg.get("content")).strip()
|
||||
emit_special(self._start_header, i)
|
||||
emit_text(role, i)
|
||||
emit_special(self._end_header, i)
|
||||
segs: list[tuple[str, bool]] = [("\n\n", False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
emit_text_segments(segs, i)
|
||||
emit_special(self._eot, i)
|
||||
elif role in ("tool", "ipython"):
|
||||
tool_body = self._tool_response_str(msg.get("content"))
|
||||
emit_special(self._start_header, i)
|
||||
emit_text("ipython", i)
|
||||
emit_special(self._end_header, i)
|
||||
tool_segs: list[tuple[str, bool]] = [("\n\n", False)]
|
||||
if tool_body:
|
||||
tool_segs.append((tool_body, True))
|
||||
emit_text_segments(tool_segs, i)
|
||||
emit_special(self._eot, i)
|
||||
else:
|
||||
return None
|
||||
|
||||
# Generation prompt — matches the gen-prompt branch of ``render()``.
|
||||
emit_special(self._start_header, -1)
|
||||
emit_text("assistant", -1)
|
||||
emit_special(self._end_header, -1)
|
||||
emit_text("\n\n", -1)
|
||||
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
+268
-89
@@ -21,16 +21,16 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import MiniMaxM2RendererConfig
|
||||
from renderers.parsing import parse_minimax
|
||||
|
||||
_DEFAULT_SYSTEM = (
|
||||
"You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax."
|
||||
)
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
"\n\n# Tools\n"
|
||||
"You may call one or more tools to assist with the user query.\n"
|
||||
@@ -58,16 +58,13 @@ class MiniMaxM2Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
default_system: str = _DEFAULT_SYSTEM,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: MiniMaxM2RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._default_system = default_system
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or MiniMaxM2RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"tool_cycle",
|
||||
)
|
||||
|
||||
self._bos = self._token_id("]~!b[")
|
||||
@@ -119,17 +116,69 @@ class MiniMaxM2Renderer:
|
||||
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) -> None:
|
||||
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) -> None:
|
||||
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_token_overlap_body(
|
||||
full_text: str,
|
||||
body_start: int,
|
||||
body_end: int,
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_sampled: bool,
|
||||
) -> None:
|
||||
"""Tokenize ``full_text`` and mark tokens that overlap the body
|
||||
char span as ``is_content=True``.
|
||||
|
||||
Differs from :func:`attribute_text_segments` only in the
|
||||
boundary-token rule: a token straddling scaffold→body gets
|
||||
``True`` if any of its bytes are body bytes (overlap rule),
|
||||
rather than being attributed to whichever segment its first
|
||||
char belongs to. The body's first byte is preserved even when
|
||||
BPE merges it with the wrap's trailing byte (``>The`` →
|
||||
single token).
|
||||
"""
|
||||
from renderers.base import _get_offset_tokenizer
|
||||
|
||||
offset_tok = _get_offset_tokenizer(self._tokenizer)
|
||||
encoding = offset_tok(
|
||||
full_text, add_special_tokens=False, return_offsets_mapping=True
|
||||
)
|
||||
for tok_id, (start, end) in zip(
|
||||
encoding["input_ids"], encoding["offset_mapping"]
|
||||
):
|
||||
overlaps = start < body_end and end > body_start
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(overlaps)
|
||||
|
||||
# ── Extract system message ──────────────────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
@@ -137,27 +186,38 @@ class MiniMaxM2Renderer:
|
||||
conversation: list[Message] = messages[1:] if first_is_system else messages
|
||||
|
||||
# ── System block (always present) ───────────────────────────
|
||||
emit_special(self._bos, sys_idx, is_sampled=False)
|
||||
emit_special(self._role, sys_idx, is_sampled=False)
|
||||
emit_special(self._bos, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._role, sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
sys_content = (
|
||||
self._visible_text(messages[0].get("content")) if first_is_system else ""
|
||||
)
|
||||
system_text = "system\n" + (sys_content or self._default_system)
|
||||
# Body = caller's system content (if any). Default system message
|
||||
# is template-injected scaffold; tools header / per-tool JSON /
|
||||
# footer / instructions are scaffold too (the tools dict is
|
||||
# recoverable from the ``tools`` arg).
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
sys_segments.append((sys_content, True))
|
||||
else:
|
||||
sys_segments.append((self.config.model_identity, False))
|
||||
|
||||
if tools:
|
||||
system_text += _TOOLS_HEADER
|
||||
sys_segments.append((_TOOLS_HEADER, False))
|
||||
for tool in tools:
|
||||
func = tool.get("function", tool)
|
||||
system_text += (
|
||||
"<tool>" + json.dumps(func, ensure_ascii=False) + "</tool>\n"
|
||||
sys_segments.append(
|
||||
(
|
||||
"<tool>" + json.dumps(func, ensure_ascii=False) + "</tool>\n",
|
||||
False,
|
||||
)
|
||||
)
|
||||
system_text += _TOOLS_FOOTER_PREFIX
|
||||
system_text += _TOOLS_INSTRUCTIONS
|
||||
sys_segments.append((_TOOLS_FOOTER_PREFIX, False))
|
||||
sys_segments.append((_TOOLS_INSTRUCTIONS, False))
|
||||
|
||||
emit_text(system_text, sys_idx, is_sampled=False)
|
||||
emit_special(self._eos, sys_idx, is_sampled=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False)
|
||||
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._eos, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Compute last_user_index (relative to conversation) ──────
|
||||
last_ui = -1
|
||||
@@ -172,30 +232,24 @@ class MiniMaxM2Renderer:
|
||||
orig_idx = ci + (1 if first_is_system else 0)
|
||||
|
||||
if role == "user":
|
||||
emit_special(self._role, orig_idx, is_sampled=False)
|
||||
emit_text(
|
||||
"user\n" + self._visible_text(msg.get("content")),
|
||||
orig_idx,
|
||||
is_sampled=False,
|
||||
)
|
||||
emit_special(self._eos, orig_idx, is_sampled=False)
|
||||
emit_text("\n", orig_idx, is_sampled=False)
|
||||
emit_special(self._role, orig_idx, is_sampled=False, is_content=False)
|
||||
user_content = self._visible_text(msg.get("content"))
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if user_content:
|
||||
user_segments.append((user_content, True))
|
||||
emit_text_segments(user_segments, orig_idx, is_sampled=False)
|
||||
emit_special(self._eos, orig_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
orig_idx,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
orig_idx,
|
||||
ci,
|
||||
last_ui,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
@@ -206,17 +260,24 @@ class MiniMaxM2Renderer:
|
||||
msg,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
emit_token_overlap_body=emit_token_overlap_body,
|
||||
)
|
||||
|
||||
# ── Generation prompt ───────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._role, -1, is_sampled=False)
|
||||
emit_text("ai\n", -1, is_sampled=False)
|
||||
emit_special(self._think, -1, is_sampled=False)
|
||||
emit_text("\n", -1, is_sampled=False)
|
||||
emit_special(self._role, -1, is_sampled=False, is_content=False)
|
||||
emit_text("ai\n", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -267,6 +328,12 @@ class MiniMaxM2Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
@@ -277,22 +344,77 @@ class MiniMaxM2Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't track sampled_mask here. Local helpers accept the kwarg
|
||||
# for signature compatibility with ``_render_tool`` and ignore
|
||||
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
|
||||
# empty.
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_token_overlap_body(
|
||||
full_text: str,
|
||||
body_start: int,
|
||||
body_end: int,
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_sampled: bool,
|
||||
) -> None:
|
||||
from renderers.base import _get_offset_tokenizer
|
||||
|
||||
offset_tok = _get_offset_tokenizer(self._tokenizer)
|
||||
encoding = offset_tok(
|
||||
full_text, add_special_tokens=False, return_offsets_mapping=True
|
||||
)
|
||||
for tok_id, (start, end) in zip(
|
||||
encoding["input_ids"], encoding["offset_mapping"]
|
||||
):
|
||||
overlaps = start < body_end and end > body_start
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(overlaps)
|
||||
|
||||
# Trailing ``\n`` after the ``[e~[`` turn close — see ``render()``.
|
||||
emit_text("\n", -1)
|
||||
@@ -302,12 +424,18 @@ class MiniMaxM2Renderer:
|
||||
content = self._visible_text(msg.get("content"))
|
||||
if role == "user":
|
||||
emit_special(self._role, i)
|
||||
emit_text("user\n" + content, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i)
|
||||
emit_special(self._eos, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "system":
|
||||
emit_special(self._role, i)
|
||||
emit_text("system\n" + content, i)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if content:
|
||||
sys_segments.append((content, True))
|
||||
emit_text_segments(sys_segments, i)
|
||||
emit_special(self._eos, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "tool":
|
||||
@@ -318,6 +446,8 @@ class MiniMaxM2Renderer:
|
||||
msg,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
emit_token_overlap_body=emit_token_overlap_body,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
@@ -328,7 +458,15 @@ class MiniMaxM2Renderer:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -337,9 +475,9 @@ class MiniMaxM2Renderer:
|
||||
conv_idx,
|
||||
last_user_index,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
):
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
@@ -358,26 +496,31 @@ class MiniMaxM2Renderer:
|
||||
# the chat template emits these as the generation prompt and the
|
||||
# model never samples them. Marking the role marker and tag as
|
||||
# ``is_sampled=False`` keeps the SFT loss mask aligned with what
|
||||
# the model would actually have produced.
|
||||
emit_special(self._role, orig_idx, is_sampled=False)
|
||||
# the model would actually have produced. ``is_content`` is also
|
||||
# False here — the role tag isn't part of any message's body.
|
||||
emit_special(self._role, orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build the model-sampled portion (think block + content + tool
|
||||
# calls). Text segments stay contiguous within each is_sampled
|
||||
# span to preserve BPE merges.
|
||||
# calls). For assistant messages the invariant
|
||||
# ``is_content == sampled_mask`` holds — every sampled token is
|
||||
# body, every scaffold token isn't.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
emit_thinking = reasoning_content and (
|
||||
conv_idx > last_user_index or preserve_thinking
|
||||
)
|
||||
emit_thinking = reasoning_content and conv_idx > last_user_index
|
||||
|
||||
if emit_thinking:
|
||||
# The thinking branch has the ``<think>`` special token
|
||||
# immediately after ``ai\n``, which forces a tokenizer
|
||||
# boundary — splitting ``ai\n`` (not_sampled) from the
|
||||
# ``<think>``-led body (sampled) is BPE-safe.
|
||||
emit_text("ai\n", orig_idx, is_sampled=False)
|
||||
emit_special(self._think, orig_idx, is_sampled=True)
|
||||
emit_text("\n" + reasoning_content + "\n", orig_idx, is_sampled=True)
|
||||
emit_special(self._think_end, orig_idx, is_sampled=True)
|
||||
emit_text("ai\n", orig_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._think, orig_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n" + reasoning_content + "\n",
|
||||
orig_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._think_end, orig_idx, is_sampled=True, is_content=True)
|
||||
# \n\n + content must be contiguous for BPE
|
||||
body = "\n\n" + content if content else "\n\n"
|
||||
else:
|
||||
@@ -390,17 +533,19 @@ class MiniMaxM2Renderer:
|
||||
# choice for SFT (don't train on a token whose first byte
|
||||
# is template scaffolding).
|
||||
if tool_calls and not body:
|
||||
emit_text("ai\n\n", orig_idx, is_sampled=False)
|
||||
emit_text("ai\n\n", orig_idx, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_text("ai\n", orig_idx, is_sampled=False)
|
||||
emit_text("ai\n", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if tool_calls:
|
||||
# \n before <minimax:tool_call> must be contiguous with preceding text.
|
||||
# The empty-body / non-thinking case folded the leading \n
|
||||
# into the role-tag emission above; skip it here.
|
||||
if emit_thinking or body:
|
||||
emit_text(body + "\n", orig_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_tok, orig_idx, is_sampled=True)
|
||||
emit_text(body + "\n", orig_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_tok, orig_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
invoke_block = "\n"
|
||||
for tc in tool_calls:
|
||||
@@ -432,16 +577,18 @@ class MiniMaxM2Renderer:
|
||||
)
|
||||
invoke_block += "</invoke>\n"
|
||||
|
||||
emit_text(invoke_block, orig_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end_tok, orig_idx, is_sampled=True)
|
||||
emit_text(invoke_block, orig_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end_tok, orig_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
elif body:
|
||||
emit_text(body, orig_idx, is_sampled=True)
|
||||
emit_text(body, orig_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# ``[e~[`` is the model's stop signal — it samples this to end
|
||||
# its turn, so it is part of the sampled stream. The trailing
|
||||
# ``\n`` is template-appended between turns and never sampled.
|
||||
emit_special(self._eos, orig_idx, is_sampled=True)
|
||||
emit_text("\n", orig_idx, is_sampled=False)
|
||||
emit_special(self._eos, orig_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -452,10 +599,15 @@ class MiniMaxM2Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
emit_token_overlap_body=None,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False.
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# body bytes get ``is_content=True``; the surrounding ``<response>``
|
||||
# wrap, role tag and separators are scaffold so an SFT mask over
|
||||
# tool body never trains the model to emit those.
|
||||
prev_is_tool = conv_idx > 0 and conversation[conv_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
conv_idx + 1 < len(conversation)
|
||||
@@ -463,8 +615,8 @@ class MiniMaxM2Renderer:
|
||||
)
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._role, orig_idx, is_sampled=False)
|
||||
emit_text("tool", orig_idx, is_sampled=False)
|
||||
emit_special(self._role, orig_idx, is_sampled=False, is_content=False)
|
||||
emit_text("tool", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
content = self._visible_text(msg.get("content"))
|
||||
# Leading ``\n`` before ``<response>`` only on the first of a
|
||||
@@ -473,12 +625,39 @@ class MiniMaxM2Renderer:
|
||||
# through a single emit_text call instead of splitting the merge.
|
||||
prefix = "" if prev_is_tool else "\n"
|
||||
suffix = "\n" if next_is_tool else ""
|
||||
emit_text(
|
||||
prefix + "<response>" + content + "</response>" + suffix,
|
||||
orig_idx,
|
||||
is_sampled=False,
|
||||
)
|
||||
|
||||
# ``<response>`` is plain text with no separator between the
|
||||
# closing ``>`` and ``content``'s first byte, so BPE can merge
|
||||
# them into a single token (e.g., ``>The``). The shared
|
||||
# ``attribute_text_segments`` helper picks the segment of a
|
||||
# boundary-spanning token by its *first* char (here scaffold),
|
||||
# which would drop the body's leading letter out of the body
|
||||
# run. We instead use an "intersects body" rule: any token whose
|
||||
# ``[start, end)`` char range overlaps the body span gets
|
||||
# ``is_content=True``. A few scaffold bytes (the leading ``>``
|
||||
# or trailing ``<``) bleed into the body run, but body bytes are
|
||||
# recoverable as a substring of the decoded body span.
|
||||
body_text = prefix + "<response>" + content + "</response>" + suffix
|
||||
body_start = len(prefix) + len("<response>")
|
||||
body_end = body_start + len(content)
|
||||
if content and emit_token_overlap_body is not None:
|
||||
emit_token_overlap_body(
|
||||
body_text, body_start, body_end, orig_idx, is_sampled=False
|
||||
)
|
||||
else:
|
||||
# Empty body or no overlap-aware emitter available — fall back
|
||||
# to the standard segments path.
|
||||
tool_segments: list[tuple[str, bool]] = []
|
||||
if prefix:
|
||||
tool_segments.append((prefix, False))
|
||||
tool_segments.append(("<response>", False))
|
||||
if content:
|
||||
tool_segments.append((content, True))
|
||||
tool_segments.append(("</response>", False))
|
||||
if suffix:
|
||||
tool_segments.append((suffix, False))
|
||||
emit_text_segments(tool_segments, orig_idx, is_sampled=False)
|
||||
|
||||
if not next_is_tool:
|
||||
emit_special(self._eos, orig_idx, is_sampled=False)
|
||||
emit_text("\n", orig_idx, is_sampled=False)
|
||||
emit_special(self._eos, orig_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+372
-175
@@ -24,10 +24,14 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Nemotron3RendererConfig, Nemotron3UltraRendererConfig
|
||||
from renderers.parsing import parse_qwen35
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -72,24 +76,75 @@ def _render_extra_keys(obj: dict[str, Any], handled_keys: set[str]) -> list[str]
|
||||
return lines
|
||||
|
||||
|
||||
# The Nemotron-3 family ships two chat-template variants. Nano / Super share
|
||||
# one (renderer ``Nemotron3Renderer`` / config ``name="nemotron-3"``); Ultra
|
||||
# differs in the reasoning-block glue — no ``\n`` around ``</think>`` — and is
|
||||
# the ``Nemotron3UltraRenderer`` subclass (``name="nemotron-3-ultra"``). Which
|
||||
# variant a checkpoint uses is carried by ``MODEL_RENDERER_MAP``, so the right
|
||||
# renderer class is constructed and the variant is encoded by the class itself.
|
||||
|
||||
|
||||
def _is_super(tokenizer) -> bool:
|
||||
"""Does this checkpoint use the **Super** flavour of the shared Nano/Super
|
||||
template — i.e. the one whose Jinja defines the ``low_effort`` kwarg?
|
||||
|
||||
Nano and Super share one config (``nemotron-3``), so the model name is the
|
||||
only signal that separates them. Detected by substring; unknown / fine-tuned
|
||||
checkpoints default to ``False`` so ``low_effort`` is a no-op there —
|
||||
matching how the Nano template silently ignores it.
|
||||
"""
|
||||
return "super" in (getattr(tokenizer, "name_or_path", "") or "").lower()
|
||||
|
||||
|
||||
class Nemotron3Renderer:
|
||||
"""Deterministic message → token renderer for Nemotron 3 models."""
|
||||
"""Deterministic message → token renderer for Nemotron-3 Nano / Super.
|
||||
|
||||
The Ultra variant (distinct ``</think>`` glue) is the
|
||||
:class:`Nemotron3UltraRenderer` subclass below; both are registered under
|
||||
their own discriminator and differ only by the class-level hooks here.
|
||||
"""
|
||||
|
||||
# Variant hooks (overridden by ``Nemotron3UltraRenderer``): the default
|
||||
# config to build when none is passed, and whether to use Ultra's
|
||||
# reasoning-block glue.
|
||||
_config_cls: type = Nemotron3RendererConfig
|
||||
_ultra: bool = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: Nemotron3RendererConfig | Nemotron3UltraRendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
cfg = config or type(self)._config_cls()
|
||||
self.config = cfg
|
||||
if not cfg.truncate_history_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
elif not cfg.enable_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
else:
|
||||
implied_thinking_retention = "tool_cycle"
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
cfg,
|
||||
implied_thinking_retention,
|
||||
)
|
||||
|
||||
# Resolve the per-variant reasoning-effort hint appended to the last
|
||||
# user message. Ultra honours ``medium_effort``; Super honours
|
||||
# ``low_effort``; Nano honours neither. The non-matching kwarg is
|
||||
# silently ignored (empty hint), exactly as ``apply_chat_template``
|
||||
# ignores a template variable the variant's Jinja never defines.
|
||||
if self._ultra:
|
||||
self._effort_hint = (
|
||||
"\n\n{reasoning effort: efficient}"
|
||||
if getattr(cfg, "medium_effort", False)
|
||||
else ""
|
||||
)
|
||||
elif getattr(cfg, "low_effort", False) and _is_super(tokenizer):
|
||||
self._effort_hint = "\n\n{reasoning effort: low}"
|
||||
else:
|
||||
self._effort_hint = ""
|
||||
|
||||
# Look up special token IDs from the tokenizer (not hardcoded).
|
||||
# <|endoftext|> is optional: Nemotron-3 Nano / Super tokenizers ship
|
||||
# <|im_end|> as the sole EOS; older / larger variants additionally
|
||||
@@ -241,19 +296,44 @@ class Nemotron3Renderer:
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
|
||||
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) -> None:
|
||||
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
# ── 1. System message + optional tools ──────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
@@ -262,12 +342,14 @@ class Nemotron3Renderer:
|
||||
# Nemotron 3: system prompt BEFORE tools block
|
||||
sys_idx = orig_idx(0) if first_is_system else -1
|
||||
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False)
|
||||
emit_text("system\n", sys_idx, is_sampled=False)
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build system content: user's system text first, then tools
|
||||
# Build system content: user's system text first, then tools.
|
||||
# The template emits ``system_message`` verbatim (no trim) and
|
||||
# gates the ``\n\n`` separator on its raw length, so keep the
|
||||
# caller's content unstripped.
|
||||
if first_is_system:
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
sys_content = self._render_content(messages[0].get("content"))
|
||||
else:
|
||||
sys_content = ""
|
||||
|
||||
@@ -282,38 +364,48 @@ class Nemotron3Renderer:
|
||||
+ _TOOLS_INSTRUCTIONS
|
||||
)
|
||||
|
||||
# Body = caller's system text only; tools block (header, per-
|
||||
# tool XML, footer, instructions) is scaffold.
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
full_sys = sys_content + "\n\n" + tools_block
|
||||
else:
|
||||
full_sys = tools_block
|
||||
|
||||
emit_text(full_sys, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False)
|
||||
sys_segments.append((sys_content, True))
|
||||
sys_segments.append(("\n\n", False))
|
||||
sys_segments.append((tools_block, False))
|
||||
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
elif first_is_system:
|
||||
sys_idx = orig_idx(0)
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False)
|
||||
emit_text("system\n" + sys_content, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False)
|
||||
sys_content = self._render_content(messages[0].get("content"))
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
sys_segments2: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
sys_segments2.append((sys_content, True))
|
||||
emit_text_segments(sys_segments2, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Track the most-recent plain (non-tool-call) assistant so we can
|
||||
# preserve its reasoning while stripping reasoning from earlier
|
||||
# assistants — the Nemotron-3 template matches this pattern.
|
||||
last_plain_assistant_idx = -1
|
||||
# All Nemotron-3 variants (Nano / Super / Ultra) truncate historical
|
||||
# thinking on every assistant turn *before the last user message* —
|
||||
# the template rule ``truncate_history_thinking and loop.index0 <
|
||||
# last_user_idx`` is byte-identical across the three chat templates.
|
||||
# Compute the last-user index over the normalized ``messages`` list (a
|
||||
# leading system never holds a user, so the relative comparison is
|
||||
# unaffected).
|
||||
last_user_idx_norm = -1
|
||||
for j in range(len(messages) - 1, -1, -1):
|
||||
if messages[j].get("role") == "assistant" and not messages[j].get(
|
||||
"tool_calls"
|
||||
):
|
||||
last_plain_assistant_idx = j
|
||||
if messages[j].get("role") == "user":
|
||||
last_user_idx_norm = j
|
||||
break
|
||||
|
||||
# ── 2. Iterate messages ─────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
role = msg["role"]
|
||||
content = self._render_content(msg.get("content")).strip()
|
||||
# Keep content unstripped: the template emits user / system / tool
|
||||
# content verbatim, and assistant trimming happens inside
|
||||
# ``_assistant_body`` exactly where the template applies it.
|
||||
content = self._render_content(msg.get("content"))
|
||||
msg_orig_idx = orig_idx(i)
|
||||
|
||||
if role == "system":
|
||||
@@ -322,28 +414,37 @@ class Nemotron3Renderer:
|
||||
continue # Already handled above
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._im_start, msg_orig_idx, is_sampled=False)
|
||||
emit_text("user\n" + content, msg_orig_idx, is_sampled=False)
|
||||
emit_special(self._im_end, msg_orig_idx, is_sampled=False)
|
||||
emit_text("\n", msg_orig_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._im_start, msg_orig_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
# Reasoning-effort hint rides on the LAST user message only,
|
||||
# glued to the content so BPE sees them as one chunk (matching
|
||||
# the template's ``content + '\n\n{reasoning effort: …}'``). It
|
||||
# is template scaffold, not caller content → is_content=False.
|
||||
if self._effort_hint and i == last_user_idx_norm:
|
||||
user_segments.append((self._effort_hint, False))
|
||||
emit_text_segments(user_segments, msg_orig_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._im_end, msg_orig_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("\n", msg_orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
is_last_turn = i >= last_plain_assistant_idx
|
||||
preserve_thinking = msg_orig_idx >= 0 and should_preserve_past_thinking(
|
||||
original_messages,
|
||||
msg_orig_idx,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
# Template: ``include_content = not (truncate_history_thinking
|
||||
# and loop.index0 < last_user_idx)``.
|
||||
include_content = (
|
||||
not self.config.truncate_history_thinking or i >= last_user_idx_norm
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
msg_orig_idx,
|
||||
content,
|
||||
is_last_turn=is_last_turn,
|
||||
preserve_thinking=preserve_thinking,
|
||||
include_content=include_content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_ids=emit_ids,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
@@ -355,6 +456,7 @@ class Nemotron3Renderer:
|
||||
auto_system_injected=auto_system_injected,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
else:
|
||||
@@ -362,18 +464,23 @@ class Nemotron3Renderer:
|
||||
|
||||
# ── 3. Generation prompt ────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_start, -1, is_sampled=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False)
|
||||
emit_text("\n", -1, is_sampled=False)
|
||||
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
# Disable-thinking suffix: <think></think> with no trailing newlines
|
||||
emit_special(self._think, -1, is_sampled=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
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(
|
||||
@@ -393,7 +500,7 @@ class Nemotron3Renderer:
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — args land in a JSON object, schema not needed
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
stop_ids = {self._im_end}
|
||||
if self._endoftext is not None:
|
||||
@@ -406,6 +513,7 @@ class Nemotron3Renderer:
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
@@ -426,6 +534,17 @@ class Nemotron3Renderer:
|
||||
not previous_prompt_ids
|
||||
or not new_messages
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
# An active effort hint rides on the *last* user message. Appending
|
||||
# a new turn can move which user is last, which would strand the
|
||||
# hint on the frozen previous prompt — the append-only bridge can't
|
||||
# rewrite it. Bail so the caller does a full, correct re-render.
|
||||
or self._effort_hint
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
@@ -442,36 +561,76 @@ class Nemotron3Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't track sampled_mask here. Local helpers accept the kwarg
|
||||
# for signature compatibility with ``_render_tool`` and ignore
|
||||
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
|
||||
# empty.
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
emit_text("\n", -1)
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._render_content(msg.get("content")).strip()
|
||||
# Unstripped — the template emits user / system / tool content
|
||||
# verbatim (see :meth:`render`).
|
||||
content = self._render_content(msg.get("content"))
|
||||
if role == "user":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("user\n" + content, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "system":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("system\n" + content, i)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if content:
|
||||
sys_segments.append((content, True))
|
||||
emit_text_segments(sys_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "tool":
|
||||
@@ -483,6 +642,7 @@ class Nemotron3Renderer:
|
||||
auto_system_injected=False,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
@@ -490,14 +650,22 @@ class Nemotron3Renderer:
|
||||
# Generation prompt.
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
else:
|
||||
emit_special(self._think, -1)
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Assistant message rendering
|
||||
@@ -509,112 +677,122 @@ class Nemotron3Renderer:
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
is_last_turn: bool,
|
||||
preserve_thinking: bool = False,
|
||||
include_content: bool,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_ids,
|
||||
) -> None:
|
||||
# Extract reasoning_content
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
reasoning_content = msg["reasoning_content"]
|
||||
elif "</think>" in content:
|
||||
before_think_end, after_think_end = content.split("</think>", 1)
|
||||
if "<think>" in before_think_end:
|
||||
reasoning_content = before_think_end.split("<think>")[-1].lstrip("\n")
|
||||
else:
|
||||
reasoning_content = before_think_end.lstrip("\n")
|
||||
reasoning_content = reasoning_content.rstrip("\n")
|
||||
content = after_think_end.lstrip("\n")
|
||||
|
||||
reasoning_content = reasoning_content.strip()
|
||||
|
||||
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
|
||||
# at inference the chat template emits these as the generation
|
||||
# prompt and the model never samples them. Marking the role tag
|
||||
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
|
||||
# what the model would actually have produced.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False)
|
||||
# what the model would actually have produced. On assistant the
|
||||
# invariant ``is_content == sampled_mask`` holds.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Nemotron 3 keeps reasoning on the most-recent plain assistant but
|
||||
# strips it from historical turns, which collapse to an empty
|
||||
# <think></think> block. Empty <think></think> is also emitted when
|
||||
# the turn has no reasoning at all. The trailing ``\n`` (when
|
||||
# tool_calls follow) is glued to ``content`` in a single emit_text
|
||||
# so BPE sees ``content\n`` as one chunk, matching how
|
||||
# apply_chat_template tokenises the concatenated template string.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
# A \n is always required between the text/think block and the first
|
||||
# <tool_call>, whether the content is empty or not.
|
||||
content_suffix = "\n" if tool_calls else ""
|
||||
# Build the body (everything between ``assistant\n`` and ``<|im_end|>``)
|
||||
# as a single string mirroring the chat template's own string algebra,
|
||||
# then tokenise it in one pass. The ``<think>`` / ``</think>`` /
|
||||
# ``<tool_call>`` / ``</tool_call>`` markers are added tokens, so the
|
||||
# tokenizer isolates them — encoding the assembled body yields the same
|
||||
# ids as ``apply_chat_template`` (which likewise encodes a rendered
|
||||
# string). The whole body is sampled content; ``<|im_end|>`` is the
|
||||
# model's stop signal (sampled), and the inter-turn ``\n`` is not.
|
||||
body = self._assistant_body(msg, content, include_content=include_content)
|
||||
if body:
|
||||
emit_text(body, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if reasoning_content and (is_last_turn or preserve_thinking):
|
||||
emit_special(self._think, msg_idx, is_sampled=True)
|
||||
emit_text("\n" + reasoning_content + "\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
# Single \n separator (not \n\n like Qwen3.5)
|
||||
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=True)
|
||||
elif reasoning_content:
|
||||
# Historical assistant whose reasoning got stripped — template
|
||||
# keeps a single \n between the collapsed <think></think> and
|
||||
# the content as a marker that reasoning existed.
|
||||
emit_special(self._think, msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=True)
|
||||
def _assistant_body(
|
||||
self, msg: Message, raw_content: str, *, include_content: bool
|
||||
) -> str:
|
||||
"""Assemble the assistant body string exactly as the chat template.
|
||||
|
||||
``include_content`` is the template's ``not (truncate_history_thinking
|
||||
and loop.index0 < last_user_idx)`` (already OR-ed with the
|
||||
``thinking_retention`` override by the caller): ``True`` keeps the
|
||||
full think+content block,
|
||||
``False`` collapses historical thinking to an empty ``<think></think>``.
|
||||
"""
|
||||
ultra = self._ultra
|
||||
|
||||
# 1. Assemble ``content`` — wrap a ``reasoning_content`` field in
|
||||
# <think> tags (raw, not stripped: interior whitespace is part of
|
||||
# the reasoning), else prepend an empty <think></think> only when
|
||||
# the content carries no inline think tags of its own (which are
|
||||
# passed through verbatim, like the template).
|
||||
reasoning = msg.get("reasoning_content")
|
||||
if isinstance(reasoning, str) and reasoning.strip():
|
||||
if ultra:
|
||||
content = "<think>\n" + reasoning + "</think>" + raw_content
|
||||
else:
|
||||
content = "<think>\n" + reasoning + "\n</think>\n" + raw_content
|
||||
else:
|
||||
# No reasoning ever — <think></think> glued directly to content.
|
||||
emit_special(self._think, msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
emit_text(content + content_suffix, msg_idx, is_sampled=True)
|
||||
content = raw_content
|
||||
if "<think>" not in content and "</think>" not in content:
|
||||
content = "<think></think>" + content
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
|
||||
# Tool calls (leading \n was glued to the content above; each
|
||||
# iteration's trailing \n after </tool_call> handles the
|
||||
# separator to the next block).
|
||||
if tool_calls:
|
||||
parts: list[str] = []
|
||||
if content.strip():
|
||||
if include_content:
|
||||
parts.append(content.strip() + "\n")
|
||||
else:
|
||||
# Drop historical thinking: keep only what follows the last
|
||||
# </think> (or precedes a dangling <think>), then re-stamp
|
||||
# an empty block. Nano/Super trim the remainder; Ultra glues
|
||||
# it raw (its template omits the trailing ``| trim``).
|
||||
c = content
|
||||
if "</think>" in c:
|
||||
c = c.split("</think>")[-1]
|
||||
elif "<think>" in c:
|
||||
c = c.split("<think>")[0]
|
||||
c = "<think></think>" + (c if ultra else c.strip())
|
||||
if c:
|
||||
parts.append(c + "\n")
|
||||
else:
|
||||
# Non-string / empty content: bare collapsed think block, no \n.
|
||||
parts.append("<think></think>")
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
parts.append(self._format_tool_call(tc))
|
||||
return "".join(parts)
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True)
|
||||
emit_text("\n<function=" + name + ">\n", msg_idx, is_sampled=True)
|
||||
# No tool calls.
|
||||
if include_content:
|
||||
return content.strip()
|
||||
c = content
|
||||
if "<think>" in c and "</think>" in c:
|
||||
c = "<think></think>" + c.split("</think>")[-1]
|
||||
return c.strip()
|
||||
|
||||
# Render arguments
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
# per-argument rendering below still works.
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
if isinstance(arguments, dict):
|
||||
for arg_name, arg_value in arguments.items():
|
||||
if isinstance(arg_value, (dict, list)):
|
||||
value_str = json.dumps(arg_value, ensure_ascii=False)
|
||||
else:
|
||||
value_str = str(arg_value)
|
||||
emit_text(
|
||||
"<parameter="
|
||||
+ arg_name
|
||||
+ ">\n"
|
||||
+ value_str
|
||||
+ "\n</parameter>\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
)
|
||||
|
||||
emit_text("</function>\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
|
||||
# Trailing \n after </tool_call> (Nemotron 3 specific)
|
||||
emit_text("\n", msg_idx, is_sampled=True)
|
||||
|
||||
# ``<|im_end|>`` is the model's stop signal — it samples this to
|
||||
# end its turn, so it is part of the sampled stream. The trailing
|
||||
# ``\n`` is template-appended between turns and never sampled.
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
@staticmethod
|
||||
def _format_tool_call(tc: dict[str, Any]) -> str:
|
||||
"""Render one tool call as ``<tool_call>…</tool_call>\\n`` XML."""
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
# per-argument rendering below still works.
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
parts = ["<tool_call>\n<function=" + name + ">\n"]
|
||||
if isinstance(arguments, dict):
|
||||
for arg_name, arg_value in arguments.items():
|
||||
if isinstance(arg_value, (dict, list)):
|
||||
value_str = json.dumps(arg_value, ensure_ascii=False)
|
||||
else:
|
||||
value_str = str(arg_value)
|
||||
parts.append(
|
||||
"<parameter=" + arg_name + ">\n" + value_str + "\n</parameter>\n"
|
||||
)
|
||||
parts.append("</function>\n</tool_call>\n")
|
||||
return "".join(parts)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Tool message rendering
|
||||
@@ -630,10 +808,13 @@ class Nemotron3Renderer:
|
||||
auto_system_injected: bool,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False.
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# body bytes get ``is_content=True``; the surrounding wrap is
|
||||
# scaffold.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
@@ -641,17 +822,33 @@ class Nemotron3Renderer:
|
||||
oi = msg_orig_idx
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._im_start, oi, is_sampled=False)
|
||||
emit_text("user\n", oi, is_sampled=False)
|
||||
emit_special(self._im_start, oi, is_sampled=False, is_content=False)
|
||||
emit_text("user\n", oi, is_sampled=False, is_content=False)
|
||||
# else: the previous tool's trailing \n already provides the
|
||||
# separator into this block.
|
||||
|
||||
emit_special(self._tool_response, oi, is_sampled=False)
|
||||
emit_text("\n" + content + "\n", oi, is_sampled=False)
|
||||
emit_special(self._tool_response_end, oi, is_sampled=False)
|
||||
emit_special(self._tool_response, oi, is_sampled=False, is_content=False)
|
||||
emit_text_segments(
|
||||
[("\n", False), (content, True), ("\n", False)], oi, is_sampled=False
|
||||
)
|
||||
emit_special(self._tool_response_end, oi, is_sampled=False, is_content=False)
|
||||
# Nemotron 3: trailing \n after </tool_response>
|
||||
emit_text("\n", oi, is_sampled=False)
|
||||
emit_text("\n", oi, is_sampled=False, is_content=False)
|
||||
|
||||
if not next_is_tool:
|
||||
emit_special(self._im_end, oi, is_sampled=False)
|
||||
emit_text("\n", oi, is_sampled=False)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
emit_text("\n", oi, is_sampled=False, is_content=False)
|
||||
|
||||
|
||||
class Nemotron3UltraRenderer(Nemotron3Renderer):
|
||||
"""Renderer for Nemotron-3 **Ultra**.
|
||||
|
||||
Identical to :class:`Nemotron3Renderer` except the reasoning block is glued
|
||||
as ``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around
|
||||
``</think>``) and truncated historical turns collapse to
|
||||
``<think></think>{content}`` (no ``\\n``) — the difference is carried by the
|
||||
``_ultra`` class hook. Honours the Ultra-only ``medium_effort`` kwarg.
|
||||
"""
|
||||
|
||||
_config_cls = Nemotron3UltraRendererConfig
|
||||
_ultra = True
|
||||
|
||||
@@ -20,6 +20,7 @@ import re
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from renderers.base import ParsedToolCall, ToolCallParseStatus
|
||||
from renderers.hermes import HermesToolParser
|
||||
|
||||
|
||||
# ── Shared helpers ───────────────────────────────────────────────────
|
||||
@@ -458,6 +459,7 @@ class ThinkTextReasoningParser:
|
||||
|
||||
|
||||
TOOL_PARSERS: dict[str, type] = {
|
||||
"hermes": HermesToolParser,
|
||||
"qwen3": Qwen3ToolParser,
|
||||
"qwen3.5": Qwen35ToolParser,
|
||||
"glm": GlmToolParser,
|
||||
|
||||
+376
-29
@@ -65,30 +65,36 @@ def _coerce_arg_value(
|
||||
"""Coerce a raw ``<arg_value>`` body to its declared type.
|
||||
|
||||
Returns ``(value, used_json_fallback)``. The boolean is ``True`` only
|
||||
when ``json.loads`` was attempted and raised, so the caller knows
|
||||
whether to flag ``INVALID_JSON``. Returning a string verbatim
|
||||
because the schema declared ``type: "string"`` is NOT a fallback.
|
||||
when ``json.loads`` was attempted, raised, AND the schema doesn't
|
||||
permit a string. Returning a string verbatim because the schema
|
||||
permits strings is NOT a fallback.
|
||||
|
||||
Rule (matches vLLM / SGLang reference parsers):
|
||||
|
||||
- If the param's declared ``type`` is ``"string"`` (or single-element
|
||||
``["string"]``), return ``text`` verbatim — never ``json.loads``.
|
||||
- Anything else (no schema, non-string scalar, object, array, or
|
||||
union types that include non-string): try ``json.loads`` and fall
|
||||
back to raw ``text`` on parse failure.
|
||||
- Otherwise try ``json.loads``. If that fails, return raw ``text``.
|
||||
The ``used_json_fallback`` flag is ``True`` only when the schema
|
||||
does NOT permit a string — i.e. the fallback is truly suspect.
|
||||
|
||||
Union types that include ``"string"`` alongside other types still
|
||||
attempt ``json.loads`` first so an explicit integer / bool can
|
||||
parse; the string branch only wins as the fallback.
|
||||
Union types (``anyOf``/``oneOf``) that include ``"string"`` alongside
|
||||
other types still attempt ``json.loads`` first so an explicit
|
||||
integer / bool can parse; the string branch wins as fallback, and
|
||||
landing there is expected — not a malformed-JSON signal.
|
||||
"""
|
||||
string_is_allowed = False
|
||||
if param_schema is not None:
|
||||
declared = param_schema.get("type")
|
||||
if declared == "string" or declared == ["string"]:
|
||||
return text, False
|
||||
for branch in param_schema.get("anyOf") or param_schema.get("oneOf") or []:
|
||||
if isinstance(branch, dict) and branch.get("type") == "string":
|
||||
string_is_allowed = True
|
||||
break
|
||||
try:
|
||||
return json.loads(text), False
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return text, True
|
||||
return text, not string_is_allowed
|
||||
|
||||
|
||||
def _find(ids: list[int], target: int, start: int = 0) -> int:
|
||||
@@ -127,6 +133,39 @@ def _decode(tokenizer, ids: list[int]) -> str:
|
||||
return tokenizer.decode(ids, skip_special_tokens=False)
|
||||
|
||||
|
||||
def _reasoning_end_token_index(
|
||||
tokenizer, ids: list[int], marker: str = "</think>"
|
||||
) -> int:
|
||||
"""Token index immediately past the first ``</think>`` in ``ids``.
|
||||
|
||||
Returns 0 when ``ids`` has no closed reasoning region — callers treat
|
||||
that as "scan from the start" (preserves pre-existing behavior for
|
||||
non-thinking / truncated-reasoning completions).
|
||||
|
||||
Used by parsers whose ``</think>`` is *not* a single special token
|
||||
(DeepSeek-V3, Kimi-K2.5) — where it tokenizes to several pieces and is
|
||||
context-sensitive (the closing ``>`` merges differently depending on the
|
||||
next char), so a token-id or fixed-subsequence search isn't reliable. We
|
||||
instead locate the boundary in decoded text via binary search over prefix
|
||||
decodes, which holds as long as ``decode(ids[:k])`` is prefix-stable in
|
||||
``k`` (true for the byte-level BPE tokenizers here; ``</think>`` is clean
|
||||
ASCII that won't straddle a byte boundary). Single-token ``</think>``
|
||||
parsers (Qwen3) anchor on the token id directly and don't need this.
|
||||
"""
|
||||
if not ids or marker not in _decode(tokenizer, ids):
|
||||
return 0
|
||||
# Smallest prefix length (in tokens) whose decode already contains the
|
||||
# full marker — i.e. the index just past where </think> completes.
|
||||
lo, hi = 1, len(ids)
|
||||
while lo < hi:
|
||||
mid = (lo + hi) // 2
|
||||
if marker in _decode(tokenizer, ids[:mid]):
|
||||
hi = mid
|
||||
else:
|
||||
lo = mid + 1
|
||||
return lo
|
||||
|
||||
|
||||
# ── Qwen3: <tool_call> JSON </tool_call> ────────────────────────────
|
||||
|
||||
|
||||
@@ -137,11 +176,26 @@ def parse_qwen3(
|
||||
stop_ids: set[int],
|
||||
tool_call_id: int,
|
||||
tool_call_end_id: int,
|
||||
reasoning_end_id: int | None = None,
|
||||
) -> ParsedResponse:
|
||||
"""Parse Qwen3 completion tokens. Hermes-style JSON tool calls."""
|
||||
ids = _strip_stop_tokens(token_ids, stop_ids)
|
||||
|
||||
tc_start = _find(ids, tool_call_id)
|
||||
# Reasoning is resolved before tool calls. Thinking models (e.g.
|
||||
# Qwen3-*-Thinking) routinely draft ``<tool_call>`` blocks *inside* their
|
||||
# ``<think>...</think>`` trace while planning; those are reasoning, not
|
||||
# real invocations. Anchoring the tool-call scan after the ``</think>``
|
||||
# boundary keeps in-think drafts out of ``tool_calls`` (otherwise they
|
||||
# surface as phantom/duplicate calls) and out of the reasoning/content
|
||||
# split. Mirrors vLLM's DelegatingParser, which runs the reasoning parser
|
||||
# first and tool-parses only the post-``</think>`` content.
|
||||
# ``reasoning_end_id`` is the ``</think>`` token id; when it's absent
|
||||
# (``None``) or the model never closed its reasoning, the scan falls back
|
||||
# to the whole stream (prior behavior).
|
||||
reasoning_end = _find(ids, reasoning_end_id) if reasoning_end_id is not None else -1
|
||||
scan_start = reasoning_end + 1 if reasoning_end != -1 else 0
|
||||
|
||||
tc_start = _find(ids, tool_call_id, scan_start)
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
if tc_start != -1:
|
||||
content_ids = ids[:tc_start]
|
||||
@@ -502,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
|
||||
@@ -518,32 +771,40 @@ def parse_laguna_xs2(
|
||||
tool_call_id: int,
|
||||
tool_call_end_id: int,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
strip_newlines: bool = True,
|
||||
) -> ParsedResponse:
|
||||
"""Parse Laguna-XS.2 completion tokens.
|
||||
"""Parse Laguna-XS.2 / XS-2.1 completion tokens.
|
||||
|
||||
Thinking uses single-token ``<think>`` / ``</think>`` (ids found by
|
||||
scan). Tool calls are delimited by single-token ``<tool_call>`` /
|
||||
``</tool_call>``, but ``<arg_key>`` / ``<arg_value>`` inside are
|
||||
plain text — regex-extracted from the decoded inner block.
|
||||
|
||||
``strip_newlines`` mirrors the template's whitespace around reasoning
|
||||
and content. XS.2 wraps reasoning with ``\\n`` on both sides
|
||||
(``<think>\\n{r}\\n</think>``) and brackets post-think content with
|
||||
``\\n`` too (``</think>\\n{c}\\n``) — strip exactly those newlines,
|
||||
never a bare ``.strip()``, which would also eat whitespace the model
|
||||
emitted intentionally. XS-2.1 renders both segments verbatim, so it
|
||||
parses with ``strip_newlines=False``.
|
||||
"""
|
||||
ids = _strip_stop_tokens(token_ids, stop_ids)
|
||||
|
||||
# The template wraps reasoning with ``\n`` on both sides
|
||||
# (``<think>\n{r}\n</think>``) and brackets post-think content with ``\n``
|
||||
# too (``</think>\n{c}\n``). Strip exactly those newlines from each
|
||||
# decoded segment — never a bare ``.strip()``, which would also eat
|
||||
# whitespace the model emitted intentionally.
|
||||
def _segment(segment_ids: list[int]) -> str:
|
||||
text = _decode(tokenizer, segment_ids)
|
||||
return text.strip("\n") if strip_newlines else text
|
||||
|
||||
reasoning = None
|
||||
parse_offset = 0
|
||||
think_end = _find(ids, think_end_id)
|
||||
if think_end != -1:
|
||||
reasoning_ids = ids[:think_end]
|
||||
reasoning_ids = [t for t in reasoning_ids if t != think_id]
|
||||
reasoning = _decode(tokenizer, reasoning_ids).strip("\n")
|
||||
reasoning = _segment(reasoning_ids)
|
||||
ids = ids[think_end + 1 :]
|
||||
parse_offset = think_end + 1
|
||||
elif (think_start := _find(ids, think_id)) != -1:
|
||||
reasoning = _decode(tokenizer, ids[think_start + 1 :]).strip("\n")
|
||||
reasoning = _segment(ids[think_start + 1 :])
|
||||
return ParsedResponse(
|
||||
content="", reasoning_content=reasoning or None, tool_calls=[]
|
||||
)
|
||||
@@ -551,7 +812,7 @@ def parse_laguna_xs2(
|
||||
tc_start = _find(ids, tool_call_id)
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
if tc_start != -1:
|
||||
content_text = _decode(tokenizer, ids[:tc_start]).strip("\n")
|
||||
content_text = _segment(ids[:tc_start])
|
||||
tool_calls = _parse_laguna_xs2_tool_calls(
|
||||
tokenizer,
|
||||
ids[tc_start:],
|
||||
@@ -561,7 +822,7 @@ def parse_laguna_xs2(
|
||||
param_index=_build_param_type_index(tools),
|
||||
)
|
||||
else:
|
||||
content_text = _decode(tokenizer, ids).strip("\n")
|
||||
content_text = _segment(ids)
|
||||
|
||||
return ParsedResponse(
|
||||
content=content_text,
|
||||
@@ -579,17 +840,20 @@ def _parse_laguna_xs2_tool_calls(
|
||||
section_offset: int,
|
||||
param_index: dict[str, dict[str, dict[str, Any]]],
|
||||
) -> list[ParsedToolCall]:
|
||||
"""Parse Laguna-XS.2 tool calls.
|
||||
"""Parse Laguna-XS.2 / XS-2.1 tool calls.
|
||||
|
||||
Inside each ``<tool_call>...</tool_call>`` block, the format is::
|
||||
|
||||
{name}\\n
|
||||
<arg_key>{k1}</arg_key>\\n<arg_value>{v1}</arg_value>\\n
|
||||
{name}
|
||||
<arg_key>{k1}</arg_key><arg_value>{v1}</arg_value>
|
||||
...
|
||||
<arg_key>{kn}</arg_key>\\n<arg_value>{vn}</arg_value>\\n
|
||||
<arg_key>{kn}</arg_key><arg_value>{vn}</arg_value>
|
||||
|
||||
The function name is everything before the first ``<arg_key>`` literal
|
||||
in the decoded block.
|
||||
XS.2 puts a ``\\n`` after the name and between the tag pairs; XS-2.1
|
||||
packs everything tightly. The function name is everything before the
|
||||
first ``<arg_key>`` literal in the decoded block (stripped), and the
|
||||
key/value regex allows optional whitespace between the tags, so both
|
||||
layouts parse identically.
|
||||
"""
|
||||
import re
|
||||
|
||||
@@ -679,7 +943,15 @@ def parse_deepseek_v3(
|
||||
"""
|
||||
ids = _strip_stop_tokens(token_ids, stop_ids)
|
||||
|
||||
tc_section_start = _find(ids, tool_calls_begin_id)
|
||||
# Reasoning first: skip past </think> before looking for the tool-call
|
||||
# section, so a section the model drafts *inside* its <think> trace isn't
|
||||
# parsed as a real call (regression #78 — cf. parse_qwen3). content_ids
|
||||
# still starts at 0, so the </think> text-split below recovers reasoning.
|
||||
# DeepSeek-V3 renders </think> as multi-token text, hence the decode-based
|
||||
# boundary finder rather than a token-id anchor.
|
||||
reasoning_end = _reasoning_end_token_index(tokenizer, ids)
|
||||
|
||||
tc_section_start = _find(ids, tool_calls_begin_id, reasoning_end)
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
if tc_section_start != -1:
|
||||
content_ids = ids[:tc_section_start]
|
||||
@@ -956,6 +1228,7 @@ def parse_kimi_k2_section(
|
||||
tool_call_begin_id: int,
|
||||
tool_call_argument_begin_id: int,
|
||||
tool_call_end_id: int,
|
||||
scan_start: int = 0,
|
||||
) -> tuple[list[int], list[ParsedToolCall]]:
|
||||
"""Split ``ids`` into ``(content_before_section, tool_calls)`` by finding
|
||||
the Kimi-style tool-call section delimiters.
|
||||
@@ -967,8 +1240,15 @@ def parse_kimi_k2_section(
|
||||
of the section and a list of ``ParsedToolCall`` covering every attempted
|
||||
block inside it; an unclosed section is still walked to whatever the model
|
||||
emitted before EOS. Returns ``(ids, [])`` when no section is present.
|
||||
|
||||
``scan_start`` restricts the section search to ``ids[scan_start:]`` while
|
||||
keeping ``content_ids = ids[:section_start]`` and all token spans relative
|
||||
to the full ``ids``. Callers pass the post-``</think>`` index so a section
|
||||
the model drafts inside its reasoning trace isn't parsed as a real call;
|
||||
because ``content_ids`` still starts at 0, downstream text-based reasoning
|
||||
extraction is unaffected (regression #78).
|
||||
"""
|
||||
section_start = _find_any(ids, tool_calls_section_begin_ids)
|
||||
section_start = _find_any(ids, tool_calls_section_begin_ids, scan_start)
|
||||
if section_start == -1:
|
||||
return list(ids), []
|
||||
content_ids = ids[:section_start]
|
||||
@@ -1264,3 +1544,70 @@ def _gptoss_extract_after_token(
|
||||
return None
|
||||
after = _decode(tokenizer, header_ids[pos + 1 :]).strip()
|
||||
return after.split()[0] if after else None
|
||||
|
||||
|
||||
# ── Llama-3: single JSON tool call {"name": "...", "parameters": {...}} ─
|
||||
|
||||
|
||||
def parse_llama_3(
|
||||
tokenizer,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
stop_ids: set[int],
|
||||
) -> ParsedResponse:
|
||||
"""Parse Llama-3 completion tokens.
|
||||
|
||||
The Llama-3 chat template emits tool calls as a single JSON blob in
|
||||
the assistant body — ``{"name": "...", "parameters": {...}}`` — with
|
||||
no surrounding XML tags or special tokens. Plain replies are just
|
||||
text. We detect the tool-call shape with a strict starts-with-``{``
|
||||
+ parses-as-dict-with-name-key check; anything else is treated as
|
||||
content. Llama-3 doesn't have a built-in reasoning channel, so
|
||||
``reasoning_content`` is always ``None``.
|
||||
|
||||
Unlike the delimiter-based formats (Qwen/GLM), the tool call has no
|
||||
special token to anchor on, so a leading assistant role-header
|
||||
(``<|start_header_id|>assistant<|end_header_id|>\\n\\n``) would defeat
|
||||
the starts-with-``{`` check. Callers that slice a completion without
|
||||
dropping the generation prompt include that scaffold; we skip past the
|
||||
final ``<|end_header_id|>`` so the body is what we parse. The sampled
|
||||
stream in production carries no header, making this a no-op there.
|
||||
"""
|
||||
ids = _strip_stop_tokens(token_ids, stop_ids)
|
||||
|
||||
# Skip a leading assistant role-header scaffold if present.
|
||||
body_start = 0
|
||||
end_header_id = tokenizer.convert_tokens_to_ids("<|end_header_id|>")
|
||||
if isinstance(end_header_id, int):
|
||||
eh_positions = _find_all(ids, end_header_id)
|
||||
if eh_positions:
|
||||
body_start = eh_positions[-1] + 1
|
||||
body_ids = ids[body_start:]
|
||||
text = _decode(tokenizer, body_ids).strip()
|
||||
|
||||
if text.startswith("{") and text.endswith("}"):
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
parsed = None
|
||||
if isinstance(parsed, dict) and parsed.get("name"):
|
||||
arguments = parsed.get("parameters", parsed.get("arguments", {}))
|
||||
return ParsedResponse(
|
||||
content="",
|
||||
reasoning_content=None,
|
||||
tool_calls=[
|
||||
ParsedToolCall(
|
||||
raw=text,
|
||||
name=parsed["name"],
|
||||
arguments=arguments,
|
||||
token_span=(body_start, len(ids)),
|
||||
status=ToolCallParseStatus.OK,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
# Not a tool-call shape (plain reply, or a ``{...}`` body that didn't
|
||||
# parse / lacked a name). Llama-3 has no delimiter to anchor a
|
||||
# "malformed attempt" against, so it falls through to content rather
|
||||
# than producing a non-OK ParsedToolCall.
|
||||
return ParsedResponse(content=text, reasoning_content=None)
|
||||
|
||||
@@ -0,0 +1,694 @@
|
||||
"""PrimeIntellect Qwen3 renderer with exact chat-template tokenization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Mapping, Sequence
|
||||
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,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import PrimeQwen3RendererConfig
|
||||
from renderers.parsing import parse_qwen35
|
||||
|
||||
_DEFAULT_TOOL_SYSTEM = "You are Qwen, a helpful AI assistant that can interact with a computer to solve tasks."
|
||||
_TOOLS_HEADER = "\n\n# Tools\n\nYou have access to the following functions:\n\n<tools>"
|
||||
_TOOLS_FOOTER = (
|
||||
"\n</tools>\n\n"
|
||||
"If you choose to call a function ONLY reply in the following format with NO suffix:"
|
||||
"\n\n<tool_call>\n<function=example_function_name>"
|
||||
"\n<parameter=example_parameter_1>\nvalue_1\n</parameter>"
|
||||
"\n<parameter=example_parameter_2>"
|
||||
"\nThis is the value for the second parameter"
|
||||
"\nthat can span\nmultiple lines\n</parameter>"
|
||||
"\n</function>\n</tool_call>"
|
||||
"\n\n<IMPORTANT>\nReminder:"
|
||||
"\n- Function calls MUST follow the specified format: an inner "
|
||||
"<function=...></function> block must be nested within "
|
||||
"<tool_call></tool_call> XML tags"
|
||||
"\n- Required parameters MUST be specified"
|
||||
"\n- You may provide optional reasoning for your function call in natural "
|
||||
"language BEFORE the function call, but NOT after"
|
||||
"\n- If there is no function call available, answer the question like normal "
|
||||
"with your current knowledge and do not tell the user about function calls"
|
||||
"\n</IMPORTANT>"
|
||||
)
|
||||
|
||||
|
||||
def _render_extra_keys(
|
||||
value: Any,
|
||||
handled_keys: frozenset[str],
|
||||
) -> str:
|
||||
if not isinstance(value, Mapping):
|
||||
return ""
|
||||
|
||||
rendered: list[str] = []
|
||||
for key, item in value.items():
|
||||
if key in handled_keys:
|
||||
continue
|
||||
item_text = (
|
||||
json.dumps(item, ensure_ascii=False)
|
||||
if isinstance(item, Mapping)
|
||||
or (
|
||||
isinstance(item, Sequence)
|
||||
and not isinstance(item, (str, bytes, bytearray))
|
||||
)
|
||||
else str(item)
|
||||
)
|
||||
rendered.append(f"\n<{key}>{item_text}</{key}>")
|
||||
return "".join(rendered)
|
||||
|
||||
|
||||
def _tool_definition(tool: ToolSpec) -> str:
|
||||
raw_tool: Any = tool
|
||||
if isinstance(raw_tool, Mapping) and isinstance(raw_tool.get("function"), Mapping):
|
||||
raw_tool = raw_tool["function"]
|
||||
if not isinstance(raw_tool, Mapping):
|
||||
raise TypeError("Tool definitions must be mappings.")
|
||||
|
||||
rendered = "\n<function>\n<name>" + str(raw_tool.get("name", "")) + "</name>"
|
||||
if "description" in raw_tool:
|
||||
rendered += (
|
||||
"\n<description>" + str(raw_tool["description"]).strip() + "</description>"
|
||||
)
|
||||
rendered += "\n<parameters>"
|
||||
|
||||
parameters = raw_tool.get("parameters")
|
||||
if isinstance(parameters, Mapping):
|
||||
properties = parameters.get("properties")
|
||||
if isinstance(properties, Mapping):
|
||||
for param_name, param_fields in properties.items():
|
||||
rendered += "\n<parameter>\n<name>" + str(param_name) + "</name>"
|
||||
if isinstance(param_fields, Mapping):
|
||||
if "type" in param_fields:
|
||||
rendered += "\n<type>" + str(param_fields["type"]) + "</type>"
|
||||
if "description" in param_fields:
|
||||
rendered += (
|
||||
"\n<description>"
|
||||
+ str(param_fields["description"]).strip()
|
||||
+ "</description>"
|
||||
)
|
||||
rendered += _render_extra_keys(
|
||||
param_fields,
|
||||
frozenset({"name", "type", "description"}),
|
||||
)
|
||||
rendered += "\n</parameter>"
|
||||
rendered += _render_extra_keys(
|
||||
parameters,
|
||||
frozenset({"type", "properties"}),
|
||||
)
|
||||
|
||||
rendered += "\n</parameters>"
|
||||
rendered += _render_extra_keys(
|
||||
raw_tool,
|
||||
frozenset({"type", "name", "description", "parameters"}),
|
||||
)
|
||||
rendered += "\n</function>"
|
||||
return rendered
|
||||
|
||||
|
||||
class _TokenBuilder:
|
||||
def __init__(self, tokenizer: PreTrainedTokenizer):
|
||||
self.tokenizer = tokenizer
|
||||
self.token_ids: list[int] = []
|
||||
self.message_indices: list[int] = []
|
||||
self.sampled_mask: list[bool] = []
|
||||
self.is_content: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
self,
|
||||
token_id: int,
|
||||
message_index: int,
|
||||
*,
|
||||
sampled: bool,
|
||||
content: bool,
|
||||
) -> None:
|
||||
self.token_ids.append(token_id)
|
||||
self.message_indices.append(message_index)
|
||||
self.sampled_mask.append(sampled)
|
||||
self.is_content.append(content)
|
||||
|
||||
def emit_text(
|
||||
self,
|
||||
text: str,
|
||||
message_index: int,
|
||||
*,
|
||||
sampled: bool,
|
||||
content: bool,
|
||||
) -> None:
|
||||
if not text:
|
||||
return
|
||||
token_ids = self.tokenizer.encode(text, add_special_tokens=False)
|
||||
self.token_ids.extend(token_ids)
|
||||
self.message_indices.extend([message_index] * len(token_ids))
|
||||
self.sampled_mask.extend([sampled] * len(token_ids))
|
||||
self.is_content.extend([content] * len(token_ids))
|
||||
|
||||
def emit_segments(
|
||||
self,
|
||||
segments: list[tuple[str, bool]],
|
||||
message_index: int,
|
||||
*,
|
||||
sampled: bool,
|
||||
) -> None:
|
||||
for token_id, content in attribute_text_segments(self.tokenizer, segments):
|
||||
self.token_ids.append(token_id)
|
||||
self.message_indices.append(message_index)
|
||||
self.sampled_mask.append(sampled)
|
||||
self.is_content.append(content)
|
||||
|
||||
def emit_assistant_segments(
|
||||
self,
|
||||
segments: list[tuple[str, bool]],
|
||||
message_index: int,
|
||||
) -> None:
|
||||
for token_id, content in attribute_text_segments(self.tokenizer, segments):
|
||||
self.token_ids.append(token_id)
|
||||
self.message_indices.append(message_index)
|
||||
self.sampled_mask.append(content)
|
||||
self.is_content.append(content)
|
||||
|
||||
def prepend_prior(self, token_ids: list[int]) -> None:
|
||||
self.token_ids.extend(token_ids)
|
||||
self.message_indices.extend([-1] * len(token_ids))
|
||||
self.sampled_mask.extend([False] * len(token_ids))
|
||||
self.is_content.extend([False] * len(token_ids))
|
||||
|
||||
|
||||
class PrimeQwen3Renderer:
|
||||
"""Renderer for PrimeIntellect/Qwen3-0.6B and Qwen3-1.7B."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: PrimeQwen3RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or PrimeQwen3RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
self._im_end = self._token_id("<|im_end|>")
|
||||
self._endoftext = self._token_id("<|endoftext|>")
|
||||
self._think = self._token_id("<think>")
|
||||
self._think_end = self._token_id("</think>")
|
||||
self._tool_call = self._token_id("<tool_call>")
|
||||
self._tool_call_end = self._token_id("</tool_call>")
|
||||
self._tool_response = self._token_id("<tool_response>")
|
||||
self._tool_response_end = self._token_id("</tool_response>")
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
token_id = self._tokenizer.convert_tokens_to_ids(token)
|
||||
assert isinstance(token_id, int) and token_id != self._tokenizer.unk_token_id, (
|
||||
f"Token {token!r} not found in tokenizer vocabulary"
|
||||
)
|
||||
return token_id
|
||||
|
||||
@staticmethod
|
||||
def _content(message: Message) -> str:
|
||||
content = message.get("content")
|
||||
if content is None:
|
||||
return ""
|
||||
if not isinstance(content, str):
|
||||
raise TypeError("PrimeQwen3Renderer only supports string message content.")
|
||||
return content
|
||||
|
||||
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.")
|
||||
|
||||
builder = _TokenBuilder(self._tokenizer)
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
loop_start = 1 if first_is_system else 0
|
||||
|
||||
if first_is_system or tools:
|
||||
system_index = 0 if first_is_system else -1
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
system_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
system_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if first_is_system:
|
||||
system_segments.append((self._content(messages[0]), True))
|
||||
else:
|
||||
system_segments.append((_DEFAULT_TOOL_SYSTEM, False))
|
||||
|
||||
if tools:
|
||||
tools_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tools_text += _tool_definition(tool)
|
||||
tools_text += _TOOLS_FOOTER
|
||||
system_segments.append((tools_text, False))
|
||||
|
||||
builder.emit_segments(system_segments, system_index, sampled=False)
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
system_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
system_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
loop_messages = messages[loop_start:]
|
||||
for loop_index, message in enumerate(loop_messages):
|
||||
message_index = loop_start + loop_index
|
||||
role = message.get("role", "")
|
||||
if role == "assistant":
|
||||
tool_calls = message.get("tool_calls")
|
||||
if tool_calls:
|
||||
self._render_assistant_tool_calls(
|
||||
message,
|
||||
message_index,
|
||||
builder,
|
||||
)
|
||||
else:
|
||||
self._render_assistant(message, message_index, builder)
|
||||
elif role == "tool":
|
||||
opens_group = (
|
||||
loop_index > 0
|
||||
and loop_messages[loop_index - 1].get("role") != "tool"
|
||||
)
|
||||
closes_group = (
|
||||
loop_index == len(loop_messages) - 1
|
||||
or loop_messages[loop_index + 1].get("role") != "tool"
|
||||
)
|
||||
self._render_tool(
|
||||
message,
|
||||
message_index,
|
||||
builder,
|
||||
opens_group=opens_group,
|
||||
closes_group=closes_group,
|
||||
)
|
||||
else:
|
||||
self._render_history_message(message, message_index, builder)
|
||||
|
||||
if add_generation_prompt:
|
||||
self._render_generation_prompt(builder)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=builder.token_ids,
|
||||
message_indices=builder.message_indices,
|
||||
sampled_mask=builder.sampled_mask,
|
||||
is_content=builder.is_content,
|
||||
message_roles=[message.get("role") or "" for message in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def _render_history_message(
|
||||
self,
|
||||
message: Message,
|
||||
message_index: int,
|
||||
builder: _TokenBuilder,
|
||||
) -> None:
|
||||
role = message.get("role", "")
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_segments(
|
||||
[(role + "\n", False), (self._content(message), True)],
|
||||
message_index,
|
||||
sampled=False,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
message: Message,
|
||||
message_index: int,
|
||||
builder: _TokenBuilder,
|
||||
) -> None:
|
||||
content = self._content(message)
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
if "reasoning_content" in message:
|
||||
builder.emit_text(
|
||||
"assistant\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._think,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
reasoning = message.get("reasoning_content")
|
||||
if reasoning:
|
||||
builder.emit_text(
|
||||
str(reasoning).strip(),
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._think_end,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
if content.strip():
|
||||
builder.emit_text(
|
||||
"\n" + content.strip(),
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
else:
|
||||
builder.emit_assistant_segments(
|
||||
[("assistant\n", False), (content, True)],
|
||||
message_index,
|
||||
)
|
||||
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def _render_assistant_tool_calls(
|
||||
self,
|
||||
message: Message,
|
||||
message_index: int,
|
||||
builder: _TokenBuilder,
|
||||
) -> None:
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
content = message.get("content")
|
||||
trimmed_content = content.strip() if isinstance(content, str) else ""
|
||||
opener_segments = [("assistant\n", False)]
|
||||
if trimmed_content:
|
||||
opener_segments.append((trimmed_content + "\n\n", True))
|
||||
builder.emit_assistant_segments(opener_segments, message_index)
|
||||
|
||||
tool_calls = message.get("tool_calls") or []
|
||||
for tool_call_index, tool_call in enumerate(tool_calls):
|
||||
raw_call: Any = tool_call
|
||||
if isinstance(raw_call, Mapping) and isinstance(
|
||||
raw_call.get("function"), Mapping
|
||||
):
|
||||
raw_call = raw_call["function"]
|
||||
if not isinstance(raw_call, Mapping):
|
||||
raise TypeError("Tool calls must be mappings.")
|
||||
|
||||
builder.emit_special(
|
||||
self._tool_call,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
call_text = "\n<function=" + str(raw_call.get("name", "")) + ">\n"
|
||||
if "arguments" in raw_call:
|
||||
arguments = raw_call["arguments"]
|
||||
# OpenAI canonical form serializes arguments as a JSON string;
|
||||
# degrade malformed payloads to no parameters like Qwen3.5.
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
if not isinstance(arguments, Mapping):
|
||||
arguments = {}
|
||||
for argument_name, argument_value in arguments.items():
|
||||
value_text = (
|
||||
json.dumps(argument_value, ensure_ascii=False)
|
||||
if isinstance(argument_value, Mapping)
|
||||
or (
|
||||
isinstance(argument_value, Sequence)
|
||||
and not isinstance(argument_value, (str, bytes, bytearray))
|
||||
)
|
||||
else str(argument_value)
|
||||
)
|
||||
call_text += (
|
||||
"<parameter="
|
||||
+ str(argument_name)
|
||||
+ ">\n"
|
||||
+ value_text
|
||||
+ "\n</parameter>\n"
|
||||
)
|
||||
call_text += "</function>\n"
|
||||
builder.emit_text(
|
||||
call_text,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._tool_call_end,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
if tool_call_index < len(tool_calls) - 1:
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
message: Message,
|
||||
message_index: int,
|
||||
builder: _TokenBuilder,
|
||||
*,
|
||||
opens_group: bool,
|
||||
closes_group: bool,
|
||||
) -> None:
|
||||
if opens_group:
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"user\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
builder.emit_special(
|
||||
self._tool_response,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_segments(
|
||||
[("\n", False), (self._content(message), True), ("\n", False)],
|
||||
message_index,
|
||||
sampled=False,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._tool_response_end,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
if closes_group:
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def _render_generation_prompt(self, builder: _TokenBuilder) -> None:
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
-1,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"assistant\n",
|
||||
-1,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> list[int]:
|
||||
return self.render(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_qwen35(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
stop_ids={self._im_end, self._endoftext},
|
||||
think_id=self._think,
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
return [self._im_end, self._endoftext]
|
||||
|
||||
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, # noqa: ARG002
|
||||
) -> 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.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
{self._im_end, self._endoftext},
|
||||
synthesize_close=self._im_end,
|
||||
)
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
builder = _TokenBuilder(self._tokenizer)
|
||||
builder.prepend_prior(previous_ids)
|
||||
builder.emit_text("\n", -1, sampled=False, content=False)
|
||||
|
||||
for message_index, message in enumerate(new_messages):
|
||||
role = message.get("role", "")
|
||||
if role == "tool":
|
||||
opens_group = (
|
||||
message_index == 0
|
||||
or new_messages[message_index - 1].get("role") != "tool"
|
||||
)
|
||||
closes_group = (
|
||||
message_index == len(new_messages) - 1
|
||||
or new_messages[message_index + 1].get("role") != "tool"
|
||||
)
|
||||
self._render_tool(
|
||||
message,
|
||||
message_index,
|
||||
builder,
|
||||
opens_group=opens_group,
|
||||
closes_group=closes_group,
|
||||
)
|
||||
else:
|
||||
self._render_history_message(message, message_index, builder)
|
||||
|
||||
self._render_generation_prompt(builder)
|
||||
return RenderedTokens(
|
||||
token_ids=builder.token_ids,
|
||||
message_indices=builder.message_indices,
|
||||
sampled_mask=builder.sampled_mask,
|
||||
is_content=builder.is_content,
|
||||
message_roles=[message.get("role") or "" for message in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["PrimeQwen3Renderer"]
|
||||
+245
-101
@@ -18,10 +18,14 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen3RendererConfig
|
||||
from renderers.parsing import parse_qwen3
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
@@ -47,16 +51,13 @@ class Qwen3Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: Qwen3RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or Qwen3RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all" if not self.config.enable_thinking else "tool_cycle",
|
||||
)
|
||||
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
@@ -66,6 +67,7 @@ class Qwen3Renderer:
|
||||
self._tool_call_end = self._token_id("</tool_call>")
|
||||
self._tool_response = self._token_id("<tool_response>")
|
||||
self._tool_response_end = self._token_id("</tool_response>")
|
||||
self._think_end = self._token_id("</think>")
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
tid = self._tokenizer.convert_tokens_to_ids(token)
|
||||
@@ -79,19 +81,34 @@ class Qwen3Renderer:
|
||||
return []
|
||||
return self._tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
@staticmethod
|
||||
def _query_boundary_text(content) -> str:
|
||||
if isinstance(content, str):
|
||||
return content.strip()
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
parts.append(item)
|
||||
elif isinstance(item, dict) and isinstance(item.get("text"), str):
|
||||
parts.append(item["text"])
|
||||
return "".join(parts).strip()
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _is_user_query_message(msg: Message) -> bool:
|
||||
if msg.get("role") != "user":
|
||||
return False
|
||||
content = Qwen3Renderer._query_boundary_text(msg.get("content"))
|
||||
return not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _last_query_index(messages: list[Message]) -> int:
|
||||
for i in range(len(messages) - 1, -1, -1):
|
||||
msg = messages[i]
|
||||
if msg.get("role") != "user":
|
||||
continue
|
||||
content = msg.get("content")
|
||||
if not isinstance(content, str):
|
||||
continue
|
||||
if not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
):
|
||||
if Qwen3Renderer._is_user_query_message(messages[i]):
|
||||
return i
|
||||
return len(messages) - 1
|
||||
|
||||
@@ -108,43 +125,76 @@ class Qwen3Renderer:
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
|
||||
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) -> None:
|
||||
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated segments as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment.
|
||||
|
||||
Lets call sites express "this wrap + this body, joined the
|
||||
same way as the chat template, but attributed separately"
|
||||
without splitting the encode call (which could shift BPE
|
||||
merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── 1. System + tools ───────────────────────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
|
||||
if tools:
|
||||
sys_idx = 0 if first_is_system else -1
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False)
|
||||
tool_text = "system\n"
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
# Body = system content (if any). Everything else in this
|
||||
# block — role tag, tools header / footer, the JSON tool
|
||||
# specs — is scaffold. The tools dict is recoverable from
|
||||
# the ``tools`` argument; don't re-attribute its embedded
|
||||
# JSON as message body.
|
||||
segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if first_is_system:
|
||||
tool_text += (messages[0].get("content") or "") + "\n\n"
|
||||
tool_text += _TOOLS_HEADER
|
||||
sys_content = messages[0].get("content") or ""
|
||||
if sys_content:
|
||||
segments.append((sys_content, True))
|
||||
segments.append(("\n\n", False))
|
||||
segments.append((_TOOLS_HEADER, False))
|
||||
for tool in tools:
|
||||
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
|
||||
tool_text += _TOOLS_FOOTER
|
||||
emit_text(tool_text, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False)
|
||||
segments.append(("\n" + json.dumps(tool, ensure_ascii=False), False))
|
||||
segments.append((_TOOLS_FOOTER, False))
|
||||
emit_text_segments(segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
elif first_is_system:
|
||||
emit_special(self._im_start, 0, is_sampled=False)
|
||||
emit_text(
|
||||
"system\n" + (messages[0].get("content") or ""), 0, is_sampled=False
|
||||
)
|
||||
emit_special(self._im_end, 0, is_sampled=False)
|
||||
emit_text("\n", 0, is_sampled=False)
|
||||
emit_special(self._im_start, 0, is_sampled=False, is_content=False)
|
||||
sys_content = messages[0].get("content") or ""
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
sys_segments.append((sys_content, True))
|
||||
emit_text_segments(sys_segments, 0, is_sampled=False)
|
||||
emit_special(self._im_end, 0, is_sampled=False, is_content=False)
|
||||
emit_text("\n", 0, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Compute last_query_index ─────────────────────────────
|
||||
last_qi = self._last_query_index(messages)
|
||||
@@ -158,49 +208,61 @@ class Qwen3Renderer:
|
||||
if role == "system":
|
||||
if i == 0:
|
||||
continue
|
||||
emit_special(self._im_start, i, is_sampled=False)
|
||||
emit_text(role + "\n" + content, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False)
|
||||
emit_text("\n", i, is_sampled=False)
|
||||
emit_special(self._im_start, i, is_sampled=False, is_content=False)
|
||||
msg_segments: list[tuple[str, bool]] = [(role + "\n", False)]
|
||||
if content:
|
||||
msg_segments.append((content, True))
|
||||
emit_text_segments(msg_segments, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False, is_content=False)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._im_start, i, is_sampled=False)
|
||||
emit_text("user\n" + content, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False)
|
||||
emit_text("\n", i, is_sampled=False)
|
||||
emit_special(self._im_start, i, is_sampled=False, is_content=False)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False, is_content=False)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
last_qi,
|
||||
i == num_messages - 1,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
messages, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
# ── 4. Generation prompt ────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_start, -1, is_sampled=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False)
|
||||
if not self._enable_thinking:
|
||||
emit_text("<think>\n\n</think>\n\n", -1, is_sampled=False)
|
||||
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
|
||||
if not self.config.enable_thinking:
|
||||
emit_text(
|
||||
"<think>\n\n</think>\n\n", -1, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens, message_indices=indices, sampled_mask=sampled
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
@@ -228,6 +290,7 @@ class Qwen3Renderer:
|
||||
stop_ids={self._im_end, self._endoftext},
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
reasoning_end_id=self._think_end,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
@@ -248,6 +311,13 @@ class Qwen3Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
is_user_query=self._is_user_query_message,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
@@ -258,22 +328,56 @@ class Qwen3Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't track sampled_mask here. Local helpers accept the kwarg
|
||||
# for signature compatibility with ``_render_tool`` and ignore
|
||||
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
|
||||
# empty.
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
# Trailing ``\n`` after the turn-close token. ``render()`` emits this
|
||||
# as part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
|
||||
@@ -285,12 +389,18 @@ class Qwen3Renderer:
|
||||
content = msg.get("content") if isinstance(msg.get("content"), str) else ""
|
||||
if role == "user":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("user\n" + content, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "system":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("system\n" + content, i)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if content:
|
||||
sys_segments.append((content, True))
|
||||
emit_text_segments(sys_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "tool":
|
||||
@@ -300,16 +410,25 @@ class Qwen3Renderer:
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if not self._enable_thinking:
|
||||
if not self.config.enable_thinking:
|
||||
emit_text("<think>\n\n</think>\n\n", -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
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),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -319,9 +438,9 @@ class Qwen3Renderer:
|
||||
last_query_index,
|
||||
is_last,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
):
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
@@ -339,23 +458,26 @@ class Qwen3Renderer:
|
||||
# at inference the chat template emits these as the generation
|
||||
# prompt and the model never samples them. Marking the role tag
|
||||
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
|
||||
# what the model would actually have produced.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False)
|
||||
# what the model would actually have produced. ``is_content`` is
|
||||
# also False here — the role tag isn't part of any message's
|
||||
# body, on any role.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build the model-sampled portion (think block + content + tool
|
||||
# calls). Text segments stay contiguous within each is_sampled
|
||||
# span to preserve BPE merges (e.g., ".\n" is a single token in
|
||||
# Qwen3); the only split we introduce here is at ``\n`` after the
|
||||
# role tag, which the existing renderer already treats as a
|
||||
# token boundary (cf. ``_render_tool``).
|
||||
# token boundary (cf. ``_render_tool``). For assistant messages
|
||||
# the invariant ``is_content == sampled_mask`` holds — every
|
||||
# sampled token is body, every scaffold token isn't.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
|
||||
emit_in_template_window = msg_idx > last_query_index and (
|
||||
is_last or reasoning_content
|
||||
)
|
||||
emit_via_override = preserve_thinking and bool(reasoning_content)
|
||||
if emit_in_template_window or emit_via_override:
|
||||
if emit_in_template_window:
|
||||
body = (
|
||||
"<think>\n"
|
||||
+ reasoning_content.strip("\n")
|
||||
@@ -366,7 +488,7 @@ class Qwen3Renderer:
|
||||
body = content
|
||||
|
||||
if not tool_calls:
|
||||
emit_text(body, msg_idx, is_sampled=True)
|
||||
emit_text(body, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
for tc_idx, tc in enumerate(tool_calls):
|
||||
func = tc.get("function") or tc
|
||||
@@ -381,23 +503,29 @@ class Qwen3Renderer:
|
||||
# Text before this tool_call (includes separator)
|
||||
if tc_idx == 0:
|
||||
separator = "\n" if content else ""
|
||||
emit_text(body + separator, msg_idx, is_sampled=True)
|
||||
emit_text(
|
||||
body + separator, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
else:
|
||||
emit_text("\n", msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
|
||||
|
||||
# ``<|im_end|>`` is the model's stop signal — it samples this to
|
||||
# end its turn, so it is part of the sampled stream. The trailing
|
||||
# ``\n`` is template-appended between turns and never sampled.
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
# end its turn, so it is part of the sampled stream (and the
|
||||
# assistant's body). The trailing ``\n`` is template-appended
|
||||
# between turns and never sampled — scaffold for is_content too.
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -407,24 +535,40 @@ class Qwen3Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False.
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# field's body bytes get ``is_content=True``; everything else —
|
||||
# the ``<|im_start|>user`` wrap, the inter-section ``\n``s, the
|
||||
# ``<|tool_response>`` specials — is scaffold so the SFT mask
|
||||
# for tool body never trains the model to emit them.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
)
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False)
|
||||
emit_text("user", msg_idx, is_sampled=False)
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("user", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
emit_special(self._tool_response, msg_idx, is_sampled=False)
|
||||
emit_text("\n" + content + "\n", msg_idx, is_sampled=False)
|
||||
emit_special(self._tool_response_end, msg_idx, is_sampled=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._tool_response, msg_idx, is_sampled=False, is_content=False)
|
||||
# ``\n`` + content + ``\n`` — body is the middle segment only.
|
||||
# Single BPE pass over the joined text preserves boundary
|
||||
# merges (Qwen3 keeps ``\n`` as its own token, so this is
|
||||
# mostly a no-op, but we route through segments anyway so the
|
||||
# attribution doesn't depend on tokenizer-specific behaviour).
|
||||
emit_text_segments(
|
||||
[("\n", False), (content, True), ("\n", False)],
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_response_end, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
if not next_is_tool:
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+411
-182
@@ -26,10 +26,14 @@ from renderers.base import (
|
||||
PlaceholderRange,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.parsing import parse_qwen35
|
||||
from renderers.qwen3_vl import (
|
||||
_image_hash,
|
||||
@@ -64,62 +68,79 @@ _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:
|
||||
"""Deterministic message → token renderer for Qwen3.5 models."""
|
||||
|
||||
_config_cls: type = Qwen35RendererConfig
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Qwen35RendererConfig | None = None,
|
||||
*,
|
||||
processor: Any = None,
|
||||
enable_thinking: bool | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
image_cache_max: int = 256,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
if enable_thinking is None:
|
||||
enable_thinking = _detect_enable_thinking_default(tokenizer)
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
cfg = config or type(self)._config_cls()
|
||||
# ``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": _default_enable_thinking(tokenizer)}
|
||||
)
|
||||
self.config = cfg
|
||||
if getattr(cfg, "preserve_thinking", False):
|
||||
implied_thinking_retention = "all"
|
||||
elif not cfg.enable_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
else:
|
||||
implied_thinking_retention = "tool_cycle"
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
cfg,
|
||||
implied_thinking_retention,
|
||||
)
|
||||
|
||||
# Look up special token IDs from the tokenizer (not hardcoded)
|
||||
@@ -141,7 +162,6 @@ class Qwen35Renderer:
|
||||
# rationale (FIFO-bounded; same image seen across rollouts /
|
||||
# bridge re-renders).
|
||||
self._image_cache: dict[str, tuple[Any, int]] = {}
|
||||
self._image_cache_max = image_cache_max
|
||||
|
||||
@property
|
||||
def mm_token_type_id_map(self) -> dict[int, int]:
|
||||
@@ -186,7 +206,7 @@ class Qwen35Renderer:
|
||||
grid_thw = out["image_grid_thw"][0]
|
||||
merge_size = proc.image_processor.merge_size
|
||||
num_image_tokens = int(grid_thw.prod()) // (merge_size * merge_size)
|
||||
if len(self._image_cache) >= self._image_cache_max:
|
||||
if len(self._image_cache) >= self.config.image_cache_max:
|
||||
self._image_cache.pop(next(iter(self._image_cache)))
|
||||
self._image_cache[h] = (out, num_image_tokens)
|
||||
return pil, out, num_image_tokens, h
|
||||
@@ -251,6 +271,16 @@ class Qwen35Renderer:
|
||||
# last_query_index computation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _is_user_query_message(msg: Message) -> bool:
|
||||
if msg.get("role") != "user":
|
||||
return False
|
||||
content = Qwen35Renderer._render_content(msg.get("content")).strip()
|
||||
return not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _last_query_index(messages: list[Message]) -> int:
|
||||
"""Find the index of the last 'real' user query (not a tool_response wrapper).
|
||||
@@ -263,14 +293,7 @@ class Qwen35Renderer:
|
||||
assistant-only inputs (e.g. the bridge's dummy-assistant render).
|
||||
"""
|
||||
for i in range(len(messages) - 1, -1, -1):
|
||||
msg = messages[i]
|
||||
if msg.get("role") != "user":
|
||||
continue
|
||||
content = Qwen35Renderer._render_content(msg.get("content")).strip()
|
||||
if not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
):
|
||||
if Qwen35Renderer._is_user_query_message(messages[i]):
|
||||
return i
|
||||
return len(messages)
|
||||
|
||||
@@ -291,33 +314,88 @@ class Qwen35Renderer:
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
mm_hashes: dict[str, list[str]] = {}
|
||||
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
mm_items: dict[str, list[dict[str, Any]]] = {}
|
||||
# 1-indexed counters for ``add_vision_id`` (mirrors the Jinja's
|
||||
# ``image_count`` / ``video_count`` namespaces). Increment only
|
||||
# in the main message loop — the template renders the system
|
||||
# message with ``do_vision_count=False`` and would raise on
|
||||
# vision in system content anyway, so the renderer's
|
||||
# ``emit_image`` is only reached from user / tool emission paths.
|
||||
vision_counts = {"image": 0, "video": 0}
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
|
||||
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) -> None:
|
||||
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated segments as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment.
|
||||
|
||||
Lets call sites express "this wrap + this body, joined the
|
||||
same way as the chat template, but attributed separately"
|
||||
without splitting the encode call (which could shift BPE
|
||||
merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_image(part: dict[str, Any], msg_idx: int) -> None:
|
||||
# Image placeholders only appear in user / tool messages; the
|
||||
# model never samples them. Pin is_sampled=False here so
|
||||
# callers don't need to thread the flag through.
|
||||
# callers don't need to thread the flag through. The
|
||||
# ``<|image_pad|>`` placeholders represent caller-provided
|
||||
# image data, so they ARE body content (is_content=True);
|
||||
# the surrounding ``<|vision_start|>`` / ``<|vision_end|>``
|
||||
# specials are template scaffold.
|
||||
_, out, n, h = self._process_image(part)
|
||||
emit_special(self._vision_start, msg_idx, is_sampled=False)
|
||||
vision_counts["image"] += 1
|
||||
if self.config.add_vision_id:
|
||||
emit_text(
|
||||
f"Picture {vision_counts['image']}: ",
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
emit_special(
|
||||
self._vision_start, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
offset = len(tokens)
|
||||
for _ in range(n):
|
||||
emit_special(self._image_pad, msg_idx, is_sampled=False)
|
||||
emit_special(self._vision_end, msg_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._image_pad, msg_idx, is_sampled=False, is_content=True
|
||||
)
|
||||
emit_special(self._vision_end, msg_idx, is_sampled=False, is_content=False)
|
||||
mm_hashes.setdefault("image", []).append(h)
|
||||
mm_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=n)
|
||||
@@ -337,20 +415,28 @@ class Qwen35Renderer:
|
||||
``<|im_end|>``), matching how Jinja's ``render_content`` macro
|
||||
concatenates strings before tokenization. This preserves BPE
|
||||
byte-parity against ``apply_chat_template``.
|
||||
|
||||
Within each flush the ``"user\\n"`` wrap is scaffold and the
|
||||
text parts are body. ``emit_text_segments`` carries that
|
||||
attribution through the BPE pass.
|
||||
"""
|
||||
# Every token in a user message is conversation history that
|
||||
# the model never samples at inference.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False)
|
||||
buf: list[str] = ["user\n"]
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
# First flush includes the ``"user\n"`` wrap as a scaffold
|
||||
# segment; subsequent flushes are pure body (after a media
|
||||
# break).
|
||||
buf_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
|
||||
def flush_buf() -> None:
|
||||
if buf:
|
||||
emit_text("".join(buf), msg_idx, is_sampled=False)
|
||||
buf.clear()
|
||||
if buf_segments:
|
||||
emit_text_segments(buf_segments, msg_idx, is_sampled=False)
|
||||
buf_segments.clear()
|
||||
|
||||
for item in content_list:
|
||||
if isinstance(item, str):
|
||||
buf.append(item)
|
||||
if item:
|
||||
buf_segments.append((item, True))
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
flush_buf()
|
||||
@@ -360,14 +446,15 @@ class Qwen35Renderer:
|
||||
"Video parts are not yet supported by Qwen35Renderer."
|
||||
)
|
||||
elif "text" in item:
|
||||
buf.append(item["text"])
|
||||
if item["text"]:
|
||||
buf_segments.append((item["text"], True))
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
flush_buf()
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 1. System message + optional tools ──────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
@@ -376,31 +463,37 @@ class Qwen35Renderer:
|
||||
# System message index for attribution
|
||||
sys_idx = 0 if first_is_system else -1
|
||||
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False)
|
||||
emit_text("system\n", sys_idx, is_sampled=False)
|
||||
|
||||
# Tools header + JSON definitions
|
||||
tool_text = _TOOLS_HEADER
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
# Body = system content (if any). Everything else in this
|
||||
# block — role tag, tools header / footer / instructions, the
|
||||
# JSON tool specs — is scaffold. The tools dict is
|
||||
# recoverable from the ``tools`` argument; don't re-attribute
|
||||
# its embedded JSON as message body.
|
||||
segments: list[tuple[str, bool]] = [
|
||||
("system\n", False),
|
||||
(_TOOLS_HEADER, False),
|
||||
]
|
||||
for tool in tools:
|
||||
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
|
||||
tool_text += _TOOLS_FOOTER
|
||||
tool_text += _TOOLS_INSTRUCTIONS
|
||||
|
||||
# Append user's system content if present
|
||||
segments.append(("\n" + json.dumps(tool, ensure_ascii=False), False))
|
||||
segments.append((_TOOLS_FOOTER, False))
|
||||
segments.append((_TOOLS_INSTRUCTIONS, False))
|
||||
if first_is_system:
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
if sys_content:
|
||||
tool_text += "\n\n" + sys_content
|
||||
|
||||
emit_text(tool_text, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False)
|
||||
segments.append(("\n\n", False))
|
||||
segments.append((sys_content, True))
|
||||
emit_text_segments(segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
elif first_is_system:
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
emit_special(self._im_start, 0, is_sampled=False)
|
||||
emit_text("system\n" + sys_content, 0, is_sampled=False)
|
||||
emit_special(self._im_end, 0, is_sampled=False)
|
||||
emit_text("\n", 0, is_sampled=False)
|
||||
emit_special(self._im_start, 0, is_sampled=False, is_content=False)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
sys_segments.append((sys_content, True))
|
||||
emit_text_segments(sys_segments, 0, is_sampled=False)
|
||||
emit_special(self._im_end, 0, is_sampled=False, is_content=False)
|
||||
emit_text("\n", 0, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Compute last_query_index ─────────────────────────────
|
||||
last_qi = self._last_query_index(messages)
|
||||
@@ -420,27 +513,24 @@ class Qwen35Renderer:
|
||||
if self._content_has_media(raw_content):
|
||||
emit_user_with_media(raw_content, i)
|
||||
else:
|
||||
emit_special(self._im_start, i, is_sampled=False)
|
||||
emit_text("user\n" + content, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False)
|
||||
emit_text("\n", i, is_sampled=False)
|
||||
emit_special(self._im_start, i, is_sampled=False, is_content=False)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False, is_content=False)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
last_qi,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_ids=emit_ids,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
@@ -450,6 +540,7 @@ class Qwen35Renderer:
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_image=emit_image,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
else:
|
||||
@@ -457,16 +548,16 @@ class Qwen35Renderer:
|
||||
|
||||
# ── 4. Generation prompt ────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_start, -1, is_sampled=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False)
|
||||
emit_text("\n", -1, is_sampled=False)
|
||||
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._think, -1, is_sampled=False)
|
||||
emit_text("\n\n", -1, is_sampled=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False)
|
||||
emit_text("\n\n", -1, is_sampled=False)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n\n", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
mm_data: MultiModalData | None = None
|
||||
if mm_hashes or mm_placeholders or mm_items:
|
||||
@@ -480,6 +571,9 @@ class Qwen35Renderer:
|
||||
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),
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -532,6 +626,13 @@ class Qwen35Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
is_user_query=self._is_user_query_message,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
@@ -541,36 +642,102 @@ class Qwen35Renderer:
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
# ``add_vision_id`` numbers placeholders across the whole
|
||||
# conversation. The bridge can only seed that counter from
|
||||
# ``previous_multi_modal_data`` (raw prior token ids don't carry
|
||||
# the image/video count back), so if the caller asks for
|
||||
# ``add_vision_id=True`` while omitting prior mm-data on a
|
||||
# conversation that already contains images, the bridged
|
||||
# output would silently emit ``Picture 1:`` again. Refuse the
|
||||
# bridge in that case — the caller falls back to a full
|
||||
# re-render, which has the full message list and counts from
|
||||
# scratch correctly.
|
||||
if (
|
||||
self.config.add_vision_id
|
||||
and previous_multi_modal_data is None
|
||||
and self._vision_start in previous_ids
|
||||
):
|
||||
return None
|
||||
|
||||
# Seed combined-token list with prior turn so placeholder offsets
|
||||
# are absolute in the bridged sequence (matching ``render()``).
|
||||
# Parallel ``indices``/``sampled`` are seeded with ``-1``/``False``
|
||||
# for the prior portion — the bridge has no attribution info for
|
||||
# ``previous_ids``. Bridge-added tokens get proper ``msg_idx``
|
||||
# (relative to ``new_messages``) and uniformly ``False``
|
||||
# ``sampled``: nothing the bridge emits was model-sampled.
|
||||
# ``is_content`` follows the same rules as in :meth:`render` so
|
||||
# consumers can walk the trajectory and read each step's own
|
||||
# body mask; the prior portion is uniformly False since we have
|
||||
# no attribution info for it.
|
||||
tokens: list[int] = list(previous_ids)
|
||||
indices: list[int] = [-1] * len(previous_ids)
|
||||
sampled: list[bool] = [False] * len(previous_ids)
|
||||
content_mask: list[bool] = [False] * len(previous_ids)
|
||||
new_hashes: dict[str, list[str]] = {}
|
||||
new_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
new_items: dict[str, list[dict[str, Any]]] = {}
|
||||
# Seed the ``add_vision_id`` counters from prior-turn images / videos
|
||||
# so the bridged turn's first placeholder gets ``Picture {prev+1}``.
|
||||
# Bridges can't recover the count from raw token ids, so callers
|
||||
# must thread ``previous_multi_modal_data`` through to keep
|
||||
# ``add_vision_id`` parity across turns.
|
||||
prev_image_count = 0
|
||||
prev_video_count = 0
|
||||
if previous_multi_modal_data is not None:
|
||||
prev_image_count = len(previous_multi_modal_data.mm_items.get("image", []))
|
||||
prev_video_count = len(previous_multi_modal_data.mm_items.get("video", []))
|
||||
vision_counts = {"image": prev_image_count, "video": prev_video_count}
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't track sampled_mask here. Local helpers accept the kwarg
|
||||
# for signature compatibility with ``_render_tool`` and ignore
|
||||
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
|
||||
# empty.
|
||||
def emit_special(
|
||||
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> 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 = -1, *, is_sampled: bool = False
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
tokens.extend(self._encode(text))
|
||||
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_image(part: dict[str, Any], _msg_idx: int = -1) -> None:
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> 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_image(part: dict[str, Any], msg_idx: int = -1) -> None:
|
||||
_, out, n, h = self._process_image(part)
|
||||
emit_special(self._vision_start)
|
||||
vision_counts["image"] += 1
|
||||
if self.config.add_vision_id:
|
||||
emit_text(f"Picture {vision_counts['image']}: ", msg_idx)
|
||||
emit_special(self._vision_start, msg_idx)
|
||||
offset = len(tokens)
|
||||
for _ in range(n):
|
||||
emit_special(self._image_pad)
|
||||
emit_special(self._vision_end)
|
||||
emit_special(self._image_pad, msg_idx, is_content=True)
|
||||
emit_special(self._vision_end, msg_idx)
|
||||
new_hashes.setdefault("image", []).append(h)
|
||||
new_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=n)
|
||||
@@ -582,35 +749,37 @@ class Qwen35Renderer:
|
||||
}
|
||||
)
|
||||
|
||||
def emit_user_with_media(content_list: list[Any]) -> None:
|
||||
emit_special(self._im_start)
|
||||
buf: list[str] = ["user\n"]
|
||||
def emit_user_with_media(content_list: list[Any], msg_idx: int) -> None:
|
||||
emit_special(self._im_start, msg_idx)
|
||||
buf_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
|
||||
def flush_buf() -> None:
|
||||
if buf:
|
||||
emit_text("".join(buf))
|
||||
buf.clear()
|
||||
if buf_segments:
|
||||
emit_text_segments(buf_segments, msg_idx)
|
||||
buf_segments.clear()
|
||||
|
||||
for item in content_list:
|
||||
if isinstance(item, str):
|
||||
buf.append(item)
|
||||
if item:
|
||||
buf_segments.append((item, True))
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
flush_buf()
|
||||
emit_image(item)
|
||||
emit_image(item, msg_idx)
|
||||
elif _is_video_part(item):
|
||||
raise NotImplementedError(
|
||||
"Video parts are not yet supported by Qwen35Renderer."
|
||||
)
|
||||
elif "text" in item:
|
||||
buf.append(item["text"])
|
||||
if item["text"]:
|
||||
buf_segments.append((item["text"], True))
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
flush_buf()
|
||||
emit_special(self._im_end)
|
||||
emit_text("\n")
|
||||
emit_special(self._im_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
|
||||
# Trailing ``\n`` after ``<|im_end|>`` — ``render()`` emits it as
|
||||
# part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
|
||||
@@ -623,15 +792,21 @@ class Qwen35Renderer:
|
||||
content = self._render_content(raw_content).strip()
|
||||
if role == "user":
|
||||
if self._content_has_media(raw_content):
|
||||
emit_user_with_media(raw_content)
|
||||
emit_user_with_media(raw_content, i)
|
||||
else:
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("user\n" + content, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "system":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("system\n" + content, i)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if content:
|
||||
sys_segments.append((content, True))
|
||||
emit_text_segments(sys_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "tool":
|
||||
@@ -641,6 +816,7 @@ class Qwen35Renderer:
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_image=emit_image,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
@@ -648,7 +824,7 @@ class Qwen35Renderer:
|
||||
# Generation prompt — matches the gen-prompt branch of ``render()``.
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
else:
|
||||
@@ -658,18 +834,20 @@ class Qwen35Renderer:
|
||||
emit_text("\n\n", -1)
|
||||
|
||||
# Merge prev mm_data (images from earlier turns) with the new turn's.
|
||||
# Copy the per-modality lists (not just the outer dict) so appending
|
||||
# below never mutates the caller's previous_multi_modal_data.
|
||||
merged_hashes: dict[str, list[str]] = (
|
||||
dict(previous_multi_modal_data.mm_hashes)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_placeholders: dict[str, list[PlaceholderRange]] = (
|
||||
dict(previous_multi_modal_data.mm_placeholders)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_items: dict[str, list[dict[str, Any]]] = (
|
||||
dict(previous_multi_modal_data.mm_items)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
@@ -680,8 +858,17 @@ class Qwen35Renderer:
|
||||
for modality, vals in new_items.items():
|
||||
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)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
)
|
||||
|
||||
mm_data = MultiModalData(
|
||||
mm_hashes=merged_hashes,
|
||||
@@ -690,7 +877,11 @@ class Qwen35Renderer:
|
||||
)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=[-1] * len(tokens),
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
message_tool_names=bridge_tool_names,
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -728,10 +919,10 @@ class Qwen35Renderer:
|
||||
content: str,
|
||||
last_query_index: int,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_ids,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Extract reasoning_content
|
||||
reasoning_content = ""
|
||||
@@ -754,26 +945,36 @@ class Qwen35Renderer:
|
||||
# at inference the chat template emits these as the generation
|
||||
# prompt and the model never samples them. Marking the role tag
|
||||
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
|
||||
# what the model would actually have produced. The split between
|
||||
# ``assistant`` and ``\n`` is a safe BPE boundary in the Qwen
|
||||
# tokenizer (``\n`` after the role is its own token).
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False)
|
||||
# what the model would actually have produced. ``is_content`` is
|
||||
# also False here — the role tag isn't part of any message's
|
||||
# body, on any role.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build the model-sampled portion (think block + content + tool
|
||||
# calls). Text segments stay contiguous within each is_sampled
|
||||
# span to preserve BPE merges.
|
||||
emit_thinking = self._should_render_thinking(msg_idx, last_query_index) or (
|
||||
preserve_thinking and bool(reasoning_content)
|
||||
)
|
||||
# span to preserve BPE merges. For assistant messages the
|
||||
# invariant ``is_content == sampled_mask`` holds — every sampled
|
||||
# token is body, every scaffold token isn't. The XML-style tool
|
||||
# call tags (``<function=...>``, ``<parameter=...>``, etc.) are
|
||||
# part of the model's emitted output too — keep them
|
||||
# ``is_content=True`` per the assistant rule.
|
||||
emit_thinking = self._should_render_thinking(
|
||||
msg_idx, last_query_index
|
||||
) or getattr(self.config, "preserve_thinking", False)
|
||||
if emit_thinking:
|
||||
# Include thinking block
|
||||
emit_special(self._think, msg_idx, is_sampled=True)
|
||||
emit_text("\n" + reasoning_content + "\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n\n" + content, msg_idx, is_sampled=True)
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n" + reasoning_content + "\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n\n" + content, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_text(content, msg_idx, is_sampled=True)
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool calls
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
@@ -786,13 +987,18 @@ class Qwen35Renderer:
|
||||
# Separator before <tool_call>
|
||||
if tc_idx == 0:
|
||||
if content.strip():
|
||||
emit_text("\n\n", msg_idx, is_sampled=True)
|
||||
emit_text("\n\n", msg_idx, is_sampled=True, is_content=True)
|
||||
# else: no separator
|
||||
else:
|
||||
emit_text("\n", msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True)
|
||||
emit_text("\n<function=" + name + ">\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n<function=" + name + ">\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
# Render arguments
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
@@ -813,16 +1019,20 @@ class Qwen35Renderer:
|
||||
+ "\n</parameter>\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
emit_text("</function>\n", msg_idx, is_sampled=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
|
||||
emit_text("</function>\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
# ``<|im_end|>`` is the model's stop signal — it samples this to
|
||||
# end its turn, so it is part of the sampled stream. The trailing
|
||||
# ``\n`` is template-appended between turns and never sampled.
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
# end its turn, so it is part of the sampled stream (and the
|
||||
# assistant's body). The trailing ``\n`` is template-appended
|
||||
# between turns and never sampled — scaffold for is_content too.
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Tool message rendering
|
||||
@@ -836,6 +1046,7 @@ class Qwen35Renderer:
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_image,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Consecutive tool messages share a single <|im_start|>user ... <|im_end|>
|
||||
# envelope. Whether to open and close the envelope depends only on the
|
||||
@@ -843,9 +1054,11 @@ class Qwen35Renderer:
|
||||
# tool message — keep this predicate text/media-agnostic.
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. The bridge's
|
||||
# local emit_special / emit_text accept the is_sampled kwarg for
|
||||
# signature compatibility but ignore it.
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# field's body bytes get ``is_content=True``; everything else —
|
||||
# the ``<|im_start|>user`` wrap, the inter-section ``\n``s, the
|
||||
# ``<|tool_response>`` specials — is scaffold so the SFT mask
|
||||
# for tool body never trains the model to emit them.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
@@ -853,11 +1066,11 @@ class Qwen35Renderer:
|
||||
raw_content = messages[msg_idx].get("content")
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False)
|
||||
emit_text("user", msg_idx, is_sampled=False)
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("user", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
emit_special(self._tool_response, msg_idx, is_sampled=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._tool_response, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if self._content_has_media(raw_content):
|
||||
# Mirror the chat template's ``render_content`` macro for list
|
||||
@@ -867,16 +1080,22 @@ class Qwen35Renderer:
|
||||
# ``_content_has_media`` returns False unless content is a list,
|
||||
# but the type checker can't follow that through the call.
|
||||
assert isinstance(raw_content, list)
|
||||
buf: list[str] = ["\n"]
|
||||
# First flush: leading ``"\n"`` is scaffold (separates the
|
||||
# ``<|tool_response>`` special from the body); subsequent
|
||||
# text items in this run are body. After a media break, the
|
||||
# buffer resets to pure body until the next media break or
|
||||
# end-of-content.
|
||||
buf_segments: list[tuple[str, bool]] = [("\n", False)]
|
||||
|
||||
def flush_buf() -> None:
|
||||
if buf:
|
||||
emit_text("".join(buf), msg_idx, is_sampled=False)
|
||||
buf.clear()
|
||||
if buf_segments:
|
||||
emit_text_segments(buf_segments, msg_idx, is_sampled=False)
|
||||
buf_segments.clear()
|
||||
|
||||
for item in raw_content:
|
||||
if isinstance(item, str):
|
||||
buf.append(item)
|
||||
if item:
|
||||
buf_segments.append((item, True))
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
flush_buf()
|
||||
@@ -886,19 +1105,29 @@ class Qwen35Renderer:
|
||||
"Video parts are not yet supported by Qwen35Renderer."
|
||||
)
|
||||
elif "text" in item:
|
||||
buf.append(item["text"])
|
||||
if item["text"]:
|
||||
buf_segments.append((item["text"], True))
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
flush_buf()
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
else:
|
||||
content = self._render_content(raw_content).strip()
|
||||
emit_text("\n" + content + "\n", msg_idx, is_sampled=False)
|
||||
# ``\n`` + content + ``\n`` — body is the middle segment only.
|
||||
# Single BPE pass over the joined text preserves boundary
|
||||
# merges.
|
||||
emit_text_segments(
|
||||
[("\n", False), (content, True), ("\n", False)],
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
)
|
||||
|
||||
emit_special(self._tool_response_end, msg_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._tool_response_end, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
if not next_is_tool:
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+6
-6
@@ -7,12 +7,9 @@ Delta vs Qwen3.5 (template line 122):
|
||||
``None`` as ``null`` (not ``None``), fixing the single-turn extension-break
|
||||
mode where a boolean parameter's case drifted across a re-render.
|
||||
|
||||
The template's other delta vs Qwen3.5 (a ``preserve_thinking`` toggle that
|
||||
flips historical ``<think>`` retention on or off globally) is no longer
|
||||
exposed as a constructor kwarg — its default-False behaviour matches
|
||||
Qwen3.5 and is now baked in. Callers who want the toggled-on behaviour
|
||||
pass ``preserve_all_thinking=True`` to ``create_renderer``, the
|
||||
renderer-agnostic spelling of the same intent.
|
||||
Historical-thinking retention follows Qwen3.5's default unless
|
||||
``Qwen36RendererConfig.preserve_thinking`` is set, matching the upstream
|
||||
Qwen3.6 Jinja toggle.
|
||||
|
||||
Everything else — tool system prompt, tool-call XML structure, thinking
|
||||
markers, bridge logic, parser — is identical to Qwen3.5.
|
||||
@@ -23,12 +20,15 @@ from __future__ import annotations
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from renderers.configs import Qwen36RendererConfig
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
|
||||
|
||||
class Qwen36Renderer(Qwen35Renderer):
|
||||
"""Deterministic message → token renderer for Qwen3.6 models."""
|
||||
|
||||
_config_cls = Qwen36RendererConfig
|
||||
|
||||
@staticmethod
|
||||
def _render_arg_value(arg_value: Any) -> str:
|
||||
if isinstance(arg_value, str):
|
||||
|
||||
+295
-121
@@ -42,9 +42,14 @@ from renderers.base import (
|
||||
PlaceholderRange,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen3VLRendererConfig
|
||||
from renderers.parsing import parse_qwen3
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
@@ -70,9 +75,14 @@ def _is_image_part(item: Any) -> bool:
|
||||
t = item.get("type")
|
||||
if t in ("image", "image_url"):
|
||||
return True
|
||||
# Permissive fallback: chat templates check ``'image' in content`` to
|
||||
# accept loosely-shaped image parts, so mirror that.
|
||||
return "image" in item or "image_url" in item
|
||||
if t is not None:
|
||||
return False
|
||||
# Untyped fallback for loosely-shaped image parts. Require a truthy
|
||||
# value: HF Arrow schema unification (Dataset.from_list over a list of
|
||||
# heterogeneous content dicts) fills missing keys with None, so any
|
||||
# text part round-tripped through a Dataset will have ``image_url: None``
|
||||
# as a key. Mere key presence isn't enough.
|
||||
return bool(item.get("image")) or bool(item.get("image_url"))
|
||||
|
||||
|
||||
def _is_video_part(item: Any) -> bool:
|
||||
@@ -81,7 +91,9 @@ def _is_video_part(item: Any) -> bool:
|
||||
t = item.get("type")
|
||||
if t in ("video", "video_url"):
|
||||
return True
|
||||
return "video" in item or "video_url" in item
|
||||
if t is not None:
|
||||
return False
|
||||
return bool(item.get("video")) or bool(item.get("video_url"))
|
||||
|
||||
|
||||
def _load_pil_image(item: dict[str, Any]):
|
||||
@@ -170,14 +182,31 @@ class _Emitter:
|
||||
value than the current buffer triggers a flush first — split points
|
||||
are always at the ``is_sampled`` boundary, which the caller is
|
||||
expected to place at a ``\\n`` boundary so BPE merges don't drift.
|
||||
|
||||
``is_content`` is the per-token body/scaffold attribution. Within a
|
||||
single flush adjacent text fragments may carry different
|
||||
``is_content`` values (e.g. ``"user\\n"`` scaffold + caller content
|
||||
body): the buffer stores fragments as a list of
|
||||
``(text, is_content)`` segments and flushes via
|
||||
:func:`attribute_text_segments`, which performs one BPE pass over
|
||||
the joined text and assigns per-token is_content from each token's
|
||||
source segment. When every segment in a flush shares the same
|
||||
is_content (the common case for sampled assistant body / pure
|
||||
scaffold) the fast path of a single ``encode()`` call is used and
|
||||
no offset-tokenizer lookup is required.
|
||||
"""
|
||||
|
||||
def __init__(self, encode_fn, msg_idx: int = -1):
|
||||
def __init__(self, encode_fn, tokenizer=None, msg_idx: int = -1):
|
||||
self._encode = encode_fn
|
||||
self._tokenizer = tokenizer
|
||||
self.token_ids: list[int] = []
|
||||
self.message_indices: list[int] = []
|
||||
self.sampled: list[bool] = []
|
||||
self._buf: str = ""
|
||||
self.is_content: list[bool] = []
|
||||
# Buffered text fragments as ``(text, is_content)`` tuples. All
|
||||
# fragments share a single ``_buf_sampled`` / ``_buf_idx``;
|
||||
# changing either of those triggers a flush.
|
||||
self._segments: list[tuple[str, bool]] = []
|
||||
self._buf_idx: int = msg_idx
|
||||
self._buf_sampled: bool = False
|
||||
self.msg_idx = msg_idx
|
||||
@@ -187,49 +216,78 @@ class _Emitter:
|
||||
# text doesn't get glued to the previous one's BPE context.
|
||||
# In practice messages are always separated by an <|im_end|>
|
||||
# special token, which already flushes — but be defensive.
|
||||
if self._buf:
|
||||
if self._segments:
|
||||
self._flush()
|
||||
self.msg_idx = msg_idx
|
||||
self._buf_idx = msg_idx
|
||||
|
||||
def text(self, text: str, *, is_sampled: bool) -> None:
|
||||
def text(self, text: str, *, is_sampled: bool, is_content: bool) -> None:
|
||||
if not text:
|
||||
return
|
||||
# Adjacent text under different msg_idx or is_sampled is rare in
|
||||
# this template — but flush at those boundaries so attribution
|
||||
# and the sampled signal stay accurate.
|
||||
if self._buf and (
|
||||
# and the sampled signal stay accurate. is_content boundaries do
|
||||
# NOT force a flush: they're carried through the joined BPE pass
|
||||
# via :func:`attribute_text_segments`, preserving merges across
|
||||
# the wrap/body boundary.
|
||||
if self._segments and (
|
||||
self._buf_idx != self.msg_idx or self._buf_sampled != is_sampled
|
||||
):
|
||||
self._flush()
|
||||
if not self._buf:
|
||||
if not self._segments:
|
||||
self._buf_idx = self.msg_idx
|
||||
self._buf_sampled = is_sampled
|
||||
self._buf += text
|
||||
self._segments.append((text, is_content))
|
||||
|
||||
def special(self, token_id: int, *, is_sampled: bool) -> None:
|
||||
if self._buf:
|
||||
def special(self, token_id: int, *, is_sampled: bool, is_content: bool) -> None:
|
||||
if self._segments:
|
||||
self._flush()
|
||||
self.token_ids.append(token_id)
|
||||
self.message_indices.append(self.msg_idx)
|
||||
self.sampled.append(is_sampled)
|
||||
self.is_content.append(is_content)
|
||||
|
||||
def cursor(self) -> int:
|
||||
"""Current token offset after flushing — used to anchor placeholder ranges."""
|
||||
if self._buf:
|
||||
if self._segments:
|
||||
self._flush()
|
||||
return len(self.token_ids)
|
||||
|
||||
def finalize(self) -> None:
|
||||
if self._buf:
|
||||
if self._segments:
|
||||
self._flush()
|
||||
|
||||
def _flush(self) -> None:
|
||||
ids = self._encode(self._buf)
|
||||
self.token_ids.extend(ids)
|
||||
self.message_indices.extend([self._buf_idx] * len(ids))
|
||||
self.sampled.extend([self._buf_sampled] * len(ids))
|
||||
self._buf = ""
|
||||
segments = self._segments
|
||||
self._segments = []
|
||||
if not segments:
|
||||
return
|
||||
# Fast path: every segment shares the same is_content — use the
|
||||
# plain ``encode()`` call so we don't pay for the offset
|
||||
# tokenizer. This is the common case (pure scaffold flushes, or
|
||||
# pure body flushes).
|
||||
first_ic = segments[0][1]
|
||||
all_same = all(ic == first_ic for _, ic in segments)
|
||||
if all_same:
|
||||
joined = "".join(text for text, _ in segments)
|
||||
ids = self._encode(joined)
|
||||
self.token_ids.extend(ids)
|
||||
self.message_indices.extend([self._buf_idx] * len(ids))
|
||||
self.sampled.extend([self._buf_sampled] * len(ids))
|
||||
self.is_content.extend([first_ic] * len(ids))
|
||||
return
|
||||
# Mixed body/scaffold flush — encode once and attribute back to
|
||||
# each segment via the fast tokenizer's offset_mapping. Requires
|
||||
# a tokenizer (not just the encode fn) to look up offsets.
|
||||
assert self._tokenizer is not None, (
|
||||
"_Emitter mixed-is_content flush requires a tokenizer; "
|
||||
"pass one to the constructor."
|
||||
)
|
||||
for tok_id, is_content in attribute_text_segments(self._tokenizer, segments):
|
||||
self.token_ids.append(tok_id)
|
||||
self.message_indices.append(self._buf_idx)
|
||||
self.sampled.append(self._buf_sampled)
|
||||
self.is_content.append(is_content)
|
||||
|
||||
|
||||
class Qwen3VLRenderer:
|
||||
@@ -237,34 +295,33 @@ class Qwen3VLRenderer:
|
||||
|
||||
Constructor args:
|
||||
tokenizer: HF tokenizer for the model.
|
||||
config: Typed renderer config (see
|
||||
:class:`renderers.Qwen3VLRendererConfig`). Defaults to a
|
||||
blank config with template defaults.
|
||||
processor: Optional ``Qwen3VLProcessor``. Required when rendering
|
||||
messages that contain image / video parts. If not supplied,
|
||||
the renderer lazy-loads it via ``AutoProcessor.from_pretrained``
|
||||
keyed off ``tokenizer.name_or_path`` the first time a
|
||||
multimodal part is seen.
|
||||
preserve_all_thinking / preserve_thinking_between_tool_calls:
|
||||
No-ops on Qwen3-VL — the chat template already drops past
|
||||
``<think>`` blocks unconditionally. Stored for Protocol parity.
|
||||
image_cache_max: Max entries in the per-instance image-processor
|
||||
cache (FIFO eviction). Default 256 covers typical RL pools
|
||||
(``rollouts_per_example`` × in-flight examples). Bump for runs
|
||||
with large image sets where the working set exceeds the cap.
|
||||
|
||||
Qwen3-VL has no historical reasoning channel in this renderer. The
|
||||
default bridge policy therefore resolves to ``"all"``; explicit
|
||||
``thinking_retention`` still controls whether the bridge is attempted.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Qwen3VLRendererConfig | None = None,
|
||||
*,
|
||||
processor: Any = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
image_cache_max: int = 256,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
self.config = config or Qwen3VLRendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
@@ -274,6 +331,7 @@ class Qwen3VLRenderer:
|
||||
self._tool_call_end = self._token_id("</tool_call>")
|
||||
self._tool_response = self._token_id("<tool_response>")
|
||||
self._tool_response_end = self._token_id("</tool_response>")
|
||||
self._think_end = self._token_id("</think>")
|
||||
self._vision_start = self._token_id("<|vision_start|>")
|
||||
self._vision_end = self._token_id("<|vision_end|>")
|
||||
self._image_pad = self._token_id("<|image_pad|>")
|
||||
@@ -288,7 +346,6 @@ class Qwen3VLRenderer:
|
||||
# tuples of ``(processor_out, num_image_tokens)`` — bounded to
|
||||
# avoid unbounded growth on long-lived pools.
|
||||
self._image_cache: dict[str, tuple[Any, int]] = {}
|
||||
self._image_cache_max = image_cache_max
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
tid = self._tokenizer.convert_tokens_to_ids(token)
|
||||
@@ -359,6 +416,16 @@ class Qwen3VLRenderer:
|
||||
return "".join(parts)
|
||||
raise TypeError(f"Unexpected content type: {type(content)}")
|
||||
|
||||
@staticmethod
|
||||
def _is_user_query_message(msg: Message) -> bool:
|
||||
if msg.get("role") != "user":
|
||||
return False
|
||||
content = Qwen3VLRenderer._render_text_content(msg.get("content")).strip()
|
||||
return not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
)
|
||||
|
||||
def _process_image(self, part: dict[str, Any]):
|
||||
"""Resolve, process, and characterize a single image part.
|
||||
|
||||
@@ -377,7 +444,7 @@ class Qwen3VLRenderer:
|
||||
grid_thw = out["image_grid_thw"][0]
|
||||
merge_size = proc.image_processor.merge_size
|
||||
num_image_tokens = int(grid_thw.prod()) // (merge_size * merge_size)
|
||||
if len(self._image_cache) >= self._image_cache_max:
|
||||
if len(self._image_cache) >= self.config.image_cache_max:
|
||||
# FIFO eviction — Python dicts preserve insertion order, so
|
||||
# ``next(iter(...))`` is the oldest key.
|
||||
self._image_cache.pop(next(iter(self._image_cache)))
|
||||
@@ -394,21 +461,38 @@ class Qwen3VLRenderer:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
em = _Emitter(self._encode)
|
||||
em = _Emitter(self._encode, tokenizer=self._tokenizer)
|
||||
mm_hashes: dict[str, list[str]] = {}
|
||||
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
mm_items: dict[str, list[dict[str, Any]]] = {}
|
||||
# ``add_vision_id`` mirrors the Jinja's ``image_count`` /
|
||||
# ``video_count`` namespaces. Counters are 1-indexed and run
|
||||
# across the entire conversation; they increment unconditionally
|
||||
# on each image / video (the Qwen3-VL template increments first,
|
||||
# then emits ``Picture N: `` only when ``add_vision_id`` is set).
|
||||
vision_counts = {"image": 0, "video": 0}
|
||||
|
||||
def emit_image(part: dict[str, Any]) -> None:
|
||||
# Image placeholders are prompt-side scaffolding the user
|
||||
# message attaches — the model never samples ``<|vision_start|>``
|
||||
# / ``<|image_pad|>`` / ``<|vision_end|>``.
|
||||
# / ``<|image_pad|>`` / ``<|vision_end|>``. The
|
||||
# ``<|image_pad|>`` placeholders represent caller-provided
|
||||
# image data, so they ARE body content (is_content=True);
|
||||
# the surrounding ``<|vision_start|>`` / ``<|vision_end|>``
|
||||
# markers are renderer-emitted scaffold.
|
||||
_, out, n, h = self._process_image(part)
|
||||
em.special(self._vision_start, is_sampled=False)
|
||||
vision_counts["image"] += 1
|
||||
if self.config.add_vision_id:
|
||||
em.text(
|
||||
f"Picture {vision_counts['image']}: ",
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
em.special(self._vision_start, is_sampled=False, is_content=False)
|
||||
offset = em.cursor()
|
||||
for _ in range(n):
|
||||
em.special(self._image_pad, is_sampled=False)
|
||||
em.special(self._vision_end, is_sampled=False)
|
||||
em.special(self._image_pad, is_sampled=False, is_content=True)
|
||||
em.special(self._vision_end, is_sampled=False, is_content=False)
|
||||
mm_hashes.setdefault("image", []).append(h)
|
||||
mm_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=n)
|
||||
@@ -425,16 +509,24 @@ class Qwen3VLRenderer:
|
||||
|
||||
User / tool content is conversation context the model never
|
||||
samples — every text fragment goes in as ``is_sampled=False``.
|
||||
Text from the caller IS the message body, so every text
|
||||
fragment is ``is_content=True``; the vision-marker specials
|
||||
around image_pad placeholders are scaffold (handled in
|
||||
:func:`emit_image`).
|
||||
"""
|
||||
if isinstance(content, str):
|
||||
em.text(content, is_sampled=False)
|
||||
em.text(content, is_sampled=False, is_content=True)
|
||||
return
|
||||
if not isinstance(content, list):
|
||||
em.text(self._render_text_content(content), is_sampled=False)
|
||||
em.text(
|
||||
self._render_text_content(content),
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
return
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
em.text(item, is_sampled=False)
|
||||
em.text(item, is_sampled=False, is_content=True)
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
emit_image(item)
|
||||
@@ -443,7 +535,7 @@ class Qwen3VLRenderer:
|
||||
"Video parts are not yet supported by Qwen3VLRenderer."
|
||||
)
|
||||
elif "text" in item:
|
||||
em.text(item["text"], is_sampled=False)
|
||||
em.text(item["text"], is_sampled=False, is_content=True)
|
||||
|
||||
# ── 1. System + tools ───────────────────────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
@@ -451,26 +543,37 @@ class Qwen3VLRenderer:
|
||||
if tools:
|
||||
sys_idx = 0 if first_is_system else -1
|
||||
em.set_msg_idx(sys_idx)
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
buf = "system\n"
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
# Body = system content (if any). Everything else in this
|
||||
# block — role tag, tools header / footer, JSON tool specs —
|
||||
# is scaffold. The tools dict is recoverable from the
|
||||
# ``tools`` argument; we don't re-attribute its embedded
|
||||
# JSON as message body.
|
||||
em.text("system\n", is_sampled=False, is_content=False)
|
||||
if first_is_system:
|
||||
buf += self._render_text_content(messages[0].get("content")) + "\n\n"
|
||||
buf += _TOOLS_HEADER
|
||||
sys_content = self._render_text_content(messages[0].get("content"))
|
||||
if sys_content:
|
||||
em.text(sys_content, is_sampled=False, is_content=True)
|
||||
em.text("\n\n", is_sampled=False, is_content=False)
|
||||
em.text(_TOOLS_HEADER, is_sampled=False, is_content=False)
|
||||
for tool in tools:
|
||||
buf += "\n" + json.dumps(tool, ensure_ascii=False)
|
||||
buf += _TOOLS_FOOTER
|
||||
em.text(buf, is_sampled=False)
|
||||
em.special(self._im_end, is_sampled=False)
|
||||
em.text("\n", is_sampled=False)
|
||||
em.text(
|
||||
"\n" + json.dumps(tool, ensure_ascii=False),
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
em.text(_TOOLS_FOOTER, is_sampled=False, is_content=False)
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
elif first_is_system:
|
||||
em.set_msg_idx(0)
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
em.text(
|
||||
"system\n" + self._render_text_content(messages[0].get("content")),
|
||||
is_sampled=False,
|
||||
)
|
||||
em.special(self._im_end, is_sampled=False)
|
||||
em.text("\n", is_sampled=False)
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("system\n", is_sampled=False, is_content=False)
|
||||
sys_content = self._render_text_content(messages[0].get("content"))
|
||||
if sys_content:
|
||||
em.text(sys_content, is_sampled=False, is_content=True)
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Iterate messages ─────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
@@ -482,11 +585,11 @@ class Qwen3VLRenderer:
|
||||
em.set_msg_idx(i)
|
||||
|
||||
if role == "user":
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
em.text("user\n", is_sampled=False)
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("user\n", is_sampled=False, is_content=False)
|
||||
render_media_content(msg.get("content"))
|
||||
em.special(self._im_end, is_sampled=False)
|
||||
em.text("\n", is_sampled=False)
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
self._render_assistant(msg, em)
|
||||
@@ -500,8 +603,8 @@ class Qwen3VLRenderer:
|
||||
# ── 3. Generation prompt ────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
em.set_msg_idx(-1)
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
em.text("assistant\n", is_sampled=False)
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("assistant\n", is_sampled=False, is_content=False)
|
||||
|
||||
em.finalize()
|
||||
|
||||
@@ -517,6 +620,9 @@ class Qwen3VLRenderer:
|
||||
token_ids=em.token_ids,
|
||||
message_indices=em.message_indices,
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -545,6 +651,7 @@ class Qwen3VLRenderer:
|
||||
stop_ids={self._im_end, self._endoftext},
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
reasoning_end_id=self._think_end,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
@@ -574,6 +681,12 @@ class Qwen3VLRenderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
is_user_query=self._is_user_query_message,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
@@ -584,30 +697,74 @@ class Qwen3VLRenderer:
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
# Bridge output is consumed as the next turn's prompt — the
|
||||
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
|
||||
# don't surface a sampled_mask here. The shared ``_render_tool``
|
||||
# helper still routes through ``em.special``/``em.text`` with
|
||||
# ``is_sampled`` kwargs, which the emitter accepts and tracks,
|
||||
# but the returned ``RenderedTokens`` leaves ``sampled_mask``
|
||||
# empty (the field defaults to ``[]``).
|
||||
em = _Emitter(self._encode)
|
||||
# ``add_vision_id`` numbers placeholders across the whole
|
||||
# conversation. The bridge can only seed that counter from
|
||||
# ``previous_multi_modal_data`` (raw prior token ids don't carry
|
||||
# the image/video count back), so if the caller asks for
|
||||
# ``add_vision_id=True`` while omitting prior mm-data on a
|
||||
# conversation that already contains images, the bridged
|
||||
# output would silently emit ``Picture 1:`` again. Refuse the
|
||||
# bridge in that case — the caller falls back to a full
|
||||
# re-render, which has the full message list and counts
|
||||
# correctly.
|
||||
if (
|
||||
self.config.add_vision_id
|
||||
and previous_multi_modal_data is None
|
||||
and self._vision_start in previous_ids
|
||||
):
|
||||
return None
|
||||
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
em = _Emitter(self._encode, tokenizer=self._tokenizer)
|
||||
# Seed the emitter with the prior turn's tokens so cursor() reports
|
||||
# absolute offsets in the combined sequence.
|
||||
# absolute offsets in the combined sequence. Per-token attribution
|
||||
# for the prior portion is unknown to the bridge (it only has
|
||||
# prev_prompt_ids + prev_completion_ids as raw lists), so seed
|
||||
# all side channels with the "no info" sentinel.
|
||||
em.token_ids = list(previous_ids)
|
||||
em.message_indices = [-1] * len(previous_ids)
|
||||
em.sampled = [False] * len(previous_ids)
|
||||
em.is_content = [False] * len(previous_ids)
|
||||
|
||||
new_hashes: dict[str, list[str]] = {}
|
||||
new_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
new_items: dict[str, list[dict[str, Any]]] = {}
|
||||
# Seed the vision counters from any prior-turn images / videos
|
||||
# the bridge was handed via ``previous_multi_modal_data``. The
|
||||
# ``add_vision_id`` template numbers placeholders across the
|
||||
# whole conversation, so a new turn's first image is
|
||||
# ``Picture {prev_total + 1}``. The bridge can't recover this
|
||||
# count from raw token ids, so callers must thread
|
||||
# ``previous_multi_modal_data`` through when they want
|
||||
# ``add_vision_id`` parity across turns.
|
||||
prev_image_count = 0
|
||||
prev_video_count = 0
|
||||
if previous_multi_modal_data is not None:
|
||||
prev_image_count = len(previous_multi_modal_data.mm_items.get("image", []))
|
||||
prev_video_count = len(previous_multi_modal_data.mm_items.get("video", []))
|
||||
vision_counts = {"image": prev_image_count, "video": prev_video_count}
|
||||
|
||||
def emit_image(part: dict[str, Any]) -> None:
|
||||
_, out, n, h = self._process_image(part)
|
||||
em.special(self._vision_start, is_sampled=False)
|
||||
vision_counts["image"] += 1
|
||||
if self.config.add_vision_id:
|
||||
em.text(
|
||||
f"Picture {vision_counts['image']}: ",
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
em.special(self._vision_start, is_sampled=False, is_content=False)
|
||||
offset = em.cursor()
|
||||
for _ in range(n):
|
||||
em.special(self._image_pad, is_sampled=False)
|
||||
em.special(self._vision_end, is_sampled=False)
|
||||
em.special(self._image_pad, is_sampled=False, is_content=True)
|
||||
em.special(self._vision_end, is_sampled=False, is_content=False)
|
||||
new_hashes.setdefault("image", []).append(h)
|
||||
new_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=n)
|
||||
@@ -621,14 +778,18 @@ class Qwen3VLRenderer:
|
||||
|
||||
def render_media_content(content: Any) -> None:
|
||||
if isinstance(content, str):
|
||||
em.text(content, is_sampled=False)
|
||||
em.text(content, is_sampled=False, is_content=True)
|
||||
return
|
||||
if not isinstance(content, list):
|
||||
em.text(self._render_text_content(content), is_sampled=False)
|
||||
em.text(
|
||||
self._render_text_content(content),
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
return
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
em.text(item, is_sampled=False)
|
||||
em.text(item, is_sampled=False, is_content=True)
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
emit_image(item)
|
||||
@@ -637,49 +798,51 @@ class Qwen3VLRenderer:
|
||||
"Video parts are not yet supported by Qwen3VLRenderer."
|
||||
)
|
||||
elif "text" in item:
|
||||
em.text(item["text"], is_sampled=False)
|
||||
em.text(item["text"], is_sampled=False, is_content=True)
|
||||
|
||||
em.set_msg_idx(-1)
|
||||
em.text("\n", is_sampled=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
em.set_msg_idx(i)
|
||||
if role == "user":
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
em.text("user\n", is_sampled=False)
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("user\n", is_sampled=False, is_content=False)
|
||||
render_media_content(msg.get("content"))
|
||||
em.special(self._im_end, is_sampled=False)
|
||||
em.text("\n", is_sampled=False)
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
elif role == "system":
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
em.text("system\n", is_sampled=False)
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("system\n", is_sampled=False, is_content=False)
|
||||
render_media_content(msg.get("content"))
|
||||
em.special(self._im_end, is_sampled=False)
|
||||
em.text("\n", is_sampled=False)
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
elif role == "tool":
|
||||
self._render_tool(new_messages, i, em, render_media_content)
|
||||
else:
|
||||
return None
|
||||
|
||||
em.set_msg_idx(-1)
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
em.text("assistant\n", is_sampled=False)
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("assistant\n", is_sampled=False, is_content=False)
|
||||
em.finalize()
|
||||
|
||||
# Merge prev mm_data with the new turn's items.
|
||||
# Merge prev mm_data with the new turn's items. Copy the per-modality
|
||||
# lists (not just the outer dict) so appending below never mutates the
|
||||
# caller's previous_multi_modal_data.
|
||||
merged_hashes = (
|
||||
dict(previous_multi_modal_data.mm_hashes)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_placeholders = (
|
||||
dict(previous_multi_modal_data.mm_placeholders)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_items = (
|
||||
dict(previous_multi_modal_data.mm_items)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
@@ -700,6 +863,11 @@ class Qwen3VLRenderer:
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=em.token_ids,
|
||||
message_indices=em.message_indices,
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -712,20 +880,22 @@ class Qwen3VLRenderer:
|
||||
# at inference the chat template emits these as the generation
|
||||
# prompt and the model never samples them. Splitting the text
|
||||
# at the ``\n`` after the role tag is safe: Qwen3 BPE treats
|
||||
# ``\n`` as a token boundary.
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
em.text("assistant\n", is_sampled=False)
|
||||
# ``\n`` as a token boundary. For the assistant role the
|
||||
# invariant ``is_content == sampled_mask`` holds — every sampled
|
||||
# token is body, every scaffold token isn't.
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("assistant\n", is_sampled=False, is_content=False)
|
||||
|
||||
# Body (content + tool calls) is the model-sampled portion.
|
||||
if not tool_calls:
|
||||
em.text(content, is_sampled=True)
|
||||
em.text(content, is_sampled=True, is_content=True)
|
||||
else:
|
||||
for tc_idx, tc in enumerate(tool_calls):
|
||||
if tc_idx == 0:
|
||||
separator = "\n" if original_content else ""
|
||||
em.text(content + separator, is_sampled=True)
|
||||
em.text(content + separator, is_sampled=True, is_content=True)
|
||||
else:
|
||||
em.text("\n", is_sampled=True)
|
||||
em.text("\n", is_sampled=True, is_content=True)
|
||||
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
@@ -736,18 +906,19 @@ class Qwen3VLRenderer:
|
||||
else json.dumps(arguments, ensure_ascii=False)
|
||||
)
|
||||
|
||||
em.special(self._tool_call, is_sampled=True)
|
||||
em.special(self._tool_call, is_sampled=True, is_content=True)
|
||||
em.text(
|
||||
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
em.special(self._tool_call_end, is_sampled=True)
|
||||
em.special(self._tool_call_end, is_sampled=True, is_content=True)
|
||||
|
||||
# ``<|im_end|>`` is the model's stop signal — it samples this to
|
||||
# end its turn. The trailing ``\n`` is template-appended between
|
||||
# turns and never sampled.
|
||||
em.special(self._im_end, is_sampled=True)
|
||||
em.text("\n", is_sampled=False)
|
||||
# end its turn (and counts as part of its body). The trailing
|
||||
# ``\n`` is template-appended between turns and never sampled.
|
||||
em.special(self._im_end, is_sampled=True, is_content=True)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -758,24 +929,27 @@ class Qwen3VLRenderer:
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. (render_media_content
|
||||
# also stamps is_sampled=False on its emissions.)
|
||||
# tokens, so every emission is is_sampled=False. The
|
||||
# ``content`` body bytes get ``is_content=True`` (via
|
||||
# ``render_media_content``); everything else — the
|
||||
# ``<|im_start|>user`` wrap, inter-section ``\n``s, and the
|
||||
# ``<|tool_response>`` specials — is scaffold.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
)
|
||||
|
||||
if not prev_is_tool:
|
||||
em.special(self._im_start, is_sampled=False)
|
||||
em.text("user", is_sampled=False)
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("user", is_sampled=False, is_content=False)
|
||||
|
||||
em.text("\n", is_sampled=False)
|
||||
em.special(self._tool_response, is_sampled=False)
|
||||
em.text("\n", is_sampled=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
em.special(self._tool_response, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
render_media_content(messages[msg_idx].get("content"))
|
||||
em.text("\n", is_sampled=False)
|
||||
em.special(self._tool_response_end, is_sampled=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
em.special(self._tool_response_end, is_sampled=False, is_content=False)
|
||||
|
||||
if not next_is_tool:
|
||||
em.special(self._im_end, is_sampled=False)
|
||||
em.text("\n", is_sampled=False)
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
+51
-2
@@ -7,9 +7,9 @@ The same barrage of tests runs against every pair.
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import config_from_name
|
||||
|
||||
# (HuggingFace model name, renderer name or "auto")
|
||||
#
|
||||
@@ -19,6 +19,7 @@ from renderers.base import load_tokenizer
|
||||
# own parametrization in the test file.
|
||||
RENDERER_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"),
|
||||
("PrimeIntellect/Qwen3-0.6B", "auto"),
|
||||
("Qwen/Qwen3.5-9B", "auto"),
|
||||
("Qwen/Qwen3.6-35B-A3B", "auto"),
|
||||
("Qwen/Qwen3-VL-4B-Instruct", "auto"),
|
||||
@@ -32,8 +33,29 @@ RENDERER_MODELS = [
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
|
||||
# Ultra resolves to the `nemotron-3-ultra` config variant via the model
|
||||
# name (auto → MODEL_RENDERER_MAP → nemotron-3-ultra).
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
# XS-2.1 resolves to `LagunaXS21Renderer` via the model name — its
|
||||
# chat template differs from XS.2's (see renderers/laguna_xs2.py).
|
||||
("poolside/Laguna-XS-2.1", "auto"),
|
||||
# DeepSeek-V3/R1 are intentionally NOT in this shared barrage: their
|
||||
# chat templates can't render the barrage's tool-call fixtures (the
|
||||
# templates require ``tool['type']`` and a string-serialized
|
||||
# ``arguments``, and V3 only renders tool_calls when content is None —
|
||||
# so ``apply_chat_template`` raises or drops the calls on the shared
|
||||
# shapes), and the is_content body-recovery checks hit a Metaspace
|
||||
# subset-decode artifact. The renderer is correct in all these cases;
|
||||
# there's just no byte-output to parity-check against. Split-specific
|
||||
# parity (V3 bare prompt vs R1 <think>+history-strip) is covered in
|
||||
# tests/test_deepseek_r1.py.
|
||||
# Llama-3 uses the canonical Meta ID for renderer auto-resolution, while
|
||||
# load_tokenizer fetches the tokenizer/chat_template from the unrestricted
|
||||
# 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"),
|
||||
]
|
||||
|
||||
@@ -44,7 +66,7 @@ def _load(model_name: str, renderer_name: str):
|
||||
key = f"{model_name}:{renderer_name}"
|
||||
if key not in _cache:
|
||||
tokenizer = load_tokenizer(model_name)
|
||||
renderer = create_renderer(tokenizer, renderer=renderer_name)
|
||||
renderer = create_renderer(tokenizer, config_from_name(renderer_name))
|
||||
_cache[key] = (tokenizer, renderer)
|
||||
return _cache[key]
|
||||
|
||||
@@ -102,3 +124,30 @@ def _skip_gpt_oss_for_hf_parity_tests(request):
|
||||
f"{model_name}: renderer matches openai-harmony / vLLM, not HF "
|
||||
"apply_chat_template — see test_gpt_oss_harmony_parity.py"
|
||||
)
|
||||
|
||||
|
||||
# Llama-3's chat template fills the "Today Date:" line via ``strftime_now``,
|
||||
# so ``apply_chat_template`` with no explicit ``date_string`` bakes in the
|
||||
# real wall-clock date — non-deterministic and not byte-stable against a
|
||||
# renderer pinned to "26 Jul 2024". Generic HF-parity tests can't pass a
|
||||
# kwarg, so they're skipped here; deterministic byte-parity (with the date
|
||||
# passed on both sides) is covered in test_llama_3.py.
|
||||
_LLAMA_HF_PARITY_TEST_FILES = {
|
||||
"test_render_ids.py",
|
||||
"test_build_helpers.py",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _skip_llama_for_hf_parity_tests(request):
|
||||
callspec = getattr(request.node, "callspec", None)
|
||||
model_name = callspec.params.get("model_name") if callspec else None
|
||||
if model_name != "meta-llama/Llama-3.2-1B-Instruct":
|
||||
return
|
||||
test_file = os.path.basename(str(request.node.fspath))
|
||||
if test_file in _LLAMA_HF_PARITY_TEST_FILES:
|
||||
pytest.skip(
|
||||
f"{model_name}: template uses strftime_now for the date line, so "
|
||||
"generic apply_chat_template parity is non-deterministic — "
|
||||
"deterministic byte-parity is covered in test_llama_3.py"
|
||||
)
|
||||
|
||||
+170
-14
@@ -20,10 +20,10 @@ from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# (HF model name, renderer name) — one representative per renderer class.
|
||||
_BRIDGE_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"),
|
||||
("PrimeIntellect/Qwen3-0.6B", "auto"),
|
||||
("Qwen/Qwen3.5-9B", "auto"),
|
||||
("Qwen/Qwen3.6-35B-A3B", "auto"),
|
||||
("zai-org/GLM-5", "auto"),
|
||||
@@ -33,6 +33,8 @@ _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"),
|
||||
]
|
||||
|
||||
@@ -41,9 +43,10 @@ _BRIDGE_MODELS = [
|
||||
def _load(model_name: str, renderer_name: str):
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import config_from_name
|
||||
|
||||
tok = load_tokenizer(model_name)
|
||||
return tok, create_renderer(tok, renderer=renderer_name)
|
||||
return tok, create_renderer(tok, config_from_name(renderer_name))
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc):
|
||||
@@ -65,7 +68,25 @@ def br_renderer(br_model, br_renderer_name):
|
||||
return _load(br_model, br_renderer_name)[1]
|
||||
|
||||
|
||||
def _simulate_prior_turn(renderer):
|
||||
@pytest.fixture
|
||||
def br_renderer_all(br_model, br_renderer_name):
|
||||
"""Renderer forced to ``thinking_retention="all"``.
|
||||
|
||||
The verbatim-extension mechanic tests below cross a user-query
|
||||
boundary. For thinking models the template drops a past block's
|
||||
thinking there, so the faithful bridge declines (covered by
|
||||
``test_bridge_declines_across_user_query_when_template_drops_thinking``).
|
||||
``"all"`` keeps thinking on every path, isolating the pure extension
|
||||
mechanic from the retention policy across all renderers.
|
||||
"""
|
||||
from renderers import create_renderer
|
||||
|
||||
tok, base = _load(br_model, br_renderer_name)
|
||||
cfg = base.config.model_copy(update={"thinking_retention": "all"})
|
||||
return create_renderer(tok, cfg)
|
||||
|
||||
|
||||
def _simulate_prior_turn(renderer, assistant=None):
|
||||
"""Build a (prev_prompt, prev_completion) pair that a real rollout
|
||||
would produce for a one-turn prior with a clean stop.
|
||||
|
||||
@@ -74,13 +95,15 @@ def _simulate_prior_turn(renderer):
|
||||
gen_prompt, and take the diff as prev_completion. We then trim
|
||||
prev_completion to the last close token so it matches what vLLM
|
||||
actually hands back (vLLM stops at the close token and excludes the
|
||||
trailing template scaffolding).
|
||||
trailing template scaffolding). Pass ``assistant`` to override the
|
||||
default no-thinking turn (e.g. one carrying ``reasoning_content``).
|
||||
"""
|
||||
prior = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi."},
|
||||
]
|
||||
assistant = [{"role": "assistant", "content": "Hello!"}]
|
||||
if assistant is None:
|
||||
assistant = [{"role": "assistant", "content": "Hello!"}]
|
||||
|
||||
prev_prompt = renderer.render_ids(prior, add_generation_prompt=True)
|
||||
full_with_assistant = renderer.render_ids(
|
||||
@@ -103,11 +126,11 @@ def _simulate_prior_turn(renderer):
|
||||
return prev_prompt, prev_completion
|
||||
|
||||
|
||||
def test_bridge_extends_prev_verbatim_on_clean_stop(br_renderer, br_model):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
|
||||
def test_bridge_extends_prev_verbatim_on_clean_stop(br_renderer_all, br_model):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer_all)
|
||||
new_messages = [{"role": "user", "content": "What's 2+2?"}]
|
||||
|
||||
bridged = br_renderer.bridge_to_next_turn(
|
||||
bridged = br_renderer_all.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, new_messages
|
||||
)
|
||||
assert bridged is not None, f"{br_model}: bridge returned None on clean stop"
|
||||
@@ -146,8 +169,8 @@ def test_bridge_rejects_empty_prev_or_new(br_renderer):
|
||||
assert br_renderer.bridge_to_next_turn(prev_prompt, prev_completion, []) is None
|
||||
|
||||
|
||||
def test_bridge_synthesises_close_on_truncation(br_renderer, br_model):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
|
||||
def test_bridge_synthesises_close_on_truncation(br_renderer_all, br_model):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer_all)
|
||||
# Drop the final close token to simulate a max_tokens truncation.
|
||||
prev_completion_trunc = prev_completion[:-1] if prev_completion else prev_completion
|
||||
if len(prev_completion_trunc) == 0:
|
||||
@@ -155,7 +178,7 @@ def test_bridge_synthesises_close_on_truncation(br_renderer, br_model):
|
||||
f"{br_model}: simulated prior had no completion tokens — can't truncate"
|
||||
)
|
||||
|
||||
bridged = br_renderer.bridge_to_next_turn(
|
||||
bridged = br_renderer_all.bridge_to_next_turn(
|
||||
prev_prompt,
|
||||
prev_completion_trunc,
|
||||
[{"role": "user", "content": "What's 2+2?"}],
|
||||
@@ -174,12 +197,12 @@ def test_bridge_synthesises_close_on_truncation(br_renderer, br_model):
|
||||
|
||||
|
||||
def test_bridge_extension_includes_new_message_text(
|
||||
br_renderer, br_tokenizer, br_model
|
||||
br_renderer_all, br_tokenizer, br_model
|
||||
):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer_all)
|
||||
new_messages = [{"role": "user", "content": "HELLO_SENTINEL_XYZ"}]
|
||||
|
||||
bridged = br_renderer.bridge_to_next_turn(
|
||||
bridged = br_renderer_all.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, new_messages
|
||||
)
|
||||
assert bridged is not None
|
||||
@@ -188,3 +211,136 @@ def test_bridge_extension_includes_new_message_text(
|
||||
assert "HELLO_SENTINEL_XYZ" in decoded, (
|
||||
f"{br_model}: new-message content missing from extension; got {decoded!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_bridge_declines_across_user_query_when_template_drops_thinking():
|
||||
"""Qwen3's template drops a past block's thinking once a new user turn
|
||||
arrives. The resolved ``tool_cycle`` bridge policy therefore treats a
|
||||
new user query as a hard re-render boundary, independent of whether the
|
||||
prior token stream happens to contain sampled thinking:
|
||||
|
||||
- new user query + retention="tool_cycle" -> decline,
|
||||
and the fallback re-render equals ``apply_chat_template``.
|
||||
- thinking_retention="all" keeps thinking on every path -> extend.
|
||||
- a tool response (in-flight cycle, no new query) keeps thinking in
|
||||
the template too -> extend.
|
||||
- no prior thinking + new user query -> decline; no marker lookback.
|
||||
"""
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import Qwen3RendererConfig
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen3-8B")
|
||||
im_end = tok.convert_tokens_to_ids("<|im_end|>")
|
||||
|
||||
u1 = {"role": "user", "content": "What is 2+2?"}
|
||||
u2 = {"role": "user", "content": "Multiply that by 3."}
|
||||
tool = {"role": "tool", "content": "ok"}
|
||||
think = "<think>\n2 plus 2 is 4.\n</think>\n\n4"
|
||||
|
||||
def prior(r, asst_text):
|
||||
p = r.render_ids([u1], add_generation_prompt=True)
|
||||
completion = tok.encode(asst_text, add_special_tokens=False) + [im_end]
|
||||
return p, completion
|
||||
|
||||
# new user query + prior thinking + default retention -> decline
|
||||
r = create_renderer(tok, Qwen3RendererConfig())
|
||||
p, comp = prior(r, think)
|
||||
assert r.bridge_to_next_turn(p, comp, [u2]) is None
|
||||
# ...and the caller's faithful re-render matches the chat template
|
||||
hist = [u1, {"role": "assistant", "content": think}, u2]
|
||||
rendered = tok.decode(r.render_ids(hist, add_generation_prompt=True))
|
||||
assert rendered == tok.apply_chat_template(
|
||||
hist, tokenize=False, add_generation_prompt=True
|
||||
)
|
||||
|
||||
# thinking_retention="all" keeps thinking everywhere -> extend
|
||||
r_all = create_renderer(tok, Qwen3RendererConfig(thinking_retention="all"))
|
||||
p, comp = prior(r_all, think)
|
||||
assert r_all.bridge_to_next_turn(p, comp, [u2]) is not None
|
||||
|
||||
# tool response continues the in-flight cycle (no new query) -> extend
|
||||
p, comp = prior(r, think)
|
||||
assert r.bridge_to_next_turn(p, comp, [tool]) is not None
|
||||
|
||||
# tool_cycle is a user-query-boundary policy; it does not scan prior tokens.
|
||||
p, comp = prior(r, "4")
|
||||
assert r.bridge_to_next_turn(p, comp, [u2]) is None
|
||||
|
||||
|
||||
# Renderers whose default/effective bridge policy declines at a new user-query
|
||||
# boundary. The exact query-boundary predicate can still be renderer-specific
|
||||
# (for example Qwen's folded ``<tool_response>`` user messages).
|
||||
# Non-thinking models (llama, deepseek-v3) are out of scope for this check.
|
||||
_GUARDED_THINKING_MODELS = {
|
||||
"Qwen/Qwen3-8B",
|
||||
"Qwen/Qwen3.5-9B",
|
||||
"Qwen/Qwen3.6-35B-A3B",
|
||||
"zai-org/GLM-5",
|
||||
"zai-org/GLM-5.1",
|
||||
"THUDM/GLM-4.5-Air",
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
|
||||
"MiniMaxAI/MiniMax-M2.5",
|
||||
"moonshotai/Kimi-K2.5",
|
||||
"openai/gpt-oss-20b",
|
||||
"tencent/Hy3",
|
||||
}
|
||||
|
||||
|
||||
def test_bridge_declines_across_user_turn_when_thinking_present(br_renderer, br_model):
|
||||
"""Across every guarded thinking renderer: a prior turn carrying
|
||||
``reasoning_content`` makes the bridge decline a new *user* query (the
|
||||
template would strip that thinking) but still extend a *tool* response
|
||||
(in-flight cycle keeps it). Non-guarded models are skipped."""
|
||||
if br_model not in _GUARDED_THINKING_MODELS:
|
||||
pytest.skip(f"{br_model}: no bridge thinking-guard")
|
||||
|
||||
asst = [
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Let me think.",
|
||||
"content": "",
|
||||
"tool_calls": [{"function": {"name": "lookup", "arguments": {"q": "x"}}}],
|
||||
}
|
||||
]
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer, asst)
|
||||
|
||||
declined = br_renderer.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, [{"role": "user", "content": "next"}]
|
||||
)
|
||||
assert declined is None, f"{br_model}: expected faithful decline across a user turn"
|
||||
|
||||
extended = br_renderer.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, [{"role": "tool", "content": "result"}]
|
||||
)
|
||||
assert extended is not None, f"{br_model}: should still bridge within a tool cycle"
|
||||
|
||||
|
||||
def test_bridge_keeps_thinking_when_history_kwarg_disables_truncation():
|
||||
"""GLM ``clear_thinking=False`` / Nemotron ``truncate_history_thinking=
|
||||
False`` keep all past thinking (the template doesn't strip it), so the
|
||||
bridge must NOT decline across a user turn — declining would re-render and
|
||||
re-tokenize model-sampled thinking bytes."""
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import GLM5RendererConfig, Nemotron3RendererConfig
|
||||
|
||||
asst = [
|
||||
{"role": "assistant", "reasoning_content": "Let me think.", "content": "Hi"}
|
||||
]
|
||||
cases = [
|
||||
("zai-org/GLM-5", GLM5RendererConfig(clear_thinking=False)),
|
||||
(
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
|
||||
Nemotron3RendererConfig(truncate_history_thinking=False),
|
||||
),
|
||||
]
|
||||
for model, cfg in cases:
|
||||
r = create_renderer(load_tokenizer(model), cfg)
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(r, asst)
|
||||
bridged = r.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, [{"role": "user", "content": "next"}]
|
||||
)
|
||||
assert bridged is not None, (
|
||||
f"{model}: bridge must keep verbatim when the template keeps all thinking"
|
||||
)
|
||||
|
||||
@@ -4,6 +4,17 @@ Runs against every (model, renderer) pair.
|
||||
"""
|
||||
|
||||
from renderers import build_training_sample, build_trajectory_step
|
||||
from renderers.base import PlaceholderRange, _build_mm_token_type_ids
|
||||
|
||||
|
||||
def test_build_mm_token_type_ids_marks_ranges():
|
||||
"""Image runs → 1, video runs → 2, everything else → 0; clips at length."""
|
||||
placeholders = {
|
||||
"image": [PlaceholderRange(offset=2, length=3)], # tokens 2,3,4
|
||||
"video": [PlaceholderRange(offset=7, length=2)], # tokens 7,8
|
||||
}
|
||||
ids = _build_mm_token_type_ids(placeholders, length=10)
|
||||
assert ids == [0, 0, 1, 1, 1, 0, 0, 2, 2, 0]
|
||||
|
||||
|
||||
def _expected(tokenizer, messages, **kwargs):
|
||||
@@ -29,10 +40,14 @@ def test_build_training_sample_ids_match(model_name, tokenizer, renderer):
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
ids, mask = build_training_sample(
|
||||
sample = build_training_sample(
|
||||
renderer, msgs, role_to_mask=lambda m: m["role"] == "assistant"
|
||||
)
|
||||
ids = sample.token_ids
|
||||
assert ids == _expected(tokenizer, msgs)
|
||||
# text-only sample carries no multimodal payload
|
||||
assert sample.multi_modal_data is None
|
||||
assert sample.mm_token_type_ids is None
|
||||
|
||||
|
||||
def test_build_training_sample_has_trainable_tokens(model_name, tokenizer, renderer):
|
||||
@@ -41,13 +56,42 @@ def test_build_training_sample_has_trainable_tokens(model_name, tokenizer, rende
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
ids, mask = build_training_sample(
|
||||
sample = build_training_sample(
|
||||
renderer, msgs, role_to_mask=lambda m: m["role"] == "assistant"
|
||||
)
|
||||
ids, mask = sample.token_ids, sample.loss_mask
|
||||
assert sum(mask) > 0
|
||||
assert len(mask) == len(ids)
|
||||
|
||||
|
||||
def test_build_training_sample_ensures_final_stop(model_name, tokenizer, renderer):
|
||||
"""The final assistant turn ends at a trainable renderer stop token.
|
||||
|
||||
Templates whose assistant close is part of the message (ChatML, Llama)
|
||||
already satisfy this, so the sample stays byte-identical; templates
|
||||
that terminate turns with the next message's role marker (GLM) get the
|
||||
canonical stop appended as the training target.
|
||||
"""
|
||||
if not renderer.render([{"role": "user", "content": "x"}]).sampled_mask:
|
||||
return # DefaultRenderer: no sampled_mask, role-only masking
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
sample = build_training_sample(renderer, msgs, ensure_final_stop=True)
|
||||
stop_ids = set(renderer.get_stop_token_ids())
|
||||
last_trainable = max(k for k, m in enumerate(sample.loss_mask) if m)
|
||||
assert sample.token_ids[last_trainable] in stop_ids
|
||||
|
||||
baseline = build_training_sample(renderer, msgs)
|
||||
if (
|
||||
baseline.token_ids[max(k for k, m in enumerate(baseline.loss_mask) if m)]
|
||||
in stop_ids
|
||||
):
|
||||
# In-message close: ensure_final_stop must not change the bytes.
|
||||
assert sample.token_ids == baseline.token_ids
|
||||
|
||||
|
||||
def test_build_trajectory_step_reconstructs_full(model_name, tokenizer, renderer):
|
||||
"""prompt_ids + completion_ids must equal the full rendered sequence."""
|
||||
prompt = [
|
||||
|
||||
+227
-16
@@ -1,8 +1,10 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
|
||||
import pytest
|
||||
from renderers.base import (
|
||||
ParsedResponse,
|
||||
ParsedToolCall,
|
||||
@@ -19,7 +21,15 @@ class _FakeRenderer:
|
||||
assert messages == [{"role": "user", "content": "hi"}]
|
||||
assert tools == [{"type": "function", "function": {"name": "echo"}}]
|
||||
assert add_generation_prompt is True
|
||||
return RenderedTokens(token_ids=[1, 2, 3])
|
||||
# Populate the full attribution surface so the test can verify
|
||||
# ``generate`` threads it through to the result dict unchanged.
|
||||
return RenderedTokens(
|
||||
token_ids=[1, 2, 3],
|
||||
message_indices=[0, 0, -1],
|
||||
sampled_mask=[False, False, False],
|
||||
is_content=[False, True, False],
|
||||
message_roles=["user"],
|
||||
)
|
||||
|
||||
def render_ids(self, messages, *, tools=None, add_generation_prompt=False):
|
||||
return self.render(
|
||||
@@ -62,8 +72,8 @@ class _FakeClient:
|
||||
self.calls.append(
|
||||
{"path": path, "cast_to": cast_to, "body": body, "options": options}
|
||||
)
|
||||
routed_experts = np.array([[[1]], [[2]]], dtype=np.int32)
|
||||
return {
|
||||
routed_experts = np.array([[[1]], [[2]]], dtype=np.uint8)
|
||||
payload = {
|
||||
"request_id": "gen-test",
|
||||
"choices": [
|
||||
{
|
||||
@@ -77,7 +87,7 @@ class _FakeClient:
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
"routed_experts": {
|
||||
"data": base64.b85encode(routed_experts.tobytes()).decode(
|
||||
"data": base64.b64encode(routed_experts.tobytes()).decode(
|
||||
"ascii"
|
||||
),
|
||||
"shape": list(routed_experts.shape),
|
||||
@@ -85,6 +95,10 @@ class _FakeClient:
|
||||
}
|
||||
],
|
||||
}
|
||||
return httpx.Response(
|
||||
200,
|
||||
content=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
|
||||
)
|
||||
|
||||
|
||||
def test_generate_builds_request_body_and_parses_response():
|
||||
@@ -113,6 +127,7 @@ def test_generate_builds_request_body_and_parses_response():
|
||||
# /inference/v1/generate is mounted at the server root, so we post to
|
||||
# an absolute URL stripped of the OpenAI SDK's automatic /v1 prefix.
|
||||
assert client.calls[0]["path"] == "http://fake-host:8000/inference/v1/generate"
|
||||
assert client.calls[0]["cast_to"] is httpx.Response
|
||||
assert client.calls[0]["body"] == {
|
||||
"model": "test-model",
|
||||
"token_ids": [1, 2, 3],
|
||||
@@ -134,9 +149,22 @@ def test_generate_builds_request_body_and_parses_response():
|
||||
assert result["prompt_ids"] == [1, 2, 3]
|
||||
assert result["completion_ids"] == [7, 8]
|
||||
assert result["completion_logprobs"] == [-0.1, -0.2]
|
||||
assert result["routed_experts"] == [[[1]], [[2]]]
|
||||
assert result["routed_experts"]["shape"] == [2, 1, 1]
|
||||
assert isinstance(result["routed_experts"]["data"], memoryview)
|
||||
assert result["routed_experts"]["data"].tobytes() == base64.b64encode(b"\x01\x02")
|
||||
assert result["multi_modal_data"] is None
|
||||
assert result["request_id"] == "gen-test"
|
||||
# Per-token attribution from the renderer surfaces on the result so
|
||||
# downstream consumers (verifiers RendererClient → prime-rl) can
|
||||
# build selective loss masks without a second render pass.
|
||||
attr = result["prompt_attribution"]
|
||||
assert attr is not None
|
||||
assert isinstance(attr, RenderedTokens)
|
||||
assert attr.token_ids == [1, 2, 3]
|
||||
assert attr.is_content == [False, True, False]
|
||||
assert attr.sampled_mask == [False, False, False]
|
||||
assert attr.message_indices == [0, 0, -1]
|
||||
assert attr.message_roles == ["user"]
|
||||
assert len(result["tool_calls"]) == 1
|
||||
tc = result["tool_calls"][0]
|
||||
assert tc.name == "echo"
|
||||
@@ -207,6 +235,44 @@ def test_generate_uses_prebuilt_prompt_ids_without_rendering():
|
||||
|
||||
assert client.calls[0]["body"]["token_ids"] == [11, 12, 13]
|
||||
assert result["prompt_ids"] == [11, 12, 13]
|
||||
# Pre-built prompt without explicit attribution → ``None`` carried
|
||||
# through. Consumers fall back to whatever attribution-free path
|
||||
# they have (e.g. uniform completion mask).
|
||||
assert result["prompt_attribution"] is None
|
||||
|
||||
|
||||
def test_generate_threads_prompt_attribution_through_prebuilt_prompt_path():
|
||||
"""When the caller passes both ``prompt_ids`` and ``prompt_attribution``
|
||||
(the multi-turn bridge path in verifiers), ``generate`` must thread
|
||||
the attribution through to the result dict unchanged — no re-rendering,
|
||||
no per-token reshuffling. Lets downstream consumers carry the
|
||||
renderer's body/scaffold cut into the trajectory step without an
|
||||
extra render pass."""
|
||||
client = _FakeClient()
|
||||
# Caller-supplied attribution; mirrors what
|
||||
# ``RendererClient._get_incremental_prompt_ids`` returns from the
|
||||
# bridge_to_next_turn output.
|
||||
supplied = RenderedTokens(
|
||||
token_ids=[11, 12, 13],
|
||||
message_indices=[-1, 0, 0],
|
||||
sampled_mask=[False, False, False],
|
||||
is_content=[False, True, True],
|
||||
message_roles=["tool"],
|
||||
)
|
||||
|
||||
result = asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=_NoRenderRenderer(),
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
prompt_ids=[11, 12, 13],
|
||||
prompt_attribution=supplied,
|
||||
)
|
||||
)
|
||||
|
||||
# Exact passthrough — same object, no copy / no transform.
|
||||
assert result["prompt_attribution"] is supplied
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -214,30 +280,42 @@ def test_generate_uses_prebuilt_prompt_ids_without_rendering():
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_generate_serializes_multimodal_features_for_qwen3_vl():
|
||||
@pytest.mark.parametrize(
|
||||
"model_id,renderer_class_path",
|
||||
[
|
||||
("Qwen/Qwen3-VL-4B-Instruct", "renderers.qwen3_vl:Qwen3VLRenderer"),
|
||||
("Qwen/Qwen3.5-2B", "renderers.qwen35:Qwen35Renderer"),
|
||||
],
|
||||
ids=["qwen3_vl", "qwen35"],
|
||||
)
|
||||
def test_generate_serializes_multimodal_features_for_qwen_vl_family(
|
||||
model_id, renderer_class_path
|
||||
):
|
||||
"""When the renderer emits ``MultiModalData``, ``generate`` translates
|
||||
it into vLLM's ``features`` payload (mm_hashes + mm_placeholders +
|
||||
base64-encoded kwargs_data) and sticks it in the request body."""
|
||||
import pytest as _pytest
|
||||
base64-encoded kwargs_data) and sticks it in the request body. Covers
|
||||
every renderer routed through ``_build_qwen_vl_features``."""
|
||||
import importlib
|
||||
|
||||
_pytest.importorskip("torch")
|
||||
_pytest.importorskip("vllm", reason="vllm needed for features serialization")
|
||||
pytest.importorskip("torch")
|
||||
pytest.importorskip("vllm", reason="vllm needed for features serialization")
|
||||
|
||||
import torch as _torch
|
||||
|
||||
from renderers.base import (
|
||||
MultiModalData,
|
||||
PlaceholderRange,
|
||||
load_tokenizer,
|
||||
)
|
||||
from renderers.qwen3_vl import Qwen3VLRenderer
|
||||
|
||||
# Build a minimal real Qwen3VLRenderer so type dispatch in
|
||||
mod_name, cls_name = renderer_class_path.split(":")
|
||||
renderer_cls = getattr(importlib.import_module(mod_name), cls_name)
|
||||
|
||||
# Build a minimal real renderer so type dispatch in
|
||||
# _build_mm_features hits the qwen branch. The tokenizer is only
|
||||
# touched in __init__ to grab special-token ids; render() / etc.
|
||||
# aren't called here because we pre-supply prompt_ids + mm_data.
|
||||
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
|
||||
renderer = Qwen3VLRenderer(tokenizer)
|
||||
tokenizer = load_tokenizer(model_id)
|
||||
renderer = renderer_cls(tokenizer)
|
||||
|
||||
# Two synthetic 1×2×2 images. Field factory expects pixel_values
|
||||
# shape ``(sum_HW, embed_dim)`` and grid_thw shape ``(N, 3)``; the
|
||||
@@ -291,3 +369,136 @@ def test_generate_serializes_multimodal_features_for_qwen3_vl():
|
||||
# Items are base64 strings (encode_mm_kwargs_item output).
|
||||
for item in features["kwargs_data"]["image"]:
|
||||
assert isinstance(item, str) and len(item) > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompt overflow handling.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _LongRenderer(_FakeRenderer):
|
||||
"""Renders a 10-token prompt regardless of input — enough to overflow a
|
||||
small ``max_prompt_len``."""
|
||||
|
||||
def render(self, messages, *, tools=None, add_generation_prompt=False):
|
||||
from renderers.base import RenderedTokens
|
||||
|
||||
return RenderedTokens(token_ids=list(range(10)))
|
||||
|
||||
|
||||
def test_generate_raises_overlong_prompt_when_explicit_cap_exceeded():
|
||||
"""Pre-flight overflow check: when an explicit ``max_prompt_len`` is set
|
||||
and the rendered prompt is longer, ``generate`` raises
|
||||
``OverlongPromptError`` without dispatching the request to the engine."""
|
||||
from renderers.client import OverlongPromptError
|
||||
|
||||
client = _FakeClient()
|
||||
renderer = _LongRenderer()
|
||||
|
||||
with pytest.raises(OverlongPromptError) as excinfo:
|
||||
asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=renderer,
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
max_prompt_len=4,
|
||||
)
|
||||
)
|
||||
|
||||
assert excinfo.value.prompt_len == 10
|
||||
assert excinfo.value.max_prompt_len == 4
|
||||
assert client.calls == [], "request must not be dispatched on pre-flight fail"
|
||||
|
||||
|
||||
def test_generate_allows_prompt_at_max_prompt_len():
|
||||
"""A prompt exactly equal to ``max_prompt_len`` is allowed (the check is
|
||||
strict ``>``); only longer prompts trip the pre-flight."""
|
||||
client = _FakeClient()
|
||||
renderer = _LongRenderer()
|
||||
|
||||
result = asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=renderer,
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
max_prompt_len=10,
|
||||
)
|
||||
)
|
||||
|
||||
assert len(client.calls) == 1
|
||||
assert result["prompt_ids"] == list(range(10))
|
||||
|
||||
|
||||
def test_generate_auto_discovers_max_prompt_len_from_models_endpoint():
|
||||
"""When ``max_prompt_len`` is ``None`` (default), ``generate`` discovers
|
||||
the cap via ``GET /v1/models`` and reads ``ModelCard.max_model_len``.
|
||||
The result is cached per ``(base_url, model)`` so subsequent calls
|
||||
don't re-query."""
|
||||
from renderers.client import OverlongPromptError, _max_prompt_len_cache
|
||||
|
||||
class _ClientWithModels(_FakeClient):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.base_url = "http://disco-host:8000/v1"
|
||||
self.models_calls = 0
|
||||
|
||||
async def get(self, path, *, cast_to):
|
||||
self.models_calls += 1
|
||||
assert path == "/models"
|
||||
return {
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id": "test-model", "max_model_len": 4},
|
||||
{"id": "other", "max_model_len": 999},
|
||||
],
|
||||
}
|
||||
|
||||
# Clear cache so this test isn't affected by earlier ones.
|
||||
_max_prompt_len_cache.clear()
|
||||
|
||||
client = _ClientWithModels()
|
||||
renderer = _LongRenderer()
|
||||
|
||||
with pytest.raises(OverlongPromptError) as excinfo:
|
||||
asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=renderer,
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
)
|
||||
)
|
||||
|
||||
assert excinfo.value.max_prompt_len == 4
|
||||
assert excinfo.value.prompt_len == 10
|
||||
assert client.models_calls == 1, "lookup must hit /models once"
|
||||
assert client.calls == [], "pre-flight must short-circuit the request"
|
||||
|
||||
|
||||
def test_generate_caches_max_prompt_len_lookup_failure():
|
||||
"""When ``GET /v1/models`` fails (e.g. mock client without ``.get``),
|
||||
the lookup result is cached as ``None`` and the pre-flight quietly
|
||||
disables — the request still goes through, callers fall back to
|
||||
whatever reactive overflow handling they have."""
|
||||
from renderers.client import _max_prompt_len_cache
|
||||
|
||||
# _FakeClient has no .get method → AttributeError → cached None.
|
||||
_max_prompt_len_cache.clear()
|
||||
client = _FakeClient()
|
||||
client.base_url = "http://no-models:8000/v1"
|
||||
|
||||
result = asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=_LongRenderer(),
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
)
|
||||
)
|
||||
|
||||
# Request was dispatched (no pre-flight rejection) and round-tripped.
|
||||
assert len(client.calls) == 1
|
||||
assert result["prompt_ids"] == list(range(10))
|
||||
assert _max_prompt_len_cache[("http://no-models:8000/v1", "test-model")] is None
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""DeepSeek-R1 renderer: the reasoning variant of the DeepSeek format.
|
||||
|
||||
General byte-parity vs ``apply_chat_template`` is covered by the conftest
|
||||
barrage (``test_render_ids`` now includes both DeepSeek models). These tests
|
||||
pin the behaviors that distinguish R1 from V3: the ``<think>`` generation
|
||||
prompt and the stripping of ``</think>`` from historical assistant turns.
|
||||
"""
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import (
|
||||
DeepSeekR1Renderer,
|
||||
DeepSeekV3Renderer,
|
||||
create_renderer,
|
||||
)
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _r1():
|
||||
tok = load_tokenizer("deepseek-ai/DeepSeek-R1")
|
||||
return tok, create_renderer(tok)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _v3():
|
||||
tok = load_tokenizer("deepseek-ai/DeepSeek-V3")
|
||||
return tok, create_renderer(tok)
|
||||
|
||||
|
||||
# Baseline render_ids == apply_chat_template parity. Tool-cycle shapes are
|
||||
# intentionally excluded: the DeepSeek template renders tool_calls only when
|
||||
# content is None (a pre-existing renderer↔template gap, tracked separately),
|
||||
# which is orthogonal to the V3/R1 reasoning split this module covers.
|
||||
_PARITY_SHAPES = [
|
||||
(
|
||||
"single_turn",
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{"role": "assistant", "content": "4"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"multi_turn",
|
||||
[
|
||||
{"role": "user", "content": "A"},
|
||||
{"role": "assistant", "content": "B"},
|
||||
{"role": "user", "content": "C"},
|
||||
{"role": "assistant", "content": "D"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"reasoning_content_field",
|
||||
[
|
||||
{"role": "user", "content": "x"},
|
||||
{"role": "assistant", "reasoning_content": "r", "content": "4"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"gen_prompt",
|
||||
[
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
],
|
||||
{"add_generation_prompt": True},
|
||||
),
|
||||
(
|
||||
"inline_think_history",
|
||||
[
|
||||
{"role": "user", "content": "q"},
|
||||
{"role": "assistant", "content": "<think>reasoning</think>answer"},
|
||||
{"role": "user", "content": "q2"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loader", [_v3, _r1], ids=["v3", "r1"])
|
||||
@pytest.mark.parametrize(
|
||||
"shape_id,messages,kwargs", _PARITY_SHAPES, ids=[s[0] for s in _PARITY_SHAPES]
|
||||
)
|
||||
def test_render_ids_matches_apply_chat_template(loader, shape_id, messages, kwargs):
|
||||
tok, renderer = loader()
|
||||
got = renderer.render_ids(messages, **kwargs)
|
||||
expected = list(
|
||||
tok.apply_chat_template(messages, tokenize=True, return_dict=False, **kwargs)
|
||||
)
|
||||
assert got == expected
|
||||
|
||||
|
||||
def test_auto_detection_picks_the_right_renderer():
|
||||
_, r1 = _r1()
|
||||
_, v3 = _v3()
|
||||
assert isinstance(r1, DeepSeekR1Renderer)
|
||||
assert isinstance(v3, DeepSeekV3Renderer)
|
||||
|
||||
|
||||
def test_generation_prompt_differs():
|
||||
"""R1 prefills ``<think>`` to trigger reasoning; V3 does not."""
|
||||
msgs = [{"role": "user", "content": "hi"}]
|
||||
tr1, r1 = _r1()
|
||||
tv3, v3 = _v3()
|
||||
|
||||
r1_text = tr1.decode(r1.render_ids(msgs, add_generation_prompt=True))
|
||||
v3_text = tv3.decode(v3.render_ids(msgs, add_generation_prompt=True))
|
||||
|
||||
# R1 prefills <think> to trigger reasoning; V3 emits a bare assistant
|
||||
# turn. (Exact byte parity vs apply_chat_template is the gen_prompt case
|
||||
# in the parity matrix above; here we just pin the V3/R1 distinction —
|
||||
# decode trims the trailing "\n" so we don't match on it.)
|
||||
assert "<think>" in r1_text and r1_text.rstrip().endswith("<think>")
|
||||
assert "<think>" not in v3_text
|
||||
|
||||
|
||||
def test_r1_strips_reasoning_from_history():
|
||||
"""A historical assistant turn carrying an inline ``<think>…</think>``
|
||||
trace renders only the post-``</think>`` answer, byte-identical to the R1
|
||||
chat template's ``content.split('</think>')[-1]``.
|
||||
"""
|
||||
tok, r1 = _r1()
|
||||
msgs = [
|
||||
{"role": "user", "content": "q"},
|
||||
{"role": "assistant", "content": "<think>private reasoning</think>The answer."},
|
||||
{"role": "user", "content": "q2"},
|
||||
]
|
||||
got = r1.render_ids(msgs)
|
||||
expected = list(tok.apply_chat_template(msgs, tokenize=True, return_dict=False))
|
||||
|
||||
assert got == expected
|
||||
# Reasoning must not survive into the rendered history.
|
||||
assert "private reasoning" not in tok.decode(got)
|
||||
|
||||
|
||||
def test_v3_emits_content_verbatim_ignoring_reasoning():
|
||||
"""V3 (non-reasoning) ignores ``reasoning_content`` — matching its
|
||||
template, which only reads ``content``."""
|
||||
tok, v3 = _v3()
|
||||
msgs = [
|
||||
{"role": "user", "content": "x"},
|
||||
{"role": "assistant", "reasoning_content": "should be ignored", "content": "4"},
|
||||
]
|
||||
got = v3.render_ids(msgs)
|
||||
expected = list(tok.apply_chat_template(msgs, tokenize=True, return_dict=False))
|
||||
|
||||
assert got == expected
|
||||
assert "should be ignored" not in tok.decode(got)
|
||||
@@ -33,6 +33,7 @@ from openai_harmony import (
|
||||
ToolDescription,
|
||||
load_harmony_encoding,
|
||||
)
|
||||
from renderers.configs import GptOssRendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
@@ -49,7 +50,9 @@ def tokenizer():
|
||||
def renderer(tokenizer):
|
||||
# Pin the date so the rendered preamble matches the harmony oracle
|
||||
# built with the same fixed date.
|
||||
return GptOssRenderer(tokenizer, conversation_start_date=DATE_FOR_PARITY)
|
||||
return GptOssRenderer(
|
||||
tokenizer, GptOssRendererConfig(conversation_start_date=DATE_FOR_PARITY)
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Hermes regressions on Trinity's real multi-token tool delimiters."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from renderers.base import ToolCallParseStatus
|
||||
from renderers.configs import DefaultRendererConfig
|
||||
from renderers.default import DefaultRenderer
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def trinity_tokenizer():
|
||||
return AutoTokenizer.from_pretrained(
|
||||
"arcee-ai/Trinity-Mini",
|
||||
revision="cdb81e8130815fec299cccc8f8700004b8366e1e",
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hermes_renderer(trinity_tokenizer):
|
||||
return DefaultRenderer(
|
||||
trinity_tokenizer,
|
||||
DefaultRendererConfig(tool_parser="hermes", reasoning_parser="think"),
|
||||
)
|
||||
|
||||
|
||||
CALL = '<tool_call>{"name":"book_flight","arguments":{"dest":"Paris"}}</tool_call>'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
f"<think>Consider {CALL}, but do not book.</think>No.",
|
||||
f"Consider {CALL}, but do not book.</think>No.",
|
||||
f"<think>Unclosed reasoning containing {CALL}",
|
||||
f"Unclosed prefilled reasoning containing {CALL}",
|
||||
f"Finished reasoning.</think>```json\n{CALL}\n```",
|
||||
f"Finished reasoning.</think>~~~json\n{CALL}\n~~~",
|
||||
f"Finished reasoning.</think>Example: `{CALL}`.",
|
||||
'Finished reasoning.</think>```json\n{"name":"book_flight","arguments":{"dest":"Paris"}}\n```',
|
||||
'Finished reasoning.</think>{"name":"book_flight","arguments":{"dest":"Paris"}}',
|
||||
],
|
||||
)
|
||||
def test_examples_are_not_actions(trinity_tokenizer, hermes_renderer, text):
|
||||
ids = trinity_tokenizer.encode(text, add_special_tokens=False)
|
||||
remaining, calls = hermes_renderer._tool_parser.extract(ids)
|
||||
assert remaining == ids
|
||||
assert calls == []
|
||||
assert hermes_renderer.parse_response(ids).tool_calls == []
|
||||
|
||||
|
||||
def test_native_calls_preserve_reasoning_content_and_original_spans(trinity_tokenizer, hermes_renderer):
|
||||
text = f"Consider the destination.</think>é🙂 before{CALL}between{CALL}after"
|
||||
ids = trinity_tokenizer.encode(text, add_special_tokens=False)
|
||||
parsed = hermes_renderer.parse_response(ids)
|
||||
assert parsed.reasoning_content == "Consider the destination."
|
||||
assert parsed.content == "é🙂 beforebetweenafter"
|
||||
assert len(parsed.tool_calls) == 2
|
||||
for call in parsed.tool_calls:
|
||||
assert call.status == ToolCallParseStatus.OK
|
||||
assert call.name == "book_flight" and call.arguments == {"dest": "Paris"}
|
||||
start, end = call.token_span
|
||||
assert 0 <= start < end <= len(ids)
|
||||
covered = trinity_tokenizer.decode(ids[start:end], skip_special_tokens=False)
|
||||
assert CALL in covered
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body,status",
|
||||
[
|
||||
('{"name":"f","arguments":{}}', ToolCallParseStatus.OK),
|
||||
('{"name":"f","arguments":[]}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":"f","arguments":null}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":"f","arguments":"{}"}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":"f"}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":42,"arguments":{}}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":" ","arguments":{}}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
("[]", ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
("{'name':'f','arguments':{}}", ToolCallParseStatus.INVALID_JSON),
|
||||
('{"name":"f","arguments":{"x":NaN}}', ToolCallParseStatus.INVALID_JSON),
|
||||
('{"name":"f","arguments":{"x":Infinity}}', ToolCallParseStatus.INVALID_JSON),
|
||||
('{"name":"f","name":"g","arguments":{}}', ToolCallParseStatus.INVALID_JSON),
|
||||
('{"name":"f","arguments":{}} trailing', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
],
|
||||
)
|
||||
def test_strict_native_envelopes(trinity_tokenizer, hermes_renderer, body, status):
|
||||
ids = trinity_tokenizer.encode(f"Use the tool.</think><tool_call>{body}</tool_call>", add_special_tokens=False)
|
||||
parsed = hermes_renderer.parse_response(ids)
|
||||
assert len(parsed.tool_calls) == 1
|
||||
assert parsed.tool_calls[0].status == status
|
||||
if status != ToolCallParseStatus.OK:
|
||||
assert parsed.tool_calls[0].name is None
|
||||
|
||||
|
||||
def test_tag_strings_in_arguments_do_not_close_a_call(trinity_tokenizer, hermes_renderer):
|
||||
args = {"text": '</tool_call> <think> ``` <tool_call> " café🙂'}
|
||||
body = json.dumps({"name": "f", "arguments": args}, ensure_ascii=False)
|
||||
ids = trinity_tokenizer.encode(
|
||||
f"Use the tool.</think><tool_call>{body}</tool_call>suffix", add_special_tokens=False
|
||||
)
|
||||
parsed = hermes_renderer.parse_response(ids)
|
||||
assert parsed.content == "suffix"
|
||||
assert parsed.tool_calls[0].arguments == args
|
||||
assert parsed.tool_calls[0].status == ToolCallParseStatus.OK
|
||||
|
||||
|
||||
def test_unclosed_call_remains_a_parse_error(trinity_tokenizer, hermes_renderer):
|
||||
ids = trinity_tokenizer.encode(
|
||||
'Use the tool.</think><tool_call>{"name":"f","arguments":{}}', add_special_tokens=False
|
||||
)
|
||||
parsed = hermes_renderer.parse_response(ids)
|
||||
assert parsed.tool_calls[0].status == ToolCallParseStatus.UNCLOSED_BLOCK
|
||||
assert parsed.tool_calls[0].name is None
|
||||
|
||||
|
||||
def test_real_schema_uses_native_chat_template(trinity_tokenizer, hermes_renderer):
|
||||
tool = {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "book_flight",
|
||||
"description": "Book a flight.",
|
||||
"parameters": {"type": "object", "properties": {"dest": {"type": "string"}}},
|
||||
},
|
||||
}
|
||||
result = hermes_renderer.render(
|
||||
[{"role": "user", "content": "Book a flight to Paris."}],
|
||||
tools=[tool],
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
text = trinity_tokenizer.decode(result.token_ids, skip_special_tokens=False)
|
||||
assert "book_flight" in text and "<tools>" in text and "<tool_call>" in text
|
||||
assert "available_actions" not in text
|
||||
assert "```json" not in text
|
||||
assert text.endswith("<think>\n")
|
||||
@@ -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
|
||||
)
|
||||
@@ -0,0 +1,390 @@
|
||||
"""Per-token ``RenderedTokens.is_content`` invariants.
|
||||
|
||||
``is_content[k]`` answers "does ``token_ids[k]`` come from message body
|
||||
bytes (caller-provided content / tool_calls / reasoning_content, or
|
||||
the model's sampled emission for the assistant role) or is it template
|
||||
scaffolding the renderer added around the body (role tags, special
|
||||
tokens, separators, tool-response wraps, generation prompt)?"
|
||||
|
||||
By design ``is_content`` is a superset of ``sampled_mask``:
|
||||
|
||||
- Equal on every token attributed to an assistant message (sampled ==
|
||||
body for that role by construction).
|
||||
- Carries new information on every other role: the model never samples
|
||||
user / tool / system tokens, so ``sampled_mask`` is uniformly
|
||||
``False`` over those — ``is_content`` differentiates body from wrap.
|
||||
|
||||
These tests parametrise across every renderer in
|
||||
``conftest.RENDERER_MODELS`` and verify the contract for hand-coded
|
||||
renderers. ``DefaultRenderer`` leaves ``is_content`` empty by design
|
||||
(the Jinja template is opaque, so the renderer cannot know the
|
||||
wrap/body split) and is exempt from the populated-length check.
|
||||
|
||||
The body-bytes decode invariant uses ``in`` (substring) rather than
|
||||
strict equality because some renderers normalise whitespace, strip
|
||||
trailing newlines, etc. within the message body emit — but the
|
||||
caller-provided content must always be recoverable as a substring of
|
||||
the decoded body run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _is_populated(rendered) -> bool:
|
||||
return len(rendered.is_content) == len(rendered.token_ids) and bool(
|
||||
rendered.is_content
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_length_or_empty(model_name, renderer):
|
||||
"""``is_content`` is either empty (opt-out) or matches token_ids
|
||||
length exactly. No partial fills."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
n_tokens = len(rendered.token_ids)
|
||||
n_mask = len(rendered.is_content)
|
||||
assert n_mask == 0 or n_mask == n_tokens, (
|
||||
f"{model_name}: is_content length {n_mask} must be 0 or match "
|
||||
f"token_ids length {n_tokens}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_equals_sampled_on_assistant(model_name, renderer):
|
||||
"""On every token attributed to an assistant message,
|
||||
``is_content[k] == sampled_mask[k]``. The two signals collapse on
|
||||
that role by design — the model's sampled output IS the assistant
|
||||
message's body, and the surrounding scaffold is neither sampled
|
||||
nor body."""
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello world!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
if len(rendered.sampled_mask) != len(rendered.token_ids):
|
||||
return # renderer opts out of sampled_mask
|
||||
|
||||
mismatches = []
|
||||
for k, msg_idx in enumerate(rendered.message_indices):
|
||||
if msg_idx < 0:
|
||||
continue
|
||||
if msgs[msg_idx].get("role") != "assistant":
|
||||
continue
|
||||
if rendered.is_content[k] != rendered.sampled_mask[k]:
|
||||
mismatches.append((k, rendered.is_content[k], rendered.sampled_mask[k]))
|
||||
assert not mismatches, (
|
||||
f"{model_name}: is_content != sampled_mask on assistant tokens "
|
||||
f"(k, is_content, sampled): {mismatches[:8]}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_excludes_generation_prompt(model_name, renderer):
|
||||
"""All generation-prompt tokens (msg_idx=-1) are scaffold — the
|
||||
next-turn opener the chat template injects so the model can
|
||||
continue. ``is_content`` must be False over that entire span."""
|
||||
msgs = [{"role": "user", "content": "Hi"}]
|
||||
rendered = renderer.render(msgs, add_generation_prompt=True)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
bad = [
|
||||
k
|
||||
for k, (msg_idx, is_content) in enumerate(
|
||||
zip(rendered.message_indices, rendered.is_content)
|
||||
)
|
||||
if msg_idx == -1 and is_content
|
||||
]
|
||||
assert not bad, (
|
||||
f"{model_name}: generation-prompt tokens marked is_content=True "
|
||||
f"at positions {bad[:8]}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_recovers_user_body(model_name, tokenizer, renderer):
|
||||
"""The decoded run of is_content=True tokens within a user message
|
||||
contains the user's original content. ``in`` rather than equality
|
||||
because some templates normalise whitespace inside the body emit;
|
||||
the input substring must still be recoverable from the decoded
|
||||
body run."""
|
||||
user_text = "Hello, my name is Sebastian."
|
||||
msgs = [
|
||||
{"role": "user", "content": user_text},
|
||||
{"role": "assistant", "content": "Hi!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
user_body_ids = [
|
||||
tid
|
||||
for tid, mi, ic in zip(
|
||||
rendered.token_ids, rendered.message_indices, rendered.is_content
|
||||
)
|
||||
if mi == 0 and ic
|
||||
]
|
||||
assert user_body_ids, (
|
||||
f"{model_name}: no is_content=True tokens attributed to user message"
|
||||
)
|
||||
decoded = tokenizer.decode(user_body_ids).strip()
|
||||
assert user_text in decoded or decoded in user_text, (
|
||||
f"{model_name}: user body run decodes to {decoded!r}, "
|
||||
f"expected to contain {user_text!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_recovers_tool_body(model_name, tokenizer, renderer):
|
||||
"""The decoded run of is_content=True tokens within a tool message
|
||||
contains the tool response body. The whole point of the body/wrap
|
||||
cut: SFT on this run trains the model to anticipate tool outputs
|
||||
without learning to emit the surrounding ``<|tool_response>`` /
|
||||
role-tag scaffold (which would interrupt a real rollout)."""
|
||||
tool_text = "The capital of France is Paris."
|
||||
msgs = [
|
||||
{"role": "user", "content": "What's the capital of France?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"id": "call_1",
|
||||
"function": {
|
||||
"name": "lookup",
|
||||
"arguments": {"q": "capital of France"},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": tool_text, "tool_call_id": "call_1"},
|
||||
{"role": "assistant", "content": "Paris."},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
tool_body_ids = [
|
||||
tid
|
||||
for tid, mi, ic in zip(
|
||||
rendered.token_ids, rendered.message_indices, rendered.is_content
|
||||
)
|
||||
if mi == 2 and ic
|
||||
]
|
||||
assert tool_body_ids, (
|
||||
f"{model_name}: no is_content=True tokens attributed to tool message"
|
||||
)
|
||||
decoded = tokenizer.decode(tool_body_ids).strip()
|
||||
assert tool_text in decoded, (
|
||||
f"{model_name}: tool body run decodes to {decoded!r}, "
|
||||
f"expected to contain {tool_text!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_recovers_system_body(model_name, tokenizer, renderer):
|
||||
"""The decoded run of is_content=True tokens within a system
|
||||
message contains the caller-provided system content. Tools header
|
||||
/ footer (if present) are scaffold and never appear as body."""
|
||||
sys_text = "You are an unusually precise assistant."
|
||||
msgs = [
|
||||
{"role": "system", "content": sys_text},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hi!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
sys_body_ids = [
|
||||
tid
|
||||
for tid, mi, ic in zip(
|
||||
rendered.token_ids, rendered.message_indices, rendered.is_content
|
||||
)
|
||||
if mi == 0 and ic
|
||||
]
|
||||
assert sys_body_ids, (
|
||||
f"{model_name}: no is_content=True tokens attributed to system message"
|
||||
)
|
||||
decoded = tokenizer.decode(sys_body_ids).strip()
|
||||
assert sys_text in decoded, (
|
||||
f"{model_name}: system body run decodes to {decoded!r}, "
|
||||
f"expected to contain {sys_text!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_no_body_on_role_tag(model_name, renderer):
|
||||
"""The first token attributed to a user/system/tool message must
|
||||
have ``is_content=False`` — that's the leading role-tag run
|
||||
(``<|im_start|>`` / equivalent), which is template scaffold, never
|
||||
body."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
user_positions = [k for k, idx in enumerate(rendered.message_indices) if idx == 0]
|
||||
assert user_positions, f"{model_name}: no tokens attributed to user message"
|
||||
first_k = user_positions[0]
|
||||
assert not rendered.is_content[first_k], (
|
||||
f"{model_name}: first user-attributed token at k={first_k} should "
|
||||
f"be is_content=False (role-tag scaffolding), but was True"
|
||||
)
|
||||
|
||||
|
||||
def test_content_token_spans_by_role_isolates_tool_body(
|
||||
model_name, tokenizer, renderer
|
||||
):
|
||||
"""``content_token_spans_by_role()["tool"]`` returns spans over
|
||||
which every token is the tool message body. Joining the decoded
|
||||
spans recovers the tool response. Adjacent scaffold tokens
|
||||
(``<|tool_response>``, role-tag openers) are never inside any
|
||||
returned span."""
|
||||
tool_text = "Result: 42"
|
||||
msgs = [
|
||||
{"role": "user", "content": "What's 6*7?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"id": "call_x",
|
||||
"function": {"name": "calc", "arguments": {"e": "6*7"}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": tool_text, "tool_call_id": "call_x"},
|
||||
{"role": "assistant", "content": "42."},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
spans = rendered.content_token_spans_by_role()
|
||||
tool_spans = spans.get("tool") or []
|
||||
assert tool_spans, f"{model_name}: no tool content spans returned"
|
||||
|
||||
pieces: list[str] = []
|
||||
for s, e in tool_spans:
|
||||
run_ids = rendered.token_ids[s:e]
|
||||
# All tokens in the span must be is_content=True by definition.
|
||||
for k in range(s, e):
|
||||
assert rendered.is_content[k], (
|
||||
f"{model_name}: span {(s, e)} contains is_content=False at k={k}"
|
||||
)
|
||||
pieces.append(tokenizer.decode(run_ids))
|
||||
joined = "".join(pieces).strip()
|
||||
assert tool_text in joined, (
|
||||
f"{model_name}: joined tool spans decode to {joined!r}, "
|
||||
f"expected to contain {tool_text!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_content_mask_for_roles_excludes_assistant_when_unset(model_name, renderer):
|
||||
"""``content_mask_for_roles({"tool"})`` returns a mask that's True
|
||||
only on tool body tokens — never on assistant tokens, even though
|
||||
those also have ``is_content=True``. The role filter is the whole
|
||||
point: SFT-on-tool-body must not bleed into the assistant span."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"id": "call_a",
|
||||
"function": {"name": "ping", "arguments": {}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "pong", "tool_call_id": "call_a"},
|
||||
{"role": "assistant", "content": "OK."},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
tool_mask = rendered.content_mask_for_roles({"tool"})
|
||||
assert len(tool_mask) == len(rendered.token_ids)
|
||||
|
||||
for k, mi in enumerate(rendered.message_indices):
|
||||
if mi < 0:
|
||||
assert not tool_mask[k], (
|
||||
f"{model_name}: scaffold token k={k} (msg_idx=-1) marked in tool mask"
|
||||
)
|
||||
continue
|
||||
role = msgs[mi].get("role")
|
||||
if role != "tool" and tool_mask[k]:
|
||||
raise AssertionError(
|
||||
f"{model_name}: tool-role mask True on a {role!r} token at k={k}"
|
||||
)
|
||||
|
||||
|
||||
def test_build_training_sample_content_sft_roles_picks_up_tool_body(
|
||||
model_name, renderer
|
||||
):
|
||||
"""``build_training_sample(..., content_sft_roles={"tool"})``
|
||||
produces a loss mask that's True on tool body tokens AND assistant
|
||||
sampled tokens, but False on the tool-message scaffold (role tag,
|
||||
``<|tool_response>`` wraps, separators). The canonical
|
||||
SFT-on-tool-body + RL-on-assistant composition."""
|
||||
from renderers import build_training_sample
|
||||
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"id": "call_z",
|
||||
"function": {"name": "noop", "arguments": {}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "done", "tool_call_id": "call_z"},
|
||||
{"role": "assistant", "content": "OK."},
|
||||
]
|
||||
sample = build_training_sample(
|
||||
renderer,
|
||||
msgs,
|
||||
role_to_mask=lambda m: m["role"] == "assistant",
|
||||
content_sft_roles={"tool"},
|
||||
)
|
||||
ids, mask = sample.token_ids, sample.loss_mask
|
||||
assert len(mask) == len(ids)
|
||||
|
||||
# We need at least one trainable tool-body token if the renderer
|
||||
# populates is_content. Renderers that opt out (empty is_content)
|
||||
# fall back to the existing role_to_mask behaviour, which leaves
|
||||
# tool tokens False — that's the documented fallback and is fine.
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
trainable_per_role: dict[str, int] = {}
|
||||
for k, mi in enumerate(rendered.message_indices):
|
||||
if mi < 0:
|
||||
continue
|
||||
if mask[k]:
|
||||
r = msgs[mi].get("role") or ""
|
||||
trainable_per_role[r] = trainable_per_role.get(r, 0) + 1
|
||||
|
||||
assert trainable_per_role.get("tool", 0) > 0, (
|
||||
f"{model_name}: build_training_sample with content_sft_roles={{'tool'}} "
|
||||
f"trained on zero tool tokens"
|
||||
)
|
||||
assert trainable_per_role.get("assistant", 0) > 0, (
|
||||
f"{model_name}: assistant tokens dropped from training mask"
|
||||
)
|
||||
assert trainable_per_role.get("user", 0) == 0, (
|
||||
f"{model_name}: user tokens leaked into training mask: {trainable_per_role}"
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Kimi K2.5 tool-schema TypeScript rendering: bool/null literal correctness.
|
||||
|
||||
Regression for PR #55: ``_function_to_typescript`` used to leak Python
|
||||
literals (``True`` / ``False`` / ``None``) into output advertised as
|
||||
TypeScript. Both call sites — ``_EnumType.to_typescript_style`` (for
|
||||
non-string enum members) and ``_TypedParam.to_typescript_style`` (for
|
||||
bool defaults) — now route non-string values through ``json.dumps`` so
|
||||
booleans and ``None`` render as ``true`` / ``false`` / ``null``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from renderers.kimi_k25 import _function_to_typescript
|
||||
|
||||
|
||||
def test_bool_default_renders_as_json_literal():
|
||||
"""Bool defaults must render as ``true`` / ``false``, not ``True`` / ``False``."""
|
||||
out = _function_to_typescript(
|
||||
{
|
||||
"name": "set_logging",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"verbose": {"type": "boolean", "default": True},
|
||||
"quiet": {"type": "boolean", "default": False},
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
assert "// Default: true" in out
|
||||
assert "// Default: false" in out
|
||||
assert "Default: True" not in out
|
||||
assert "Default: False" not in out
|
||||
|
||||
|
||||
def test_enum_non_string_members_render_as_json_literals():
|
||||
"""``null`` / bool / int enum members must render as JSON literals, not Python ``repr``."""
|
||||
out = _function_to_typescript(
|
||||
{
|
||||
"name": "set_mode",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {"enum": ["auto", None, True, False, 0]},
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
assert '"auto" | null | true | false | 0' in out
|
||||
# Python literals must not leak through.
|
||||
assert "None" not in out
|
||||
assert "True" not in out
|
||||
assert "False" not in out
|
||||
@@ -0,0 +1,376 @@
|
||||
"""Laguna-XS-2.1 focused tests.
|
||||
|
||||
The shared matrices (conftest / config-parity) already assert byte
|
||||
parity on the common shapes; this file pins the behaviours specific to
|
||||
the XS-2.1 template that those matrices don't generate:
|
||||
|
||||
- the empty-system opt-out (and the empty ``<system></system>`` block
|
||||
under ``enable_thinking``),
|
||||
- verbatim content / reasoning (no whitespace normalisation),
|
||||
- reasoning gated on ``enable_thinking`` rather than on the data,
|
||||
- packed tool-call args,
|
||||
- parse round-trips under ``enable_thinking=True`` (the shared roundtrip
|
||||
matrix runs the default config, where the template drops reasoning at
|
||||
render time, so reasoning can't round-trip there by design),
|
||||
- bridge extensions matching a fresh render byte-for-byte.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import LagunaXS21RendererConfig
|
||||
from renderers.laguna_xs2 import LagunaXS21Renderer
|
||||
|
||||
_MODEL = "poolside/Laguna-XS-2.1"
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "The city name"},
|
||||
"days": {"type": "integer", "description": "Forecast days"},
|
||||
},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _tok():
|
||||
return load_tokenizer(_MODEL)
|
||||
|
||||
|
||||
def _renderer(**config_kwargs) -> LagunaXS21Renderer:
|
||||
renderer = create_renderer(_tok(), LagunaXS21RendererConfig(**config_kwargs))
|
||||
assert isinstance(renderer, LagunaXS21Renderer)
|
||||
return renderer
|
||||
|
||||
|
||||
def _expected(msgs, *, tools=None, add_generation_prompt=False, **template_kwargs):
|
||||
return list(
|
||||
_tok().apply_chat_template(
|
||||
msgs,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
**template_kwargs,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ── Variant-specific byte parity ──────────────────────────────────────
|
||||
|
||||
|
||||
def test_empty_system_opts_out_of_system_block():
|
||||
"""An empty caller system message suppresses the default system
|
||||
prompt; with no tools and no thinking there is no <system> block."""
|
||||
msgs = [
|
||||
{"role": "system", "content": ""},
|
||||
{"role": "user", "content": "Hi"},
|
||||
]
|
||||
r = _renderer()
|
||||
assert r.render_ids(msgs, add_generation_prompt=True) == _expected(
|
||||
msgs, add_generation_prompt=True
|
||||
)
|
||||
text = _tok().decode(r.render_ids(msgs, add_generation_prompt=True))
|
||||
assert "<system>" not in text
|
||||
|
||||
|
||||
def test_empty_system_with_thinking_renders_empty_block():
|
||||
"""enable_thinking alone forces the <system> block, even when the
|
||||
empty caller system message removed all of its content."""
|
||||
msgs = [
|
||||
{"role": "system", "content": ""},
|
||||
{"role": "user", "content": "Hi"},
|
||||
]
|
||||
r = _renderer(enable_thinking=True)
|
||||
ours = r.render_ids(msgs, add_generation_prompt=True)
|
||||
assert ours == _expected(msgs, add_generation_prompt=True, enable_thinking=True)
|
||||
assert "<system></system>\n" in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_empty_system_with_tools_glues_tools_header():
|
||||
"""With the system content opted out, the tools section opens the
|
||||
block directly: ``<system>### Tools`` with no separating newlines."""
|
||||
msgs = [
|
||||
{"role": "system", "content": ""},
|
||||
{"role": "user", "content": "Weather?"},
|
||||
]
|
||||
r = _renderer()
|
||||
ours = r.render_ids(msgs, tools=TOOLS, add_generation_prompt=True)
|
||||
assert ours == _expected(msgs, tools=TOOLS, add_generation_prompt=True)
|
||||
assert "<system>### Tools" in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_reasoning_dropped_without_thinking():
|
||||
"""enable_thinking=False renders a bare ``</think>`` and drops the
|
||||
message's reasoning entirely."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{"role": "assistant", "reasoning_content": "Simple arithmetic", "content": "4"},
|
||||
]
|
||||
r = _renderer()
|
||||
ours = r.render_ids(msgs)
|
||||
assert ours == _expected(msgs)
|
||||
assert "Simple arithmetic" not in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_reasoning_rendered_verbatim_with_thinking():
|
||||
"""enable_thinking=True wraps the reasoning verbatim — whitespace
|
||||
included, empty included."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "\n spaced reasoning \n",
|
||||
"content": "4",
|
||||
},
|
||||
]
|
||||
r = _renderer(enable_thinking=True)
|
||||
ours = r.render_ids(msgs)
|
||||
assert ours == _expected(msgs, enable_thinking=True)
|
||||
assert "<think>\n spaced reasoning \n</think>" in _tok().decode(ours)
|
||||
|
||||
no_reasoning = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
ours = r.render_ids(no_reasoning)
|
||||
assert ours == _expected(no_reasoning, enable_thinking=True)
|
||||
assert "<think></think>" in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_content_rendered_verbatim():
|
||||
"""Assistant content is not stripped or newline-normalised."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "\n keep my whitespace \n"},
|
||||
]
|
||||
r = _renderer()
|
||||
assert r.render_ids(msgs) == _expected(msgs)
|
||||
|
||||
|
||||
def test_multiple_tool_calls_packed_args():
|
||||
"""Tool-call args pack tightly with mixed value types (strings
|
||||
verbatim, non-strings via tojson)."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Compare Tokyo and Paris"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "Let me check.",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Tokyo", "days": 3},
|
||||
}
|
||||
},
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "Sunny"},
|
||||
{"role": "tool", "content": "Rainy"},
|
||||
]
|
||||
r = _renderer()
|
||||
ours = r.render_ids(msgs, tools=TOOLS, add_generation_prompt=True)
|
||||
assert ours == _expected(msgs, tools=TOOLS, add_generation_prompt=True)
|
||||
assert (
|
||||
"<tool_call>get_weather<arg_key>city</arg_key><arg_value>Tokyo</arg_value>"
|
||||
"<arg_key>days</arg_key><arg_value>3</arg_value></tool_call>"
|
||||
) in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_later_system_message_renders_in_loop():
|
||||
"""A system message after the first renders inline as
|
||||
``<system>{content}</system>``; only the leading one is absorbed
|
||||
into the header."""
|
||||
msgs = [
|
||||
{"role": "system", "content": "Be helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
{"role": "system", "content": "Now be terse."},
|
||||
{"role": "user", "content": "Why?"},
|
||||
]
|
||||
r = _renderer()
|
||||
assert r.render_ids(msgs, add_generation_prompt=True) == _expected(
|
||||
msgs, add_generation_prompt=True
|
||||
)
|
||||
|
||||
|
||||
# ── Masks ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_assistant_prefill_tokens_unsampled():
|
||||
"""The generation prompt is ``<assistant>`` plus the mode's think
|
||||
tag — in a re-render both are scaffold, everything after (through
|
||||
``</assistant>``) is sampled, and the inter-turn newline is not."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "reasoning_content": "greeting", "content": "Hello!"},
|
||||
]
|
||||
for enable_thinking in (False, True):
|
||||
r = _renderer(enable_thinking=enable_thinking)
|
||||
rendered = r.render(msgs)
|
||||
positions = [k for k, i in enumerate(rendered.message_indices) if i == 1]
|
||||
sampled = [rendered.sampled_mask[k] for k in positions]
|
||||
# <assistant> + (<think> | </think>) prefill.
|
||||
assert sampled[:2] == [False, False]
|
||||
# Everything between the prefill and the inter-turn newline is
|
||||
# the model's emission, ending with the sampled </assistant>.
|
||||
assert all(sampled[2:-1]), sampled
|
||||
assert sampled[-1] is False # trailing "\n"
|
||||
assert [rendered.is_content[k] for k in positions] == sampled
|
||||
|
||||
|
||||
# ── Parse ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _completion_ids(text: str) -> list[int]:
|
||||
return _tok().encode(text, add_special_tokens=False)
|
||||
|
||||
|
||||
def test_parse_no_think_completion():
|
||||
"""Under the no-think gen prompt (``</think>`` prefilled), the
|
||||
completion is pure content up to ``</assistant>``."""
|
||||
parsed = _renderer().parse_response(_completion_ids("Four.</assistant>"))
|
||||
assert parsed.content == "Four."
|
||||
assert parsed.reasoning_content is None
|
||||
assert not parsed.tool_calls
|
||||
|
||||
|
||||
def test_parse_preserves_newlines_verbatim():
|
||||
"""The template renders content verbatim, so the parse must not
|
||||
strip the newlines the model emitted."""
|
||||
parsed = _renderer(enable_thinking=True).parse_response(
|
||||
_completion_ids("Chain of thought</think>\nThe answer.\n</assistant>")
|
||||
)
|
||||
assert parsed.reasoning_content == "Chain of thought"
|
||||
assert parsed.content == "\nThe answer.\n"
|
||||
|
||||
|
||||
def test_parse_tool_call_packed_args():
|
||||
parsed = _renderer().parse_response(
|
||||
_completion_ids(
|
||||
"I will check.<tool_call>get_weather"
|
||||
"<arg_key>city</arg_key><arg_value>Tokyo</arg_value>"
|
||||
"<arg_key>days</arg_key><arg_value>3</arg_value>"
|
||||
"</tool_call></assistant>"
|
||||
),
|
||||
tools=TOOLS,
|
||||
)
|
||||
assert parsed.content == "I will check."
|
||||
assert len(parsed.tool_calls) == 1
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.name == "get_weather"
|
||||
assert tc.arguments == {"city": "Tokyo", "days": 3}
|
||||
|
||||
|
||||
def test_roundtrip_reasoning_with_thinking():
|
||||
"""render → parse recovers reasoning and content under
|
||||
enable_thinking=True (the mode where the template keeps them)."""
|
||||
r = _renderer(enable_thinking=True)
|
||||
prompt = [{"role": "user", "content": "What is 2+2?"}]
|
||||
msg = {
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Two plus two equals four.",
|
||||
"content": "The answer is four.",
|
||||
}
|
||||
pp = r.render_ids(prompt, add_generation_prompt=True)
|
||||
full = r.render_ids([*prompt, msg])
|
||||
completion = full[len(pp) :]
|
||||
parsed = r.parse_response(completion)
|
||||
assert parsed.reasoning_content == "Two plus two equals four."
|
||||
assert parsed.content == "The answer is four."
|
||||
|
||||
|
||||
# ── Bridge ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _bridge_case(r, prev, asst, ext, *, tools=None, **template_kwargs):
|
||||
"""Return (bridged, fresh) token ids for extending prev+asst by ext."""
|
||||
pp = r.render_ids(prev, tools=tools, add_generation_prompt=True)
|
||||
full_turn = r.render_ids([*prev, asst], tools=tools)
|
||||
# The turn ends "</assistant>\n"; the model's completion stops at
|
||||
# </assistant>, so drop the template's inter-turn newline token.
|
||||
completion = full_turn[len(pp) : -1]
|
||||
assert completion[-1] == r._assistant_end
|
||||
bridged = r.bridge_to_next_turn(pp, completion, ext, tools=tools)
|
||||
fresh = r.render_ids([*prev, asst, *ext], tools=tools, add_generation_prompt=True)
|
||||
return bridged, fresh
|
||||
|
||||
|
||||
def test_bridge_user_extension_matches_full_render():
|
||||
prev = [{"role": "user", "content": "Hi"}]
|
||||
asst = {"role": "assistant", "content": "Hello!"}
|
||||
ext = [{"role": "user", "content": "Bye"}]
|
||||
for enable_thinking in (False, True):
|
||||
r = _renderer(enable_thinking=enable_thinking)
|
||||
bridged, fresh = _bridge_case(r, prev, asst, ext)
|
||||
assert bridged is not None
|
||||
assert bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_tool_extension_matches_full_render():
|
||||
prev = [{"role": "user", "content": "Weather in Tokyo, then Paris?"}]
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Tokyo"}}}
|
||||
],
|
||||
}
|
||||
ext = [
|
||||
{"role": "tool", "content": "Sunny"},
|
||||
{"role": "user", "content": "And Paris?"},
|
||||
{"role": "tool", "content": "Rainy"},
|
||||
]
|
||||
r = _renderer()
|
||||
bridged, fresh = _bridge_case(r, prev, asst, ext, tools=TOOLS)
|
||||
assert bridged is not None
|
||||
assert bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_synthesizes_close_on_truncation():
|
||||
prev = [{"role": "user", "content": "Hi"}]
|
||||
asst = {"role": "assistant", "content": "Hello!"}
|
||||
ext = [{"role": "user", "content": "Bye"}]
|
||||
r = _renderer()
|
||||
pp = r.render_ids(prev, add_generation_prompt=True)
|
||||
full_turn = r.render_ids([*prev, asst])
|
||||
# Truncated: no </assistant> in the completion.
|
||||
completion = full_turn[len(pp) : -2]
|
||||
assert r._assistant_end not in completion
|
||||
bridged = r.bridge_to_next_turn(pp, completion, ext)
|
||||
assert bridged is not None
|
||||
# The synthesised close makes the tape identical to the clean-stop
|
||||
# bridge, which matches the fresh render byte-for-byte.
|
||||
fresh = r.render_ids([*prev, asst, *ext], add_generation_prompt=True)
|
||||
assert bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_rejects_assistant_extension():
|
||||
r = _renderer()
|
||||
prev = [{"role": "user", "content": "Hi"}]
|
||||
pp = r.render_ids(prev, add_generation_prompt=True)
|
||||
assert (
|
||||
r.bridge_to_next_turn(
|
||||
pp, [r._assistant_end], [{"role": "assistant", "content": "x"}]
|
||||
)
|
||||
is None
|
||||
)
|
||||
@@ -0,0 +1,417 @@
|
||||
"""Llama-3 renderer coverage.
|
||||
|
||||
Covers ``Llama3Renderer`` and the ``meta-llama/Llama-3.2-{1B,3B}-Instruct``
|
||||
entries in ``MODEL_RENDERER_MAP``. ``load_tokenizer`` uses the
|
||||
unrestricted ``unsloth/Llama-3.2-{1B,3B}-Instruct`` mirrors underneath
|
||||
(verified byte-identical chat templates) so CI doesn't need an HF token
|
||||
with Meta license access.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import Llama3Renderer, Llama3RendererConfig, create_renderer
|
||||
from renderers.base import (
|
||||
MODEL_RENDERER_MAP,
|
||||
ParsedResponse,
|
||||
ToolCallParseStatus,
|
||||
load_tokenizer,
|
||||
)
|
||||
|
||||
# Pinned date for byte-parity tests. Matches the chat template's
|
||||
# strftime fallback so we don't have to override on the apply side.
|
||||
_PINNED_DATE = "26 Jul 2024"
|
||||
|
||||
_MODEL_PAIRS = [
|
||||
# (canonical meta-llama id used by MODEL_RENDERER_MAP, unrestricted
|
||||
# mirror used to actually load the tokenizer in tests)
|
||||
("meta-llama/Llama-3.2-1B-Instruct", "unsloth/Llama-3.2-1B-Instruct"),
|
||||
("meta-llama/Llama-3.2-3B-Instruct", "unsloth/Llama-3.2-3B-Instruct"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=_MODEL_PAIRS, ids=[m for m, _ in _MODEL_PAIRS])
|
||||
def llama_pair(request):
|
||||
canonical, mirror = request.param
|
||||
tok = load_tokenizer(canonical)
|
||||
renderer = Llama3Renderer(tok, Llama3RendererConfig(date_string=_PINNED_DATE))
|
||||
return canonical, mirror, tok, renderer
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MODEL_RENDERER_MAP shape
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_canonical_meta_llama_paths_route_to_llama_3():
|
||||
for canonical, _ in _MODEL_PAIRS:
|
||||
assert MODEL_RENDERER_MAP.get(canonical) == "llama-3", (
|
||||
f"{canonical}: expected to route to 'llama-3'"
|
||||
)
|
||||
|
||||
|
||||
def test_create_renderer_via_explicit_config(llama_pair):
|
||||
"""``Llama3RendererConfig`` resolves to Llama3Renderer in the registry."""
|
||||
_, _, tok, _ = llama_pair
|
||||
r = create_renderer(tok, Llama3RendererConfig())
|
||||
assert isinstance(r, Llama3Renderer)
|
||||
|
||||
|
||||
def test_create_renderer_auto_resolves_after_mirror_load(llama_pair):
|
||||
"""``load_tokenizer(canonical_meta_id)`` loads from the unrestricted
|
||||
mirror but preserves the canonical name needed for auto-resolution."""
|
||||
canonical, _, tok, _ = llama_pair
|
||||
assert tok.name_or_path == canonical
|
||||
assert isinstance(create_renderer(tok), Llama3Renderer)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constructor contract
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_default_date_matches_chat_template_strftime_fallback(llama_pair):
|
||||
"""Default ``date_string`` is ``"26 Jul 2024"`` so output stays
|
||||
deterministic without an explicit override."""
|
||||
_, _, tok, _ = llama_pair
|
||||
r = Llama3Renderer(tok)
|
||||
assert r.config.date_string == _PINNED_DATE
|
||||
|
||||
|
||||
def test_preserve_thinking_flags_are_noops(llama_pair):
|
||||
"""Llama-3 has no reasoning channel, so any ``thinking_retention``
|
||||
level is accepted but never changes the token stream — the same
|
||||
never-preserves contract as Kimi-K2 / Qwen3-VL. (Cross-renderer
|
||||
coverage lives in tests/test_preserve_thinking.py.)"""
|
||||
_, _, tok, _ = llama_pair
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi."},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "internal musings",
|
||||
"content": "Hello!",
|
||||
},
|
||||
]
|
||||
base = Llama3Renderer(tok).render_ids(msgs)
|
||||
for level in ("tool_cycle", "all"):
|
||||
r = Llama3Renderer(tok, Llama3RendererConfig(thinking_retention=level))
|
||||
assert r.config.thinking_retention == level
|
||||
assert r.render_ids(msgs) == base, (
|
||||
f"thinking_retention={level!r} must be a no-op for Llama-3"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Byte parity vs apply_chat_template
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _expected(tok, messages, **kwargs):
|
||||
kwargs.setdefault("add_generation_prompt", False)
|
||||
kwargs.setdefault("date_string", _PINNED_DATE)
|
||||
return list(
|
||||
tok.apply_chat_template(messages, tokenize=True, return_dict=False, **kwargs)
|
||||
)
|
||||
|
||||
|
||||
def test_parity_minimal_user(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
msgs = [{"role": "user", "content": "Hi."}]
|
||||
assert r.render_ids(msgs) == _expected(tok, msgs)
|
||||
|
||||
|
||||
def test_parity_system_and_user(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi."},
|
||||
]
|
||||
assert r.render_ids(msgs) == _expected(tok, msgs)
|
||||
|
||||
|
||||
def test_parity_system_user_assistant(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi."},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
assert r.render_ids(msgs) == _expected(tok, msgs)
|
||||
|
||||
|
||||
def test_parity_no_system_with_gen_prompt(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
msgs = [{"role": "user", "content": "Hi."}]
|
||||
assert r.render_ids(msgs, add_generation_prompt=True) == _expected(
|
||||
tok, msgs, add_generation_prompt=True
|
||||
)
|
||||
|
||||
|
||||
def test_parity_multi_turn(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
msgs = [
|
||||
{"role": "user", "content": "A"},
|
||||
{"role": "assistant", "content": "B"},
|
||||
{"role": "user", "content": "C"},
|
||||
{"role": "assistant", "content": "D"},
|
||||
]
|
||||
assert r.render_ids(msgs) == _expected(tok, msgs)
|
||||
|
||||
|
||||
def test_parity_trims_whitespace(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
msgs = [
|
||||
{"role": "user", "content": " hello "},
|
||||
{"role": "assistant", "content": "\n\nworld\n"},
|
||||
]
|
||||
assert r.render_ids(msgs) == _expected(tok, msgs)
|
||||
|
||||
|
||||
def test_parity_custom_date(llama_pair):
|
||||
"""``date_string`` constructor override changes both sides identically."""
|
||||
_, _, tok, _ = llama_pair
|
||||
r = Llama3Renderer(tok, Llama3RendererConfig(date_string="01 Jan 2026"))
|
||||
msgs = [{"role": "user", "content": "Hi."}]
|
||||
expected = list(
|
||||
tok.apply_chat_template(
|
||||
msgs, tokenize=True, return_dict=False, date_string="01 Jan 2026"
|
||||
)
|
||||
)
|
||||
assert r.render_ids(msgs) == expected
|
||||
|
||||
|
||||
def test_parity_tools_in_user_default(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get weather",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
msgs = [
|
||||
{"role": "system", "content": "Be terse."},
|
||||
{"role": "user", "content": "Weather?"},
|
||||
]
|
||||
assert r.render_ids(msgs, tools=tools) == _expected(tok, msgs, tools=tools)
|
||||
|
||||
|
||||
def test_parity_tools_in_system_mode(llama_pair):
|
||||
"""When constructed with ``tools_in_user_message=False``, the renderer
|
||||
matches ``apply_chat_template(... tools_in_user_message=False)``."""
|
||||
_, _, tok, _ = llama_pair
|
||||
r = Llama3Renderer(
|
||||
tok,
|
||||
Llama3RendererConfig(date_string=_PINNED_DATE, tools_in_user_message=False),
|
||||
)
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {"name": "get_weather", "parameters": {}},
|
||||
}
|
||||
]
|
||||
msgs = [
|
||||
{"role": "system", "content": "Be terse."},
|
||||
{"role": "user", "content": "Weather?"},
|
||||
]
|
||||
expected = list(
|
||||
tok.apply_chat_template(
|
||||
msgs,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
tools=tools,
|
||||
tools_in_user_message=False,
|
||||
date_string=_PINNED_DATE,
|
||||
)
|
||||
)
|
||||
assert r.render_ids(msgs, tools=tools) == expected
|
||||
|
||||
|
||||
def test_parity_tool_call_round_trip(llama_pair):
|
||||
"""Assistant tool_calls + tool response + final assistant — covers
|
||||
the JSON tool-call body emission and the ``ipython`` response role."""
|
||||
_, _, tok, r = llama_pair
|
||||
msgs = [
|
||||
{"role": "user", "content": "Weather?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "NYC"},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 72}'},
|
||||
{"role": "assistant", "content": "It's 72."},
|
||||
]
|
||||
assert r.render_ids(msgs) == _expected(tok, msgs)
|
||||
|
||||
|
||||
def test_parity_tool_response_dict_content(llama_pair):
|
||||
"""Tool response with mapping content goes through ``tojson`` in the
|
||||
template; the renderer's ``_tool_response_str`` mirrors that."""
|
||||
_, _, tok, r = llama_pair
|
||||
msgs = [
|
||||
{"role": "user", "content": "x"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_calls": [{"function": {"name": "f", "arguments": {}}}],
|
||||
},
|
||||
{"role": "tool", "content": {"k": "v", "n": 42}},
|
||||
{"role": "assistant", "content": "ok"},
|
||||
]
|
||||
assert r.render_ids(msgs) == _expected(tok, msgs)
|
||||
|
||||
|
||||
def test_render_raises_on_multiple_tool_calls(llama_pair):
|
||||
"""Llama-3 chat template explicitly raises on >1 tool call per turn —
|
||||
the renderer mirrors that contract."""
|
||||
_, _, _, r = llama_pair
|
||||
msgs = [
|
||||
{"role": "user", "content": "x"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "f", "arguments": {}}},
|
||||
{"function": {"name": "g", "arguments": {}}},
|
||||
],
|
||||
},
|
||||
]
|
||||
with pytest.raises(ValueError, match="single tool call"):
|
||||
r.render_ids(msgs)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# parse_response
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _tokens_for(tok, text: str) -> list[int]:
|
||||
return tok.encode(text, add_special_tokens=False)
|
||||
|
||||
|
||||
def test_parse_response_plain_content(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
ids = _tokens_for(tok, "Hello, world!") + [r._eot]
|
||||
out = r.parse_response(ids)
|
||||
assert isinstance(out, ParsedResponse)
|
||||
assert out.content == "Hello, world!"
|
||||
assert out.tool_calls == []
|
||||
assert out.reasoning_content is None
|
||||
|
||||
|
||||
def test_parse_response_tool_call(llama_pair):
|
||||
_, _, tok, r = llama_pair
|
||||
body = '{"name": "get_weather", "parameters": {"city": "NYC"}}'
|
||||
ids = _tokens_for(tok, body) + [r._eot]
|
||||
out = r.parse_response(ids)
|
||||
assert out.content == ""
|
||||
assert len(out.tool_calls) == 1
|
||||
tc = out.tool_calls[0]
|
||||
assert tc.status == ToolCallParseStatus.OK
|
||||
assert tc.name == "get_weather"
|
||||
assert tc.arguments == {"city": "NYC"}
|
||||
|
||||
|
||||
def test_parse_response_malformed_tool_call_falls_through_to_content(llama_pair):
|
||||
"""A body that LOOKS like a tool call but doesn't parse should land
|
||||
in content rather than dropping silently."""
|
||||
_, _, tok, r = llama_pair
|
||||
body = '{"name": "x", broken'
|
||||
ids = _tokens_for(tok, body) + [r._eot]
|
||||
out = r.parse_response(ids)
|
||||
assert out.tool_calls == []
|
||||
assert "{" in out.content
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bridge contract
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _simulate_prior_turn(r):
|
||||
prior = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi."},
|
||||
]
|
||||
asst = [{"role": "assistant", "content": "Hello!"}]
|
||||
|
||||
prev_prompt = r.render_ids(prior, add_generation_prompt=True)
|
||||
full = r.render_ids(prior + asst, add_generation_prompt=False)
|
||||
prev_completion = list(full[len(prev_prompt) :])
|
||||
|
||||
stop = set(r.get_stop_token_ids())
|
||||
last = -1
|
||||
for i in range(len(prev_completion) - 1, -1, -1):
|
||||
if prev_completion[i] in stop:
|
||||
last = i
|
||||
break
|
||||
if last >= 0:
|
||||
prev_completion = prev_completion[: last + 1]
|
||||
return prev_prompt, prev_completion
|
||||
|
||||
|
||||
def test_bridge_extends_prev_verbatim_on_clean_stop(llama_pair):
|
||||
_, _, _, r = llama_pair
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(r)
|
||||
new_messages = [{"role": "user", "content": "What's 2+2?"}]
|
||||
bridged = r.bridge_to_next_turn(prev_prompt, prev_completion, new_messages)
|
||||
assert bridged is not None
|
||||
prev = prev_prompt + prev_completion
|
||||
assert bridged.token_ids[: len(prev)] == prev
|
||||
assert len(bridged.token_ids) > len(prev)
|
||||
|
||||
|
||||
def test_bridge_matches_fresh_render_on_clean_stop(llama_pair):
|
||||
"""The whole point of the bridge: it must produce the same tokens as
|
||||
a fresh render of the full message list — except sampled tokens are
|
||||
kept verbatim rather than re-rendered."""
|
||||
_, _, _, r = llama_pair
|
||||
prior = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi."},
|
||||
]
|
||||
asst = [{"role": "assistant", "content": "Hello!"}]
|
||||
new_messages = [{"role": "user", "content": "What's 2+2?"}]
|
||||
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(r)
|
||||
bridged = r.bridge_to_next_turn(prev_prompt, prev_completion, new_messages)
|
||||
fresh = r.render_ids(prior + asst + new_messages, add_generation_prompt=True)
|
||||
assert bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_rejects_assistant_in_extension(llama_pair):
|
||||
_, _, _, r = llama_pair
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(r)
|
||||
bridged = r.bridge_to_next_turn(
|
||||
prev_prompt,
|
||||
prev_completion,
|
||||
[{"role": "assistant", "content": "forbidden"}],
|
||||
)
|
||||
assert bridged is None
|
||||
|
||||
|
||||
def test_bridge_synthesises_close_on_truncation(llama_pair):
|
||||
_, _, _, r = llama_pair
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(r)
|
||||
trunc = prev_completion[:-1]
|
||||
if not trunc:
|
||||
pytest.skip("simulated prior had no completion tokens to truncate")
|
||||
bridged = r.bridge_to_next_turn(
|
||||
prev_prompt, trunc, [{"role": "user", "content": "ping"}]
|
||||
)
|
||||
assert bridged is not None
|
||||
base = prev_prompt + trunc
|
||||
assert bridged.token_ids[: len(base)] == base
|
||||
assert len(bridged.token_ids) > len(base)
|
||||
@@ -9,9 +9,13 @@ repo doesn't auto-propagate.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from renderers.base import TRUSTED_REVISIONS, load_tokenizer
|
||||
import pytest
|
||||
|
||||
from renderers import base
|
||||
from renderers.base import TOKENIZER_SOURCE_OVERRIDES, TRUSTED_REVISIONS, load_tokenizer
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -70,6 +74,23 @@ def test_kimi_loads_with_pinned_revision(mock_from_pretrained):
|
||||
}
|
||||
|
||||
|
||||
@patch("transformers.AutoTokenizer.from_pretrained")
|
||||
def test_meta_llama_loads_tokenizer_from_unsloth_mirror(mock_from_pretrained):
|
||||
"""Canonical Meta Llama repos are gated; load their tokenizer/chat
|
||||
template from the audited unrestricted mirror while preserving the
|
||||
canonical name for renderer auto-resolution."""
|
||||
canonical = "meta-llama/Llama-3.2-1B-Instruct"
|
||||
mirror = "unsloth/Llama-3.2-1B-Instruct"
|
||||
mock_from_pretrained.return_value = SimpleNamespace(name_or_path=mirror)
|
||||
|
||||
tok = load_tokenizer(canonical)
|
||||
|
||||
args, kwargs = mock_from_pretrained.call_args
|
||||
assert args == (mirror,)
|
||||
assert kwargs == {"trust_remote_code": False}
|
||||
assert tok.name_or_path == canonical
|
||||
|
||||
|
||||
@patch("transformers.AutoTokenizer.from_pretrained")
|
||||
def test_unknown_path_falls_through_to_no_remote_code(mock_from_pretrained):
|
||||
"""Unknown / fine-tuned model paths — including ``moonshotai/Kimi-K2*``
|
||||
@@ -92,6 +113,33 @@ def test_unknown_path_falls_through_to_no_remote_code(mock_from_pretrained):
|
||||
)
|
||||
|
||||
|
||||
def test_tokenizer_source_overrides_are_exact_llama_mirrors():
|
||||
"""Mirror overrides are intentionally narrow: only verified
|
||||
byte-identical Llama tokenizer/template mirrors should live here."""
|
||||
assert TOKENIZER_SOURCE_OVERRIDES == {
|
||||
"meta-llama/Llama-3.2-1B-Instruct": "unsloth/Llama-3.2-1B-Instruct",
|
||||
"meta-llama/Llama-3.2-3B-Instruct": "unsloth/Llama-3.2-3B-Instruct",
|
||||
}
|
||||
|
||||
|
||||
def test_get_offset_tokenizer_rejects_offsetless_byo():
|
||||
"""BYO tokenizers without ``return_offsets_mapping`` support raise a
|
||||
clear error. Hand-coded renderers concatenate scaffold + body in one
|
||||
BPE pass and attribute tokens via the fast tokenizer's offset map;
|
||||
no transparent reload-from-name_or_path fallback exists. The
|
||||
contract is: pass a fast tokenizer or get a loud error at construct
|
||||
time, not silent BPE drift at the wrap/body boundary."""
|
||||
|
||||
class _NoOffsets:
|
||||
name_or_path = "anywhere/anything"
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
raise NotImplementedError("BYO tokenizer has no offsets")
|
||||
|
||||
with pytest.raises(RuntimeError, match="fast tokenizer.*offsets"):
|
||||
base._get_offset_tokenizer(_NoOffsets())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Smoke: real tokenizer loads behave as expected
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
"""Coverage for the fastokens fast-path in ``renderers.base.load_tokenizer``.
|
||||
|
||||
``load_tokenizer`` defaults to routing every supported model through
|
||||
``fastokens.patch_transformers()`` for ~10x faster encode. Models in
|
||||
``FASTOKENS_INCOMPATIBLE`` skip the patch (DeepSeek's Metaspace
|
||||
pretokenizer isn't supported; MiniMax tokenizers diverge on literal
|
||||
special-token text). Callers can opt out per-call with
|
||||
``use_fastokens=False``.
|
||||
|
||||
These tests pin the policy:
|
||||
|
||||
1. The denylist contains the empirically-verified incompat models —
|
||||
adding to it should be a deliberate review action.
|
||||
2. With ``use_fastokens=True`` (the default) on a compatible model, the
|
||||
resulting tokenizer's backend is the fastokens shim. Encode output
|
||||
stays byte-identical to vanilla.
|
||||
3. With ``use_fastokens=False``, the resulting tokenizer is vanilla.
|
||||
4. For incompat models, the fast path is silently skipped and the
|
||||
tokenizer still loads + encodes correctly.
|
||||
5. The fastokens patch is removed immediately after the load so it
|
||||
doesn't leak into the caller's process — subsequent
|
||||
``AutoTokenizer.from_pretrained`` calls outside ``load_tokenizer``
|
||||
use vanilla.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from renderers.base import (
|
||||
FASTOKENS_INCOMPATIBLE,
|
||||
load_tokenizer,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Denylist shape
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_fastokens_incompatible_is_explicit_set():
|
||||
"""The denylist is small and audited — pinning the exact contents
|
||||
catches accidental drift. Adding/removing entries should be a
|
||||
deliberate action with a parity probe."""
|
||||
assert FASTOKENS_INCOMPATIBLE == frozenset(
|
||||
{
|
||||
"deepseek-ai/DeepSeek-V3",
|
||||
"deepseek-ai/DeepSeek-V3-Base",
|
||||
"MiniMaxAI/MiniMax-M2",
|
||||
"MiniMaxAI/MiniMax-M2.5",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fast path (compatible model — Qwen3.5-9B as representative)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
_FAST_MODEL = "Qwen/Qwen3.5-9B"
|
||||
|
||||
|
||||
def _backend_class_name(tok) -> str:
|
||||
"""Return the class name of the underlying backend object so tests
|
||||
can tell vanilla from fastokens-shimmed tokenizers."""
|
||||
backend = getattr(tok, "_tokenizer", None)
|
||||
return type(backend).__name__ if backend is not None else type(tok).__name__
|
||||
|
||||
|
||||
def test_default_uses_fastokens_on_compatible_model():
|
||||
tok = load_tokenizer(_FAST_MODEL)
|
||||
# The shim type is named ``_TokenizerShim`` (see fastokens._compat);
|
||||
# match by name so we don't import private fastokens internals.
|
||||
assert "Shim" in _backend_class_name(tok), (
|
||||
f"Expected fastokens shim backend, got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_explicit_off_returns_vanilla_backend():
|
||||
tok = load_tokenizer(_FAST_MODEL, use_fastokens=False)
|
||||
assert "Shim" not in _backend_class_name(tok), (
|
||||
f"Expected vanilla backend, got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_fast_and_vanilla_encode_identically_on_compatible_model():
|
||||
fast = load_tokenizer(_FAST_MODEL)
|
||||
vanilla = load_tokenizer(_FAST_MODEL, use_fastokens=False)
|
||||
samples = [
|
||||
"Hello, world!",
|
||||
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
|
||||
"🌍 emoji + 中文 + tabs\there",
|
||||
" ".join([f"word_{i}" for i in range(50)]),
|
||||
]
|
||||
for s in samples:
|
||||
assert fast.encode(s, add_special_tokens=False) == vanilla.encode(
|
||||
s, add_special_tokens=False
|
||||
), f"encode diverged on {s!r}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Denylist: incompat models silently skip the patch and still load.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", sorted(FASTOKENS_INCOMPATIBLE))
|
||||
def test_incompat_model_loads_via_vanilla_backend(model):
|
||||
"""For models we know diverge / fail under fastokens, the fast path
|
||||
must be skipped so the load still succeeds with a vanilla backend."""
|
||||
if "DeepSeek" in model or "MiniMax" in model:
|
||||
# Skip if upstream gating / size makes the load impractical here.
|
||||
# We only care that the path doesn't try fastokens. Probe the
|
||||
# tokenizer_config to make sure the repo is reachable; if not,
|
||||
# skip rather than fail (CI without HF auth, network issues).
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
try:
|
||||
HfApi().repo_info(model)
|
||||
except Exception as e:
|
||||
pytest.skip(f"{model}: repo unreachable in this env ({e})")
|
||||
tok = load_tokenizer(model)
|
||||
assert "Shim" not in _backend_class_name(tok), (
|
||||
f"{model}: should NOT have been patched; got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
# And it still encodes.
|
||||
ids = tok.encode("hello", add_special_tokens=False)
|
||||
assert len(ids) > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Patch must not leak: AutoTokenizer.from_pretrained calls OUTSIDE
|
||||
# load_tokenizer should still produce a vanilla tokenizer.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_patch_is_unloaded_after_call():
|
||||
"""``load_tokenizer`` brackets the fastokens patch. After it returns
|
||||
a fastokens-shimmed tokenizer, a fresh ``AutoTokenizer.from_pretrained``
|
||||
call must NOT pick up the patch — the user's process stays clean."""
|
||||
fast = load_tokenizer(_FAST_MODEL)
|
||||
assert "Shim" in _backend_class_name(fast), "preconditions: fast path active"
|
||||
|
||||
# Now call AutoTokenizer.from_pretrained directly. It MUST be vanilla.
|
||||
direct = AutoTokenizer.from_pretrained(_FAST_MODEL, trust_remote_code=False)
|
||||
assert "Shim" not in _backend_class_name(direct), (
|
||||
f"fastokens patch leaked into user-side AutoTokenizer call: "
|
||||
f"got {_backend_class_name(direct)!r}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Failure-mode fallback: if fastokens raises during the patched load,
|
||||
# load_tokenizer falls back to vanilla without surfacing the error.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_fallback_on_fastokens_load_error(monkeypatch):
|
||||
"""Simulate fastokens raising during patched load — load_tokenizer
|
||||
should fall back to vanilla and return a working tokenizer."""
|
||||
import renderers.base as rb
|
||||
|
||||
def _boom(*args, **kwargs):
|
||||
raise ValueError("simulated fastokens failure: unsupported pre-tokenizer")
|
||||
|
||||
monkeypatch.setattr(rb, "_patched_load", _boom)
|
||||
|
||||
tok = load_tokenizer(_FAST_MODEL) # default use_fastokens=True
|
||||
# The vanilla fallback ran — backend is not a fastokens shim.
|
||||
assert "Shim" not in _backend_class_name(tok)
|
||||
# Still works.
|
||||
assert len(tok.encode("hi", add_special_tokens=False)) > 0
|
||||
@@ -99,7 +99,7 @@ def test_kimi_k2_unknown_role_message_indices():
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer("moonshotai/Kimi-K2-Instruct")
|
||||
renderer = create_renderer(tok, renderer="auto")
|
||||
renderer = create_renderer(tok)
|
||||
|
||||
msgs = [
|
||||
{"role": "user", "content": "hi"},
|
||||
|
||||
@@ -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}"
|
||||
)
|
||||
+259
-9
@@ -33,7 +33,20 @@ from renderers import (
|
||||
Qwen3VLRenderer,
|
||||
create_renderer,
|
||||
)
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
|
||||
def _config_for_model(model_name: str, **kwargs):
|
||||
renderer_name = MODEL_RENDERER_MAP[model_name]
|
||||
return _config_class_for(renderer_name)(**kwargs)
|
||||
|
||||
|
||||
def _config_with_add_vision_id(model_name: str, add_vision_id: bool):
|
||||
"""Build the typed config for ``model_name`` (resolved via
|
||||
``MODEL_RENDERER_MAP``) with ``add_vision_id`` set. The qwen_vl
|
||||
family — Qwen3.5 and Qwen3-VL — both expose this field."""
|
||||
return _config_for_model(model_name, add_vision_id=add_vision_id)
|
||||
|
||||
|
||||
pytest.importorskip("PIL", reason="Pillow required for multimodal tests")
|
||||
@@ -111,7 +124,7 @@ def _load_processor_and_renderer(model_name: str):
|
||||
)
|
||||
else:
|
||||
processor = AutoProcessor.from_pretrained(model_name)
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
# Inject processor so the renderer doesn't try to fetch it lazily.
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
@@ -520,10 +533,9 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
|
||||
):
|
||||
"""Bridge-to-next-turn invariants for the multimodal case.
|
||||
|
||||
Asserts three properties that should hold for every renderer
|
||||
regardless of thinking-mode quirks (the prior bridge-vs-full
|
||||
invariant was too strong — see commit log for the divergence
|
||||
rationale on thinking renderers):
|
||||
The renderer is forced to ``thinking_retention="all"`` so this test
|
||||
isolates multimodal bridge mechanics from thinking-retention policy.
|
||||
Asserts three properties:
|
||||
|
||||
1. **Verbatim prefix**: ``bridged.token_ids`` begins with
|
||||
``previous_prompt_ids + previous_completion_ids``. Whatever the
|
||||
@@ -543,7 +555,13 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
|
||||
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
|
||||
|
||||
kit = _modality_kit(modality, mm_model_name)
|
||||
tokenizer, _, renderer = _load_processor_and_renderer(mm_model_name)
|
||||
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
_config_for_model(mm_model_name, thinking_retention="all"),
|
||||
)
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
|
||||
initial = [
|
||||
{
|
||||
@@ -565,6 +583,12 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
|
||||
]
|
||||
|
||||
initial_rendered = renderer.render(initial, add_generation_prompt=True)
|
||||
prior_mm = initial_rendered.multi_modal_data
|
||||
prior_counts = (
|
||||
len(prior_mm.mm_placeholders.get(modality, [])),
|
||||
len(prior_mm.mm_items.get(modality, [])),
|
||||
len(prior_mm.mm_hashes.get(modality, [])),
|
||||
)
|
||||
# ``previous_completion_ids`` mirrors what a sampler would emit
|
||||
# starting AFTER the prompt's assistant role opener — i.e. the
|
||||
# response text followed by ``<|im_end|>``.
|
||||
@@ -614,6 +638,19 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
|
||||
hashes = bridged_mm.mm_hashes.get(modality, [])
|
||||
assert len(items) == 2 and len(hashes) == 2
|
||||
|
||||
# (2b) The prior turn's sidecar is unchanged — the bridge copies the
|
||||
# per-modality lists, so the carried-forward item doesn't grow the
|
||||
# caller's previous_multi_modal_data in place.
|
||||
assert (
|
||||
(
|
||||
len(prior_mm.mm_placeholders.get(modality, [])),
|
||||
len(prior_mm.mm_items.get(modality, [])),
|
||||
len(prior_mm.mm_hashes.get(modality, [])),
|
||||
)
|
||||
== prior_counts
|
||||
== (1, 1, 1)
|
||||
), f"{mm_model_name} / {modality}: bridge mutated previous_multi_modal_data"
|
||||
|
||||
# (3) Extension contains the new turn's pad run, and its
|
||||
# placeholder offset lands inside the extension region.
|
||||
pad_id = tokenizer.convert_tokens_to_ids(kit["placeholder_token"])
|
||||
@@ -636,7 +673,7 @@ def test_modality_registry_models_route_to_renderer():
|
||||
if not _hf_snapshot_cached(model_name):
|
||||
continue
|
||||
tokenizer = load_tokenizer(model_name)
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
# We expect a hand-coded VL renderer, not the default fallback.
|
||||
assert not type(renderer).__name__.startswith("Default"), (
|
||||
f"{model_name} routed to DefaultRenderer despite being in "
|
||||
@@ -682,6 +719,182 @@ def test_tool_response_image_byte_parity(mm_model_name, modality, tiny_image):
|
||||
)
|
||||
|
||||
|
||||
def _qwen_vl_processor_input_ids_with_kwargs(
|
||||
processor, messages, add_gp, **template_kwargs
|
||||
):
|
||||
"""Variant of ``_qwen_vl_processor_input_ids`` that forwards
|
||||
``template_kwargs`` to ``apply_chat_template`` so the parity oracle
|
||||
can exercise the same typed-config template field the renderer was
|
||||
constructed with (e.g. ``add_vision_id=True``).
|
||||
"""
|
||||
text = processor.apply_chat_template(
|
||||
messages,
|
||||
tokenize=False,
|
||||
add_generation_prompt=add_gp,
|
||||
**template_kwargs,
|
||||
)
|
||||
images = []
|
||||
for msg in messages:
|
||||
content = msg.get("content")
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for item in content:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if (
|
||||
item.get("type") in ("image", "image_url")
|
||||
or "image" in item
|
||||
or "image_url" in item
|
||||
):
|
||||
if "image" in item and not isinstance(item["image"], dict):
|
||||
images.append(item["image"])
|
||||
return processor(images=images, text=text, return_tensors="pt")["input_ids"][
|
||||
0
|
||||
].tolist()
|
||||
|
||||
|
||||
# ``add_vision_id`` is exposed on the Qwen-VL family renderers
|
||||
# (Qwen3.5 / Qwen3.6 / Qwen3-VL) per the chat-template audit. Kimi K2.5
|
||||
# / K2.6's template has no equivalent toggle, so it's intentionally
|
||||
# absent from ``KimiK25RendererConfig`` and skipped here.
|
||||
_ADD_VISION_ID_CASES = [
|
||||
(m, mo) for m, mo in _CASES if mo == "image" and _detect_family(m) == "qwen_vl"
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mm_model_name,modality",
|
||||
_ADD_VISION_ID_CASES,
|
||||
ids=[f"{m}|{mo}" for m, mo in _ADD_VISION_ID_CASES],
|
||||
)
|
||||
@pytest.mark.parametrize("add_vision_id", [True, False])
|
||||
def test_add_vision_id_parity_vs_processor(
|
||||
mm_model_name, modality, add_vision_id, tiny_image
|
||||
):
|
||||
"""Parity for ``add_vision_id`` across image-bearing shapes.
|
||||
|
||||
When True, the renderer must prefix each image / video placeholder
|
||||
with ``Picture N: `` / ``Video N: `` matching the Jinja template's
|
||||
``image_count`` / ``video_count`` namespaces. When False, the
|
||||
prefix is suppressed entirely. Both branches must reproduce
|
||||
``processor.apply_chat_template(messages, add_vision_id=<value>)``
|
||||
token-for-token after image expansion.
|
||||
"""
|
||||
if not _hf_snapshot_cached(mm_model_name):
|
||||
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
|
||||
|
||||
kit = _modality_kit(modality, mm_model_name)
|
||||
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
|
||||
# Build a fresh renderer for the kwarg under test (the shared
|
||||
# fixture has ``add_vision_id=False`` baked in).
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
_config_with_add_vision_id(mm_model_name, add_vision_id),
|
||||
)
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
|
||||
for case in _build_cases(kit["make_part"], tiny_image):
|
||||
messages, add_gp = case.values
|
||||
ours = renderer.render_ids(messages, add_generation_prompt=add_gp)
|
||||
theirs = _qwen_vl_processor_input_ids_with_kwargs(
|
||||
processor, messages, add_gp, add_vision_id=add_vision_id
|
||||
)
|
||||
assert ours == theirs, (
|
||||
f"{mm_model_name} / add_vision_id={add_vision_id} / "
|
||||
f"case={case.id}: renderer diverges from processor.\n"
|
||||
f" ours[:80]={ours[:80]}\n theirs[:80]={theirs[:80]}\n"
|
||||
f" len(ours)={len(ours)} len(theirs)={len(theirs)}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mm_model_name,modality",
|
||||
_ADD_VISION_ID_CASES,
|
||||
ids=[f"{m}|{mo}" for m, mo in _ADD_VISION_ID_CASES],
|
||||
)
|
||||
def test_bridge_refuses_when_add_vision_id_loses_prior_count(
|
||||
mm_model_name, modality, tiny_image
|
||||
):
|
||||
"""When ``add_vision_id=True``, the bridge needs the prior turn's
|
||||
image / video count to keep the ``Picture N:`` numbering correct.
|
||||
The only source of that count for the bridged turn is
|
||||
``previous_multi_modal_data``; raw prior token ids don't carry it
|
||||
back unambiguously (``<|vision_start|>`` is shared between image
|
||||
and video placeholders).
|
||||
|
||||
If a caller omits ``previous_multi_modal_data`` on a conversation
|
||||
that already contains images, naively continuing the bridge would
|
||||
emit ``Picture 1:`` again for the new turn — diverging from
|
||||
``apply_chat_template`` and a full re-render. The bridge must
|
||||
refuse (return None) so the caller falls back to a full re-render.
|
||||
"""
|
||||
if not _hf_snapshot_cached(mm_model_name):
|
||||
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
|
||||
|
||||
kit = _modality_kit(modality, mm_model_name)
|
||||
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
|
||||
# Force bridge-allowed retention so this test isolates add_vision_id
|
||||
# counter state from the user-turn retention gate.
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
_config_for_model(
|
||||
mm_model_name,
|
||||
add_vision_id=True,
|
||||
thinking_retention="all",
|
||||
),
|
||||
)
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
|
||||
initial = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
kit["make_part"](tiny_image),
|
||||
{"type": "text", "text": "Turn one."},
|
||||
],
|
||||
}
|
||||
]
|
||||
new_messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
kit["make_part"](tiny_image),
|
||||
{"type": "text", "text": "Turn two."},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
initial_rendered = renderer.render(initial, add_generation_prompt=True)
|
||||
im_end_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
|
||||
completion_ids = tokenizer.encode("Saw it.", add_special_tokens=False) + [im_end_id]
|
||||
|
||||
# No previous_multi_modal_data → bridge must refuse so the caller
|
||||
# falls back to a full re-render (where the counter restarts from
|
||||
# the full message list and lands on Picture 2: correctly).
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
previous_prompt_ids=initial_rendered.token_ids,
|
||||
previous_completion_ids=completion_ids,
|
||||
new_messages=new_messages,
|
||||
)
|
||||
assert bridged is None, (
|
||||
f"{mm_model_name}: bridge should refuse when add_vision_id=True "
|
||||
"and previous_multi_modal_data is omitted but prior contains images"
|
||||
)
|
||||
|
||||
# With the prior mm_data threaded through, the bridge proceeds.
|
||||
bridged_ok = renderer.bridge_to_next_turn(
|
||||
previous_prompt_ids=initial_rendered.token_ids,
|
||||
previous_completion_ids=completion_ids,
|
||||
new_messages=new_messages,
|
||||
previous_multi_modal_data=initial_rendered.multi_modal_data,
|
||||
)
|
||||
assert bridged_ok is not None, (
|
||||
f"{mm_model_name}: bridge unexpectedly refused even with previous_multi_modal_data"
|
||||
)
|
||||
|
||||
|
||||
def test_qwen3_vl_renderer_exposes_image_modality():
|
||||
"""The flagship multimodal renderer is concretely Qwen3VLRenderer.
|
||||
|
||||
@@ -692,6 +905,43 @@ def test_qwen3_vl_renderer_exposes_image_modality():
|
||||
if not _hf_snapshot_cached(model):
|
||||
pytest.skip(f"{model}: HF snapshot not cached locally")
|
||||
tokenizer = load_tokenizer(model)
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
assert isinstance(renderer, Qwen3VLRenderer)
|
||||
assert "image" in MULTIMODAL_MODELS[model]
|
||||
|
||||
|
||||
def test_is_image_part_treats_type_field_as_authoritative():
|
||||
"""``Dataset.from_list`` unifies the Arrow schema across the elements
|
||||
of a list-typed column. A content list mixing text and image parts
|
||||
round-trips with ``image_url: None`` added to every text part (and
|
||||
``text: None`` added to every image part). The classifier must treat
|
||||
the ``type`` field as authoritative when present — falling back to
|
||||
a key-presence check on ``image_url`` would misclassify the text
|
||||
part and the renderer would later raise on ``_load_pil_image(None)``.
|
||||
"""
|
||||
from renderers.qwen3_vl import _is_image_part, _is_video_part
|
||||
|
||||
# Typed parts classify by their ``type``.
|
||||
assert _is_image_part(
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,XXX"}}
|
||||
)
|
||||
assert _is_image_part({"type": "image", "image": object()})
|
||||
assert _is_video_part(
|
||||
{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,XXX"}}
|
||||
)
|
||||
|
||||
# Schema-unified text parts — typed as text, with a None zombie key
|
||||
# for the sibling modality — must NOT classify as image / video.
|
||||
schema_unified_text = {"type": "text", "text": "hello", "image_url": None}
|
||||
assert not _is_image_part(schema_unified_text)
|
||||
assert not _is_video_part(schema_unified_text)
|
||||
schema_unified_text_with_video = {"type": "text", "text": "hi", "video_url": None}
|
||||
assert not _is_video_part(schema_unified_text_with_video)
|
||||
|
||||
# Untyped fallback only fires when ``type`` is absent, and requires
|
||||
# a truthy value (mere key presence isn't enough).
|
||||
assert _is_image_part({"image_url": {"url": "data:..."}})
|
||||
assert _is_image_part({"image": object()})
|
||||
assert not _is_image_part({"image_url": None})
|
||||
assert not _is_image_part({"image": None})
|
||||
assert not _is_video_part({"video_url": None})
|
||||
|
||||
@@ -0,0 +1,676 @@
|
||||
"""Exhaustive token-for-token parity for the Nemotron-3 renderer.
|
||||
|
||||
The shared barrage in ``test_render_ids.py`` covers the common message
|
||||
shapes against every model. This file pins the Nemotron-3-specific template
|
||||
branches that the shared matrix can't reach — they'd fail on other models or
|
||||
exercise behaviour unique to the Nemotron-3 chat template:
|
||||
|
||||
* reasoning + empty / ``None`` content with and without tool calls (the
|
||||
template trims the assembled ``<think>…</think>{content}`` block and appends
|
||||
exactly one separator — a stray ``\\n`` here is the most common agentic
|
||||
regression);
|
||||
* the historical-thinking truncation boundary, which is ``loop.index0 <
|
||||
last_user_idx`` in **all three** variants (Nano / Super / Ultra) — so an
|
||||
in-flight tool cycle (assistant turns after the last user message) keeps its
|
||||
reasoning by default;
|
||||
* inline ``<think>…</think>`` tags carried in ``content`` rendering verbatim
|
||||
(the template only reformats reasoning supplied via ``reasoning_content``);
|
||||
* verbatim (unstripped) user / system / tool content and ``reasoning_content``;
|
||||
* the ``enable_thinking`` / ``truncate_history_thinking`` template kwargs;
|
||||
* the per-variant reasoning-effort kwargs: ``low_effort`` (Super) and
|
||||
``medium_effort`` (Ultra), each a no-op on the variants that don't define it.
|
||||
|
||||
Every assertion compares ``renderer.render_ids(...)`` to
|
||||
``tokenizer.apply_chat_template(..., tokenize=True)`` — a pass means the
|
||||
renderer is byte-for-byte faithful for that case. Tokenizers are loaded from
|
||||
the local HF cache (offline); no network.
|
||||
|
||||
The variants split across two configs: ``nemotron-3`` (Nano / Super, with
|
||||
``low_effort``) and ``nemotron-3-ultra`` (Ultra, with ``medium_effort``). The
|
||||
helper resolves the right config class per model from ``MODEL_RENDERER_MAP``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
# BF16 / FP8 share a tokenizer; only the BF16 checkpoints are cached for tests.
|
||||
NANO = "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"
|
||||
SUPER = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
|
||||
ULTRA = "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16"
|
||||
MODELS = [NANO, SUPER, ULTRA]
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _tok(model: str):
|
||||
return load_tokenizer(model)
|
||||
|
||||
|
||||
def _config_cls(model: str):
|
||||
"""The typed-config class the model resolves to (``nemotron-3`` for
|
||||
Nano/Super, ``nemotron-3-ultra`` for Ultra)."""
|
||||
return _config_class_for(MODEL_RENDERER_MAP[model])
|
||||
|
||||
|
||||
def _renderer(model: str, **flags):
|
||||
# Build with the model's own variant config so the renderer picks the right
|
||||
# ``</think>`` glue (and only valid kwargs are accepted).
|
||||
return create_renderer(_tok(model), _config_cls(model)(**flags))
|
||||
|
||||
|
||||
def _expected(
|
||||
model: str, messages, *, tools=None, add_generation_prompt=False, **kwargs
|
||||
):
|
||||
out = _tok(model).apply_chat_template(
|
||||
messages,
|
||||
tools=tools,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
**kwargs,
|
||||
)
|
||||
if isinstance(out, str): # some tokenizers return str even with tokenize=True
|
||||
return list(_tok(model).encode(out, add_special_tokens=False))
|
||||
return list(out)
|
||||
|
||||
|
||||
def _assert_parity(
|
||||
model, messages, *, tools=None, add_generation_prompt=False, **template_kwargs
|
||||
):
|
||||
"""Renderer ids == apply_chat_template ids for ``model``.
|
||||
|
||||
``template_kwargs`` (e.g. ``enable_thinking``, ``truncate_history_thinking``)
|
||||
are forwarded to both the renderer config and ``apply_chat_template`` so the
|
||||
two sides stay aligned.
|
||||
"""
|
||||
renderer = _renderer(model, **template_kwargs)
|
||||
got = renderer.render_ids(
|
||||
messages, tools=tools, add_generation_prompt=add_generation_prompt
|
||||
)
|
||||
exp = _expected(
|
||||
model,
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
**template_kwargs,
|
||||
)
|
||||
assert got == exp, (
|
||||
f"{model}: render_ids diverged from apply_chat_template\n"
|
||||
f" exp …{_tok(model).decode(exp[-40:])!r}\n"
|
||||
f" got …{_tok(model).decode(got[-40:])!r}"
|
||||
)
|
||||
|
||||
|
||||
pytestmark = pytest.mark.parametrize("model", MODELS, ids=["nano", "super", "ultra"])
|
||||
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "The city name"}
|
||||
},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
# ── Reasoning + tool calls: the trim / separator boundary ─────────────
|
||||
|
||||
|
||||
def test_reasoning_empty_content_tool_call(model):
|
||||
"""reason → tool call, no prose. Must be ``</think>\\n<tool_call>`` (one
|
||||
newline), not ``</think>\\n\\n<tool_call>``."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "I should call the weather tool.",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_none_content_tool_call(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Call the tool.",
|
||||
"content": None,
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_content_tool_call(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Think first.",
|
||||
"content": "Let me check.",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_empty_content_no_tool_call(model):
|
||||
"""reason → empty answer, no tool call: ``</think>`` glued to ``<|im_end|>``."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{"role": "assistant", "reasoning_content": "thinking", "content": ""},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_multiple_tool_calls_with_reasoning(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris and London?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Two cities — two calls.",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
},
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "London"},
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_tool_call_with_nested_object_args(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "go"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {
|
||||
"city": "Paris",
|
||||
"opts": {"unit": "c", "days": [1, 2]},
|
||||
},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
# ── Historical-thinking truncation boundary (last_user_idx) ───────────
|
||||
|
||||
|
||||
def test_inflight_tool_cycle_keeps_reasoning(model):
|
||||
"""Assistant turns after the last user message (the in-flight tool cycle)
|
||||
keep their reasoning by default — boundary is ``loop.index0 <
|
||||
last_user_idx`` in every variant."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Call the tool first.",
|
||||
"content": "calling",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Now I can answer.",
|
||||
"content": "It is 20 degrees.",
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_history_truncation_drops_older_reasoning(model):
|
||||
"""A reasoning turn before the last user message is collapsed to an empty
|
||||
think block (tool-call branch trims the remainder on Nano/Super)."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Q1"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "reasoning before tool",
|
||||
"content": "calling",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{"role": "assistant", "reasoning_content": "after", "content": "Done."},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{"role": "assistant", "reasoning_content": "final", "content": "A2"},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_two_block_tool_conversation(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "system", "content": "be brief"},
|
||||
{"role": "user", "content": "first"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "R2",
|
||||
"content": "calling.",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "a"}}}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "result-a"},
|
||||
{"role": "assistant", "reasoning_content": "R4", "content": "answer-1"},
|
||||
{"role": "user", "content": "second"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "R6",
|
||||
"content": "calling.",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "b"}}}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "result-b"},
|
||||
{"role": "assistant", "reasoning_content": "R8", "content": "answer-2"},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_plain_multi_turn_reasoning_truncation(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Q1"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "long reasoning one",
|
||||
"content": "A1",
|
||||
},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "long reasoning two",
|
||||
"content": "A2",
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("truncate", [True, False])
|
||||
def test_truncate_history_thinking_kwarg(model, truncate):
|
||||
"""``truncate_history_thinking=False`` keeps reasoning on every past turn."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Q1"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "first reasoning",
|
||||
"content": "A1",
|
||||
},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "second reasoning",
|
||||
"content": "A2",
|
||||
},
|
||||
],
|
||||
truncate_history_thinking=truncate,
|
||||
)
|
||||
|
||||
|
||||
# ── Inline <think> tags carried in content (no reasoning_content field) ─
|
||||
|
||||
|
||||
def test_inline_think_tags_final_turn_verbatim(model):
|
||||
"""Inline ``<think>…</think>`` in the final assistant ``content`` renders
|
||||
verbatim — the renderer must not parse + reformat it."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{"role": "assistant", "content": "<think>secret</think>visible"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_inline_think_tags_history_turn(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "<think>secret reasoning</think>visible answer",
|
||||
},
|
||||
{"role": "user", "content": "again"},
|
||||
{"role": "assistant", "content": "second"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
# ── Verbatim (unstripped) content ─────────────────────────────────────
|
||||
|
||||
|
||||
def test_system_content_whitespace_verbatim(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "system", "content": " padded system "},
|
||||
{"role": "user", "content": "hi"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_user_content_whitespace_verbatim(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": " padded user "},
|
||||
{"role": "assistant", "content": "ok"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_assistant_content_whitespace(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{"role": "assistant", "content": " spaced answer "},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_content_whitespace_verbatim(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": " padded reason ",
|
||||
"content": "answer",
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_tool_content_whitespace_verbatim(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "go"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": " spaced tool result "},
|
||||
{"role": "assistant", "content": "done"},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_system_whitespace_with_tools(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "system", "content": " weather bot "},
|
||||
{"role": "user", "content": "Weather?"},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
# ── Generation prompt / thinking toggle ───────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enable_thinking", [True, False])
|
||||
def test_generation_prompt_thinking_toggle(model, enable_thinking):
|
||||
_assert_parity(
|
||||
model,
|
||||
[{"role": "user", "content": "hi"}],
|
||||
add_generation_prompt=True,
|
||||
enable_thinking=enable_thinking,
|
||||
)
|
||||
|
||||
|
||||
def test_generation_prompt_after_tool_response(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
],
|
||||
tools=TOOLS,
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
|
||||
|
||||
# ── Whole-conversation cycles, no reasoning ───────────────────────────
|
||||
|
||||
|
||||
def test_full_tool_cycle_no_reasoning(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "Let me check.",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20, "condition": "sunny"}'},
|
||||
{"role": "assistant", "content": "It is 20 degrees and sunny."},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_consecutive_tool_responses(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris and London?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
},
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "London"},
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{"role": "tool", "content": '{"temp": 15}'},
|
||||
{"role": "assistant", "content": "Paris: 20, London: 15."},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_no_system_no_tools_injects_empty_system(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Hello!"},
|
||||
{"role": "assistant", "content": "Hi there!"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
# ── Reasoning-effort kwargs (variant-specific) ────────────────────────
|
||||
|
||||
_EFFORT_SHAPES = [
|
||||
# gen-prompt shape: hint rides on the (only) user message.
|
||||
([{"role": "user", "content": "solve it"}], {"add_generation_prompt": True}),
|
||||
# multi-turn: hint must land on the LAST user message, not the first.
|
||||
(
|
||||
[
|
||||
{"role": "user", "content": "first"},
|
||||
{"role": "assistant", "content": "ok"},
|
||||
{"role": "user", "content": "second"},
|
||||
],
|
||||
{"add_generation_prompt": True},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
"shape,extra", _EFFORT_SHAPES, ids=["gen_prompt", "multi_turn"]
|
||||
)
|
||||
def test_low_effort_kwarg(model, flag, shape, extra):
|
||||
"""``low_effort`` appends ``\\n\\n{reasoning effort: low}`` to the last user
|
||||
message on **Super**; it's a no-op on **Nano** (its template never defines
|
||||
it). Ultra's config has no such field, so it's skipped."""
|
||||
if model == ULTRA:
|
||||
pytest.skip("low_effort is a nemotron-3 (Nano/Super) kwarg")
|
||||
_assert_parity(model, shape, low_effort=flag, **extra)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
"shape,extra", _EFFORT_SHAPES, ids=["gen_prompt", "multi_turn"]
|
||||
)
|
||||
def test_medium_effort_kwarg(model, flag, shape, extra):
|
||||
"""``medium_effort`` appends ``\\n\\n{reasoning effort: efficient}`` on
|
||||
**Ultra**. Nano/Super configs have no such field, so they're skipped."""
|
||||
if model != ULTRA:
|
||||
pytest.skip("medium_effort is a nemotron-3-ultra kwarg")
|
||||
_assert_parity(model, shape, medium_effort=flag, **extra)
|
||||
|
||||
|
||||
def test_effort_kwarg_lives_on_the_right_variant(model):
|
||||
"""Each effort kwarg is declared only on the variant whose template defines
|
||||
it — the discriminated union rejects the wrong combination at config load."""
|
||||
fields = _config_cls(model).template_field_names()
|
||||
if model == ULTRA:
|
||||
assert "medium_effort" in fields and "low_effort" not in fields
|
||||
else:
|
||||
assert "low_effort" in fields and "medium_effort" not in fields
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Offline wiring tests for the Nemotron-3 variant split.
|
||||
|
||||
Assert the model→renderer mapping, the per-variant typed-config surface, and
|
||||
the name-based ``low_effort`` gating WITHOUT loading any tokenizer (no
|
||||
network). This pins the wiring the parity matrix can't reach — in particular
|
||||
the FP8 Ultra entry, which no test loads a tokenizer for — so it can't
|
||||
silently rot.
|
||||
|
||||
The two variants:
|
||||
|
||||
* ``nemotron-3`` — Nano / Super, shared template. Config exposes ``low_effort``
|
||||
(honoured on Super, a no-op on Nano).
|
||||
* ``nemotron-3-ultra`` — Ultra, distinct ``</think>`` glue. Config exposes
|
||||
``medium_effort``.
|
||||
|
||||
Both route to the one ``Nemotron3Renderer`` class, which selects the variant
|
||||
from ``config.name``.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from renderers.base import MODEL_RENDERER_MAP, RENDERER_REGISTRY, _populate_registry
|
||||
from renderers.configs import (
|
||||
Nemotron3RendererConfig,
|
||||
Nemotron3UltraRendererConfig,
|
||||
_config_class_for,
|
||||
)
|
||||
from renderers.nemotron3 import Nemotron3Renderer, Nemotron3UltraRenderer, _is_super
|
||||
|
||||
_ULTRA_REPOS = [
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8",
|
||||
]
|
||||
_NANO_SUPER_REPOS = [
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
|
||||
]
|
||||
|
||||
|
||||
def _fake_tok(name):
|
||||
return SimpleNamespace(name_or_path=name)
|
||||
|
||||
|
||||
def test_models_map_to_their_variant():
|
||||
for repo in _ULTRA_REPOS:
|
||||
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3-ultra", repo
|
||||
for repo in _NANO_SUPER_REPOS:
|
||||
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3", repo
|
||||
|
||||
|
||||
def test_each_discriminator_maps_to_its_config_and_renderer_class():
|
||||
# Config discriminator → config class.
|
||||
assert _config_class_for("nemotron-3") is Nemotron3RendererConfig
|
||||
assert _config_class_for("nemotron-3-ultra") is Nemotron3UltraRendererConfig
|
||||
# Registry → renderer class (Ultra is a sibling subclass, matching the
|
||||
# GLM-5/5.1 and Qwen3.5/3.6 house style — not one class under two names).
|
||||
_populate_registry()
|
||||
assert RENDERER_REGISTRY["nemotron-3"] is Nemotron3Renderer
|
||||
assert RENDERER_REGISTRY["nemotron-3-ultra"] is Nemotron3UltraRenderer
|
||||
assert issubclass(Nemotron3UltraRenderer, Nemotron3Renderer)
|
||||
|
||||
|
||||
def test_variant_is_encoded_by_the_class():
|
||||
# The ``</think>`` glue is selected by the class hook, not config.name —
|
||||
# so the right renderer class must be constructed (create_renderer routes
|
||||
# config.name → class). Default config also follows the class.
|
||||
assert Nemotron3Renderer._ultra is False
|
||||
assert Nemotron3UltraRenderer._ultra is True
|
||||
assert Nemotron3Renderer._config_cls is Nemotron3RendererConfig
|
||||
assert Nemotron3UltraRenderer._config_cls is Nemotron3UltraRendererConfig
|
||||
|
||||
|
||||
def test_template_fields_per_variant():
|
||||
# ``low_effort`` lives only on the Nano/Super config; ``medium_effort``
|
||||
# only on Ultra. Both ARE chat-template kwargs (unlike the removed ``ultra``
|
||||
# selector), so they appear in the template-field surface.
|
||||
assert Nemotron3RendererConfig.template_field_names() == frozenset(
|
||||
{"enable_thinking", "truncate_history_thinking", "low_effort"}
|
||||
)
|
||||
assert Nemotron3UltraRendererConfig.template_field_names() == frozenset(
|
||||
{"enable_thinking", "truncate_history_thinking", "medium_effort"}
|
||||
)
|
||||
|
||||
|
||||
def test_configs_reject_the_other_variants_effort_kwarg():
|
||||
# Discriminated-union honesty: a bad combination fails at config-load.
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
Nemotron3RendererConfig(medium_effort=True) # type: ignore[call-arg]
|
||||
with pytest.raises(ValidationError):
|
||||
Nemotron3UltraRendererConfig(low_effort=True) # type: ignore[call-arg]
|
||||
# And the removed ``ultra`` selector is gone entirely.
|
||||
with pytest.raises(ValidationError):
|
||||
Nemotron3RendererConfig(ultra=True) # type: ignore[call-arg]
|
||||
|
||||
|
||||
def test_is_super_name_detection():
|
||||
assert _is_super(_fake_tok("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"))
|
||||
assert not _is_super(_fake_tok("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"))
|
||||
# Unknown / local-path checkpoints default to False → low_effort no-op.
|
||||
assert not _is_super(_fake_tok("/home/user/local-ckpt"))
|
||||
assert not _is_super(SimpleNamespace()) # no name_or_path attr
|
||||
@@ -13,7 +13,7 @@ from renderers.base import ToolCallParseStatus, load_tokenizer
|
||||
@lru_cache
|
||||
def _qwen3_vl():
|
||||
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
@@ -98,10 +98,73 @@ def test_qwen3_vl_malformed_tool_call_surfaces_as_invalid_json():
|
||||
assert tc.token_span is not None
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _qwen3():
|
||||
tokenizer = load_tokenizer("Qwen/Qwen3-0.6B")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
def test_qwen3_in_think_tool_call_is_not_a_real_call():
|
||||
"""A ``<tool_call>`` the model drafts *inside* its ``<think>`` trace must
|
||||
stay reasoning — only the call emitted after ``</think>`` counts.
|
||||
|
||||
Regression for #78: Thinking models (e.g. Qwen3-*-Thinking-2507) draft
|
||||
tool-call syntax while planning. Because ``<tool_call>`` is a real vocab
|
||||
token, the parser used to scan the whole stream and emit the in-think
|
||||
draft *and* the genuine post-``</think>`` call as two tool calls — a
|
||||
phantom duplicate that made callers execute the same code twice. The scan
|
||||
is now anchored after ``</think>``, mirroring vLLM's reasoning-then-tools
|
||||
ordering.
|
||||
"""
|
||||
tokenizer, renderer = _qwen3()
|
||||
text = (
|
||||
"<think>\nLet me draft the call:\n"
|
||||
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
|
||||
"</tool_call>\nYes, that looks right.\n</think>\n"
|
||||
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
|
||||
"</tool_call>"
|
||||
)
|
||||
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
|
||||
|
||||
assert len(parsed.tool_calls) == 1
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.status == ToolCallParseStatus.OK
|
||||
assert tc.name == "execute_code"
|
||||
assert tc.arguments == {"code": "print(1)"}
|
||||
# The drafted call stays in the reasoning trace, not content.
|
||||
assert parsed.reasoning_content is not None
|
||||
assert "<tool_call>" in parsed.reasoning_content
|
||||
assert parsed.content == ""
|
||||
|
||||
|
||||
def test_qwen3_distinct_parallel_calls_after_think_are_preserved():
|
||||
"""The fix must not over-correct: two *genuine* parallel calls emitted
|
||||
after ``</think>`` are still both returned (no dedup), preserving the
|
||||
faithful-transcription contract for real invocations.
|
||||
"""
|
||||
tokenizer, renderer = _qwen3()
|
||||
text = (
|
||||
"<think>\nplan\n</think>\n"
|
||||
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
|
||||
"</tool_call>\n"
|
||||
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(2)"}}\n'
|
||||
"</tool_call>"
|
||||
)
|
||||
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
|
||||
|
||||
assert len(parsed.tool_calls) == 2
|
||||
assert [tc.arguments for tc in parsed.tool_calls] == [
|
||||
{"code": "print(1)"},
|
||||
{"code": "print(2)"},
|
||||
]
|
||||
assert parsed.reasoning_content == "plan"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _kimi_k25():
|
||||
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
@@ -135,3 +198,79 @@ def test_kimi_k25_tool_call_carries_token_span():
|
||||
assert 0 <= start < end <= len(token_ids), (
|
||||
f"span {tc.token_span} out of range for {len(token_ids)} input tokens"
|
||||
)
|
||||
|
||||
|
||||
def test_kimi_k25_in_think_section_is_not_a_real_call():
|
||||
"""A tool-call section the model drafts inside its ``<think>`` trace must
|
||||
not be parsed — only the section after ``</think>`` counts.
|
||||
|
||||
Regression for #78. K2.5's failure mode differed from Qwen3's: the
|
||||
in-think section tripped the "truncated reasoning" guard and the parser
|
||||
*dropped every tool call* (returned zero), losing the genuine call. The
|
||||
scan is now anchored past ``</think>``.
|
||||
"""
|
||||
tokenizer, renderer = _kimi_k25()
|
||||
section = (
|
||||
"<|tool_calls_section_begin|>"
|
||||
"<|tool_call_begin|>functions.execute_code:0"
|
||||
'<|tool_call_argument_begin|>{"code": "print(1)"}'
|
||||
"<|tool_call_end|><|tool_calls_section_end|>"
|
||||
)
|
||||
text = f"<think>\nLet me draft:\n{section}\nlooks right.\n</think>\nGo.\n{section}"
|
||||
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
|
||||
|
||||
assert len(parsed.tool_calls) == 1
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.status == ToolCallParseStatus.OK
|
||||
assert tc.name == "execute_code"
|
||||
assert tc.arguments == {"code": "print(1)"}
|
||||
# The drafted section stays in the reasoning trace.
|
||||
assert parsed.reasoning_content is not None
|
||||
assert "<|tool_calls_section_begin|>" in parsed.reasoning_content
|
||||
assert parsed.content == "Go."
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _deepseek_v3():
|
||||
tokenizer = load_tokenizer("deepseek-ai/DeepSeek-V3")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
def test_deepseek_v3_in_think_section_is_not_a_real_call():
|
||||
"""A tool-call section drafted inside ``<think>`` must not be parsed —
|
||||
only the section after ``</think>`` counts.
|
||||
|
||||
Regression for #78. DeepSeek-V3's failure mode: it returned the *wrong*
|
||||
call (the in-think draft) and lost reasoning, because ``</think>`` is
|
||||
multi-token text there and the scan wasn't anchored past it.
|
||||
"""
|
||||
tokenizer, renderer = _deepseek_v3()
|
||||
|
||||
def section(name: str) -> str:
|
||||
return (
|
||||
"<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>"
|
||||
f'{name}\n```json\n{{"code": "print(1)"}}\n```'
|
||||
"<|tool▁call▁end|><|tool▁calls▁end|>"
|
||||
)
|
||||
|
||||
text = (
|
||||
f"<think>\nLet me draft:\n{section('draft_tool')}\nlooks right.\n</think>\n"
|
||||
f"Go.\n{section('real_tool')}"
|
||||
)
|
||||
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
|
||||
|
||||
assert len(parsed.tool_calls) == 1
|
||||
tc = parsed.tool_calls[0]
|
||||
# Assert the *post-``</think>``* section was chosen, not the in-think draft.
|
||||
# (Use ``startswith`` rather than ``== "real_tool"``: under transformers
|
||||
# 5.x the DeepSeek tokenizer's decode drops the ``\n`` between name and the
|
||||
# ```json fence, so ``_parse_deepseek_tool_calls`` folds the fence into the
|
||||
# name — a pre-existing, #78-unrelated quirk. What matters here is *which*
|
||||
# section won.)
|
||||
assert tc.name is not None and tc.name.startswith("real_tool")
|
||||
assert "draft_tool" not in tc.name
|
||||
# The drafted section stays in the reasoning trace, not content.
|
||||
assert parsed.reasoning_content is not None
|
||||
assert "draft_tool" in parsed.reasoning_content
|
||||
assert parsed.content == "Go."
|
||||
|
||||
@@ -133,8 +133,7 @@ def test_tool_calls_is_list_of_parsed_tool_call(model_name, tokenizer, renderer)
|
||||
|
||||
Empty list = "model did not emit any tool calls". A list with non-OK
|
||||
entries = "model tried and the parser caught the failure"; those are
|
||||
deliberately preserved so verifier / RL-loss code can see them. This
|
||||
replaces the older list-or-None convention.
|
||||
deliberately preserved so verifier / RL-loss code can see them.
|
||||
"""
|
||||
text = "Hello!"
|
||||
ids = tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
@@ -114,11 +114,12 @@ def test_think_reasoning_parser_no_block():
|
||||
|
||||
def test_default_renderer_uses_parsers():
|
||||
"""DefaultRenderer + parsers should extract tool calls and reasoning."""
|
||||
from renderers import create_renderer
|
||||
from renderers import DefaultRendererConfig, create_renderer
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen3-0.6B")
|
||||
renderer = create_renderer(
|
||||
tok, renderer="default", tool_parser="qwen3", reasoning_parser="think"
|
||||
tok,
|
||||
DefaultRendererConfig(tool_parser="qwen3", reasoning_parser="think"),
|
||||
)
|
||||
assert renderer.supports_tools is True
|
||||
|
||||
@@ -134,10 +135,10 @@ def test_default_renderer_uses_parsers():
|
||||
|
||||
def test_default_renderer_without_parsers_is_backward_compatible():
|
||||
"""Without parsers, DefaultRenderer still does basic <think> extraction."""
|
||||
from renderers import create_renderer
|
||||
from renderers import DefaultRendererConfig, create_renderer
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen3-0.6B")
|
||||
renderer = create_renderer(tok, renderer="default")
|
||||
renderer = create_renderer(tok, DefaultRendererConfig())
|
||||
assert renderer.supports_tools is False
|
||||
|
||||
ids = tok.encode("<think>r</think>a", add_special_tokens=False)
|
||||
|
||||
+60
-423
@@ -1,22 +1,9 @@
|
||||
"""Smoke coverage for the ``preserve_*_thinking`` override flags.
|
||||
"""Targeted coverage for the ``thinking_retention`` bridge-policy flag.
|
||||
|
||||
Flags are constructor-only (``create_renderer(..., preserve_all_thinking=True)``)
|
||||
and stored as instance attributes — there is no call-site ``render`` /
|
||||
``render_ids`` override. Each test that wants a non-default flag builds
|
||||
a fresh renderer for that configuration via ``_make`` below.
|
||||
|
||||
Two invariants per renderer:
|
||||
|
||||
1. Default render (no flags) is byte-identical to the existing
|
||||
``apply_chat_template`` parity baseline — covered exhaustively elsewhere.
|
||||
2. Setting either flag never *removes* tokens compared to the default and,
|
||||
for renderers whose template would drop past-asst thinking, actually
|
||||
adds tokens for a conversation containing past-asst ``reasoning_content``.
|
||||
|
||||
Renderers whose template either always preserves thinking (DeepSeek-V3) or
|
||||
never references ``reasoning_content`` for past-asst (Kimi-K2, Qwen3-VL)
|
||||
are no-ops by design — they're listed below and the test asserts the
|
||||
default==override equality instead of strict growth.
|
||||
Generic ``thinking_retention`` controls whether a renderer may append via
|
||||
``bridge_to_next_turn`` or should fall back to a full re-render. It is not a
|
||||
chat-template kwarg, so the only full-render contract here is that explicit
|
||||
generic values do not change render output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,26 +11,8 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import should_preserve_past_thinking
|
||||
|
||||
|
||||
def _make(tokenizer, renderer_name, **flags):
|
||||
"""Build a fresh renderer with the given preserve_*_thinking flags
|
||||
bound at construction. Reuses the cached tokenizer fixture."""
|
||||
return create_renderer(tokenizer, renderer=renderer_name, **flags)
|
||||
|
||||
|
||||
# Renderers whose template doesn't drop past-asst thinking or has no
|
||||
# place to re-emit it. For these, override flags MUST be no-ops.
|
||||
NO_OP_MODELS = {
|
||||
"deepseek-ai/DeepSeek-V3",
|
||||
"deepseek-ai/DeepSeek-V3-Base",
|
||||
"moonshotai/Kimi-K2-Instruct",
|
||||
"Qwen/Qwen3-VL-4B-Instruct",
|
||||
"Qwen/Qwen3-VL-8B-Instruct",
|
||||
"Qwen/Qwen3-VL-30B-A3B-Instruct",
|
||||
"poolside/Laguna-XS.2",
|
||||
}
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
|
||||
CONVERSATION = [
|
||||
@@ -66,395 +35,63 @@ CONVERSATION = [
|
||||
]
|
||||
|
||||
|
||||
def test_should_preserve_past_thinking_classification():
|
||||
# CURRENT-block-only behaviour. between_tool_calls preserves thinking
|
||||
# ONLY for asst messages that sit AFTER the last user turn AND are in
|
||||
# a segment that contains a tool. Anything before the last user turn
|
||||
# falls back to template default (typically dropped).
|
||||
|
||||
# Live tool cycle: U-A_tc-T-A_final, no trailing user. The whole
|
||||
# post-user segment contains a tool, so both A's are preserved.
|
||||
live_cycle = [
|
||||
{"role": "user", "content": "q"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "r1",
|
||||
"tool_calls": [{"function": {"name": "f", "arguments": {}}}],
|
||||
},
|
||||
{"role": "tool", "name": "f", "content": "data"},
|
||||
{"role": "assistant", "reasoning_content": "r2", "content": "answer"},
|
||||
]
|
||||
assert should_preserve_past_thinking(
|
||||
live_cycle,
|
||||
1,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
assert should_preserve_past_thinking(
|
||||
live_cycle,
|
||||
3,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
|
||||
# Same shape with a NEW user appended → now the prior tool block is
|
||||
# "older" and between_tool_calls must drop its thinking (template
|
||||
# default). Only preserve_all_thinking would keep them.
|
||||
closed_cycle = live_cycle + [{"role": "user", "content": "next"}]
|
||||
assert not should_preserve_past_thinking(
|
||||
closed_cycle,
|
||||
1,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
assert not should_preserve_past_thinking(
|
||||
closed_cycle,
|
||||
3,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
# preserve_all_thinking still keeps them.
|
||||
assert should_preserve_past_thinking(
|
||||
closed_cycle,
|
||||
1,
|
||||
preserve_all_thinking=True,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
)
|
||||
assert should_preserve_past_thinking(
|
||||
closed_cycle,
|
||||
3,
|
||||
preserve_all_thinking=True,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
)
|
||||
|
||||
# Current segment without a tool → not a tool cycle → not preserved.
|
||||
no_tool_yet = [
|
||||
{"role": "user", "content": "q"},
|
||||
{"role": "assistant", "reasoning_content": "r", "content": "a"},
|
||||
]
|
||||
assert not should_preserve_past_thinking(
|
||||
no_tool_yet,
|
||||
1,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
|
||||
# Both flags False → always False.
|
||||
assert not should_preserve_past_thinking(
|
||||
live_cycle,
|
||||
1,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
)
|
||||
def _make(tokenizer, renderer_name, **flags):
|
||||
"""Build a fresh renderer with the given construction-time flags."""
|
||||
if renderer_name == "auto":
|
||||
renderer_name = MODEL_RENDERER_MAP.get(
|
||||
getattr(tokenizer, "name_or_path", ""), "default"
|
||||
)
|
||||
config = _config_class_for(renderer_name)(**flags)
|
||||
return create_renderer(tokenizer, config)
|
||||
|
||||
|
||||
def test_preserve_flags_default_unchanged(
|
||||
def test_generic_thinking_retention_does_not_change_full_render(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
# A renderer constructed with both flags explicitly ``False`` must
|
||||
# produce byte-identical output to one constructed with the defaults.
|
||||
bare = renderer.render_ids(CONVERSATION)
|
||||
explicit_off = _make(
|
||||
"""Generic retention is bridge policy only, not a render override."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on explicit retention — covered separately")
|
||||
|
||||
default = renderer.render_ids(CONVERSATION)
|
||||
for retention in ("tool_cycle", "all"):
|
||||
explicit = _make(
|
||||
tokenizer,
|
||||
renderer_name,
|
||||
thinking_retention=retention,
|
||||
).render_ids(CONVERSATION)
|
||||
assert explicit == default, (
|
||||
f"{model_name}: thinking_retention={retention!r} changed full render"
|
||||
)
|
||||
|
||||
|
||||
def test_no_thinking_knob_implies_all_bridge_policy(
|
||||
model_name, renderer_name, tokenizer
|
||||
):
|
||||
"""No-thinking generation config means there is no thinking to evict."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
bare = _make(tokenizer, renderer_name)
|
||||
if isinstance(bare, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer has no typed no-thinking bridge policy")
|
||||
|
||||
cfg_cls = _config_class_for(renderer_name)
|
||||
template_fields = cfg_cls.template_field_names()
|
||||
if "enable_thinking" in template_fields:
|
||||
no_thinking = {"enable_thinking": False}
|
||||
elif "thinking" in template_fields:
|
||||
no_thinking = {"thinking": False}
|
||||
else:
|
||||
pytest.skip(f"{model_name}: no no-thinking generation knob")
|
||||
|
||||
all_on = _make(tokenizer, renderer_name, **no_thinking)
|
||||
assert all_on.effective_thinking_retention == "all"
|
||||
|
||||
conservative = _make(
|
||||
tokenizer,
|
||||
renderer_name,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
).render_ids(CONVERSATION)
|
||||
assert bare == explicit_off, (
|
||||
f"{model_name}: explicit flags=False must equal bare default render"
|
||||
**no_thinking,
|
||||
thinking_retention="tool_cycle",
|
||||
)
|
||||
|
||||
|
||||
def test_preserve_all_thinking_grows_or_no_op(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
default = renderer.render_ids(CONVERSATION)
|
||||
preserved = _make(tokenizer, renderer_name, preserve_all_thinking=True).render_ids(
|
||||
CONVERSATION
|
||||
)
|
||||
|
||||
if model_name in NO_OP_MODELS:
|
||||
assert preserved == default, (
|
||||
f"{model_name} is a no-op renderer; preserve_all_thinking must "
|
||||
f"not change output (got {len(default)} → {len(preserved)})"
|
||||
)
|
||||
else:
|
||||
assert len(preserved) > len(default), (
|
||||
f"{model_name}: preserve_all_thinking should add tokens for a "
|
||||
f"conversation with past-asst reasoning_content "
|
||||
f"(default={len(default)}, preserved={len(preserved)})"
|
||||
)
|
||||
|
||||
|
||||
def test_preserve_between_tool_calls_strict_subset(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
"""``preserve_thinking_between_tool_calls`` is strictly weaker than
|
||||
``preserve_all_thinking``: token count satisfies default <= between <= all."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
default = renderer.render_ids(CONVERSATION)
|
||||
between = _make(
|
||||
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
|
||||
).render_ids(CONVERSATION)
|
||||
all_ = _make(tokenizer, renderer_name, preserve_all_thinking=True).render_ids(
|
||||
CONVERSATION
|
||||
)
|
||||
assert len(default) <= len(between) <= len(all_), (
|
||||
f"{model_name}: expected default <= between <= all, "
|
||||
f"got {len(default)} <= {len(between)} <= {len(all_)}"
|
||||
)
|
||||
|
||||
|
||||
LIVE_TOOL_CYCLE = [
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Let me call the tool.",
|
||||
"content": "Calling.",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "name": "get_weather", "content": "Sunny, 22C"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Tool returned weather.",
|
||||
"content": "Sunny.",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_preserve_btc_on_live_cycle_matches_all(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
"""In a live tool cycle (no trailing user), every past-asst sits in
|
||||
the current tool-bearing segment. ``preserve_thinking_between_tool_calls``
|
||||
should preserve all of their thinking — same set of asst messages as
|
||||
``preserve_all_thinking``, so the resulting token sequences must be
|
||||
identical (independent of which template-default condition each
|
||||
renderer uses internally)."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
btc = _make(
|
||||
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
|
||||
).render_ids(LIVE_TOOL_CYCLE)
|
||||
all_ = _make(tokenizer, renderer_name, preserve_all_thinking=True).render_ids(
|
||||
LIVE_TOOL_CYCLE
|
||||
)
|
||||
assert btc == all_, (
|
||||
f"{model_name}: in a live tool cycle btc must match preserve_all "
|
||||
f"(got len(btc)={len(btc)}, len(all)={len(all_)})"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# End-to-end visibility matrix
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Conversation shape: S-U-A-T-A-U-A-T-A. Each assistant carries a unique
|
||||
# sentinel string in ``reasoning_content`` so we can grep the decoded
|
||||
# output to see whose thinking was kept.
|
||||
TWO_BLOCK_TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "lookup",
|
||||
"description": "look up a value",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"key": {"type": "string"}},
|
||||
"required": ["key"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
TWO_BLOCK_CONV = [
|
||||
{"role": "system", "content": "be brief"},
|
||||
{"role": "user", "content": "first"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "REASON-A2",
|
||||
"content": "calling.",
|
||||
"tool_calls": [{"function": {"name": "lookup", "arguments": {"key": "a"}}}],
|
||||
},
|
||||
{"role": "tool", "name": "lookup", "content": "result-a"},
|
||||
{"role": "assistant", "reasoning_content": "REASON-A4", "content": "answer-1"},
|
||||
{"role": "user", "content": "second"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "REASON-A6",
|
||||
"content": "calling.",
|
||||
"tool_calls": [{"function": {"name": "lookup", "arguments": {"key": "b"}}}],
|
||||
},
|
||||
{"role": "tool", "name": "lookup", "content": "result-b"},
|
||||
{"role": "assistant", "reasoning_content": "REASON-A8", "content": "answer-2"},
|
||||
]
|
||||
|
||||
ALL_SENTINELS = ("REASON-A2", "REASON-A4", "REASON-A6", "REASON-A8")
|
||||
CURRENT_BLOCK_SENTINELS = ("REASON-A6", "REASON-A8")
|
||||
OLDER_BLOCK_SENTINELS = ("REASON-A2", "REASON-A4")
|
||||
|
||||
# Renderers whose template renders ``reasoning_content`` for past-asst
|
||||
# under no condition. Flags accepted as no-ops; sentinels never appear.
|
||||
NEVER_PRESERVES_MODELS = {
|
||||
"moonshotai/Kimi-K2-Instruct",
|
||||
"Qwen/Qwen3-VL-4B-Instruct",
|
||||
"Qwen/Qwen3-VL-8B-Instruct",
|
||||
"Qwen/Qwen3-VL-30B-A3B-Instruct",
|
||||
}
|
||||
|
||||
|
||||
def test_preserve_all_thinking_emits_every_asst_reasoning(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
"""``preserve_all_thinking=True`` must surface every past-asst's
|
||||
``reasoning_content`` in the decoded output — for renderers that
|
||||
have any pathway to render reasoning at all."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
|
||||
ids = _make(tokenizer, renderer_name, preserve_all_thinking=True).render_ids(
|
||||
TWO_BLOCK_CONV, tools=TWO_BLOCK_TOOLS
|
||||
)
|
||||
text = tokenizer.decode(ids)
|
||||
|
||||
if model_name in NEVER_PRESERVES_MODELS:
|
||||
for sentinel in ALL_SENTINELS:
|
||||
assert sentinel not in text, (
|
||||
f"{model_name}: never-preserves renderer leaked {sentinel} "
|
||||
f"under preserve_all_thinking"
|
||||
)
|
||||
else:
|
||||
for sentinel in ALL_SENTINELS:
|
||||
assert sentinel in text, (
|
||||
f"{model_name}: preserve_all_thinking did not emit {sentinel} "
|
||||
f"in decoded output"
|
||||
)
|
||||
|
||||
|
||||
def test_preserve_btc_emits_current_block_reasoning(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
"""``preserve_thinking_between_tool_calls=True`` must surface the
|
||||
current (post-last-user) tool block's reasoning. Older blocks fall
|
||||
back to template default, which varies per renderer — no universal
|
||||
assertion there."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
|
||||
ids = _make(
|
||||
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
|
||||
).render_ids(TWO_BLOCK_CONV, tools=TWO_BLOCK_TOOLS)
|
||||
text = tokenizer.decode(ids)
|
||||
|
||||
if model_name in NEVER_PRESERVES_MODELS:
|
||||
for sentinel in ALL_SENTINELS:
|
||||
assert sentinel not in text, (
|
||||
f"{model_name}: never-preserves renderer leaked {sentinel} "
|
||||
f"under preserve_thinking_between_tool_calls"
|
||||
)
|
||||
else:
|
||||
for sentinel in CURRENT_BLOCK_SENTINELS:
|
||||
assert sentinel in text, (
|
||||
f"{model_name}: btc did not emit current-block {sentinel} "
|
||||
f"in decoded output"
|
||||
)
|
||||
|
||||
|
||||
def test_default_renderer_raises_on_flags():
|
||||
"""``DefaultRenderer`` falls back to apply_chat_template with no
|
||||
selective re-emit pathway, so constructing one with either flag set
|
||||
must raise — fail fast, before any render is attempted."""
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen2.5-0.5B-Instruct")
|
||||
# No flags → constructs cleanly.
|
||||
create_renderer(tok, renderer="default")
|
||||
# Either flag set → raises at construction.
|
||||
with pytest.raises(NotImplementedError):
|
||||
create_renderer(tok, renderer="default", preserve_all_thinking=True)
|
||||
with pytest.raises(NotImplementedError):
|
||||
create_renderer(
|
||||
tok, renderer="default", preserve_thinking_between_tool_calls=True
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Construction-time configuration is discoverable via instance attributes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_create_renderer_records_flag_state(model_name, renderer_name, tokenizer):
|
||||
"""Each renderer exposes the bound flag state via ``_preserve_*``
|
||||
attributes — useful for downstream code (pool cache keys, logging,
|
||||
test assertions) that needs to confirm what was constructed."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
bare = create_renderer(tokenizer, renderer=renderer_name)
|
||||
assert bare._preserve_all_thinking is False
|
||||
assert bare._preserve_thinking_between_tool_calls is False
|
||||
|
||||
if not isinstance(bare, DefaultRenderer):
|
||||
# DefaultRenderer raises at construction with either flag set —
|
||||
# covered by ``test_default_renderer_raises_on_flags``.
|
||||
all_on = create_renderer(
|
||||
tokenizer, renderer=renderer_name, preserve_all_thinking=True
|
||||
)
|
||||
assert all_on._preserve_all_thinking is True
|
||||
assert all_on._preserve_thinking_between_tool_calls is False
|
||||
|
||||
btc_on = create_renderer(
|
||||
tokenizer,
|
||||
renderer=renderer_name,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
assert btc_on._preserve_all_thinking is False
|
||||
assert btc_on._preserve_thinking_between_tool_calls is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Regression: legacy chat-template-kwarg pass-throughs are gone
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_glm5_constructor_rejects_clear_thinking():
|
||||
"""``clear_thinking`` was a chat-template-kwarg pass-through. It is
|
||||
superseded by the renderer-agnostic ``preserve_all_thinking`` override
|
||||
and must no longer be accepted by the constructor — its default-True
|
||||
semantics are now baked into the render gate."""
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.glm5 import GLM5Renderer
|
||||
|
||||
tok = load_tokenizer("zai-org/GLM-5")
|
||||
with pytest.raises(TypeError):
|
||||
GLM5Renderer(tok, clear_thinking=True) # type: ignore[call-arg]
|
||||
with pytest.raises(TypeError):
|
||||
GLM5Renderer(tok, clear_thinking=False) # type: ignore[call-arg]
|
||||
|
||||
|
||||
def test_qwen36_constructor_rejects_preserve_thinking():
|
||||
"""``preserve_thinking`` on Qwen3.6 was a chat-template-kwarg
|
||||
pass-through. It is superseded by the renderer-agnostic
|
||||
``preserve_all_thinking`` override and must no longer be accepted by
|
||||
the constructor — its default-False semantics are now inherited from
|
||||
Qwen3.5's render gate."""
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.qwen36 import Qwen36Renderer
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen3.6-35B-A3B")
|
||||
with pytest.raises(TypeError):
|
||||
Qwen36Renderer(tok, preserve_thinking=True) # type: ignore[call-arg]
|
||||
assert conservative.effective_thinking_retention == "tool_cycle"
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
MODELS = [
|
||||
"PrimeIntellect/Qwen3-0.6B",
|
||||
"PrimeIntellect/Qwen3-1.7B",
|
||||
]
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {
|
||||
"type": "string",
|
||||
"description": "City name",
|
||||
"default": "Paris",
|
||||
"examples": [{"country": "FR", "city": "Paris"}],
|
||||
},
|
||||
"days": {"type": "integer", "minimum": 1},
|
||||
},
|
||||
"required": ["city"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
"strict": True,
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
CASES = [
|
||||
pytest.param(
|
||||
[{"role": "user", "content": "Hello"}],
|
||||
None,
|
||||
True,
|
||||
id="generation-prompt",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "Reverse abc"},
|
||||
{"role": "assistant", "content": "cba"},
|
||||
],
|
||||
None,
|
||||
False,
|
||||
id="plain-assistant",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": " simple arithmetic ",
|
||||
"content": " 4 ",
|
||||
},
|
||||
],
|
||||
None,
|
||||
False,
|
||||
id="reasoning",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{"role": "assistant", "reasoning_content": "", "content": "4"},
|
||||
],
|
||||
None,
|
||||
False,
|
||||
id="empty-reasoning",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "A"},
|
||||
{"role": "assistant", "content": "<think>raw</think>\nB"},
|
||||
{"role": "user", "content": "C"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "kept",
|
||||
"content": "D",
|
||||
},
|
||||
],
|
||||
None,
|
||||
False,
|
||||
id="multi-turn-reasoning",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "system", "content": "Use tools."},
|
||||
{"role": "user", "content": "Weather?"},
|
||||
],
|
||||
TOOLS,
|
||||
True,
|
||||
id="tools-with-system",
|
||||
),
|
||||
pytest.param(
|
||||
[{"role": "user", "content": "Weather?"}],
|
||||
TOOLS,
|
||||
True,
|
||||
id="tools-with-default-system",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "Weather?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "not rendered in the tool-call branch",
|
||||
"content": " Checking. ",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {
|
||||
"city": "Paris",
|
||||
"days": 2,
|
||||
"options": {"units": "metric", "locale": "fr"},
|
||||
},
|
||||
}
|
||||
},
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "London", "days": 3},
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{"role": "tool", "content": '{"temp": 15}'},
|
||||
{"role": "assistant", "content": "Paris is warmer."},
|
||||
],
|
||||
TOOLS,
|
||||
False,
|
||||
id="tool-cycle",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _load(model: str):
|
||||
tokenizer = load_tokenizer(model)
|
||||
return tokenizer, create_renderer(tokenizer)
|
||||
|
||||
|
||||
def _expected(tokenizer, messages, tools, add_generation_prompt):
|
||||
result = tokenizer.apply_chat_template(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
)
|
||||
return list(result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("messages,tools,add_generation_prompt", CASES)
|
||||
def test_prime_qwen3_matches_hf_template(
|
||||
model,
|
||||
messages,
|
||||
tools,
|
||||
add_generation_prompt,
|
||||
):
|
||||
tokenizer, renderer = _load(model)
|
||||
|
||||
expected = _expected(tokenizer, messages, tools, add_generation_prompt)
|
||||
actual = renderer.render_ids(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
)
|
||||
|
||||
assert actual == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
def test_prime_qwen3_populates_assistant_masks(model):
|
||||
_, renderer = _load(model)
|
||||
prompt = [{"role": "user", "content": "Reverse abc"}]
|
||||
messages = [*prompt, {"role": "assistant", "content": "cba"}]
|
||||
|
||||
generation_prompt = renderer.render_ids(prompt, add_generation_prompt=True)
|
||||
rendered = renderer.render(messages)
|
||||
|
||||
assert rendered.token_ids[: len(generation_prompt)] == generation_prompt
|
||||
assert not any(rendered.sampled_mask[: len(generation_prompt)])
|
||||
assert any(rendered.sampled_mask[len(generation_prompt) :])
|
||||
assert rendered.sampled_mask[-1] is False
|
||||
assert (
|
||||
len(rendered.sampled_mask)
|
||||
== len(rendered.is_content)
|
||||
== len(rendered.token_ids)
|
||||
)
|
||||
@@ -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
|
||||
@@ -19,7 +18,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import Qwen35Renderer, create_renderer
|
||||
from renderers import Qwen35Renderer, Qwen35RendererConfig, create_renderer
|
||||
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
|
||||
|
||||
|
||||
@@ -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,19 +72,43 @@ 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, renderer="qwen3.5")
|
||||
renderer = create_renderer(tok, Qwen35RendererConfig())
|
||||
assert isinstance(renderer, Qwen35Renderer)
|
||||
assert renderer._enable_thinking is expected_default, (
|
||||
assert renderer.config.enable_thinking is expected_default, (
|
||||
f"{qwen35_model}: expected enable_thinking default {expected_default}, "
|
||||
f"got {renderer._enable_thinking}"
|
||||
f"got {renderer.config.enable_thinking}"
|
||||
)
|
||||
|
||||
|
||||
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,9 +169,9 @@ 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, renderer="qwen3.5")
|
||||
renderer = create_renderer(tok, Qwen35RendererConfig())
|
||||
assert isinstance(renderer, Qwen35Renderer)
|
||||
|
||||
ours = renderer.render_ids(messages, add_generation_prompt=add_gen_prompt)
|
||||
|
||||
@@ -338,7 +338,7 @@ def test_multi_step_tool_cycle(model_name, tokenizer, renderer):
|
||||
@lru_cache
|
||||
def _qwen3_vl():
|
||||
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
@@ -353,7 +353,7 @@ def test_qwen3_vl_auto_renderer():
|
||||
@lru_cache
|
||||
def _kimi_k25():
|
||||
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
@@ -366,7 +366,7 @@ def test_kimi_k2_inline_think_tags_render_verbatim():
|
||||
reasoning, producing tokens that disagreed with ``apply_chat_template``.
|
||||
"""
|
||||
tokenizer = load_tokenizer("moonshotai/Kimi-K2-Instruct")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
msgs = [
|
||||
{"role": "user", "content": "hi"},
|
||||
{"role": "assistant", "content": "<think>secret</think>visible"},
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
"""Unit tests for the typed-config surface — discriminated union,
|
||||
auto-resolution, and ``extra="forbid"`` enforcement on per-renderer
|
||||
configs."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pydantic import TypeAdapter, ValidationError
|
||||
|
||||
from renderers import (
|
||||
AutoRendererConfig,
|
||||
DefaultRendererConfig,
|
||||
GLM5RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
Nemotron3RendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
Qwen36RendererConfig,
|
||||
RendererConfig,
|
||||
base,
|
||||
create_renderer,
|
||||
create_renderer_pool,
|
||||
)
|
||||
|
||||
|
||||
def test_per_renderer_config_rejects_unknown_fields():
|
||||
"""``extra="forbid"`` on every typed variant catches bogus keys at
|
||||
construction: ``add_vision_id`` doesn't exist on ``Qwen3RendererConfig``
|
||||
(Qwen3 is text-only), so passing it must raise."""
|
||||
with pytest.raises(ValidationError, match="add_vision_id"):
|
||||
Qwen3RendererConfig(add_vision_id=True)
|
||||
|
||||
|
||||
def test_discriminated_union_dispatches_on_name():
|
||||
"""A dict shaped like ``{"name": "glm-5", ...}`` deserialises to the
|
||||
matching typed config; the union ``RendererConfig`` is what
|
||||
downstream consumers (prime-rl, verifiers) hold as a single field."""
|
||||
ta = TypeAdapter(RendererConfig)
|
||||
parsed = ta.validate_python(
|
||||
{"name": "glm-5", "enable_thinking": False, "clear_thinking": False}
|
||||
)
|
||||
assert isinstance(parsed, GLM5RendererConfig)
|
||||
assert parsed.enable_thinking is False
|
||||
assert parsed.clear_thinking is False
|
||||
|
||||
|
||||
def test_discriminated_union_rejects_wrong_renderer_kwargs():
|
||||
"""``add_vision_id`` under ``name="qwen3"`` is invalid at deserialise
|
||||
time — the discriminator narrows to ``Qwen3RendererConfig`` whose
|
||||
schema does not include that field."""
|
||||
ta = TypeAdapter(RendererConfig)
|
||||
with pytest.raises(ValidationError, match="add_vision_id"):
|
||||
ta.validate_python({"name": "qwen3", "add_vision_id": True})
|
||||
|
||||
|
||||
def test_default_renderer_config_accepts_arbitrary_extras():
|
||||
"""``DefaultRenderer`` wraps ``apply_chat_template`` for unknown
|
||||
templates, so its config uses ``extra="allow"`` and surfaces extras
|
||||
via ``model_extra``."""
|
||||
cfg = DefaultRendererConfig(
|
||||
tool_parser="qwen3", enable_thinking=False, custom_jinja_kwarg=True
|
||||
)
|
||||
assert cfg.tool_parser == "qwen3"
|
||||
assert cfg.model_extra == {
|
||||
"enable_thinking": False,
|
||||
"custom_jinja_kwarg": True,
|
||||
}
|
||||
|
||||
|
||||
def test_create_renderer_forwards_typed_config_to_renderer(monkeypatch):
|
||||
"""``create_renderer`` dispatches on ``config.name`` via
|
||||
``RENDERER_REGISTRY``; the renderer stores the config it was given."""
|
||||
|
||||
class _FakeRenderer:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.tokenizer = tokenizer
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeRenderer)
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="unused"),
|
||||
Qwen3RendererConfig(enable_thinking=False),
|
||||
)
|
||||
assert isinstance(renderer.config, Qwen3RendererConfig)
|
||||
assert renderer.config.enable_thinking is False
|
||||
|
||||
|
||||
def test_create_renderer_auto_resolves_via_model_map(monkeypatch):
|
||||
"""``AutoRendererConfig`` (or ``config=None``) routes through
|
||||
``MODEL_RENDERER_MAP`` to pick the matching renderer + typed config,
|
||||
carrying the shared ``thinking_retention`` field over from the auto config."""
|
||||
|
||||
class _FakeQwen35:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.tokenizer = tokenizer
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3.5", _FakeQwen35)
|
||||
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen35", "qwen3.5")
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/qwen35"),
|
||||
AutoRendererConfig(thinking_retention="all"),
|
||||
)
|
||||
|
||||
assert isinstance(renderer.config, Qwen35RendererConfig)
|
||||
assert renderer.config.thinking_retention == "all"
|
||||
# Template-level kwargs stay at their per-renderer defaults — auto
|
||||
# carries only the thinking_retention flag.
|
||||
assert renderer.config.add_vision_id is False
|
||||
|
||||
|
||||
def test_create_renderer_auto_applies_chat_template_kwargs(monkeypatch):
|
||||
"""Auto resolution happens before chat-template kwargs are validated."""
|
||||
|
||||
class _FakeQwen3:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.tokenizer = tokenizer
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeQwen3)
|
||||
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen3", "qwen3")
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/qwen3"),
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
assert isinstance(renderer.config, Qwen3RendererConfig)
|
||||
assert renderer.config.enable_thinking is False
|
||||
|
||||
|
||||
def test_create_renderer_pool_forwards_chat_template_kwargs(monkeypatch):
|
||||
"""Pool construction uses the same renderer-owned config resolution."""
|
||||
|
||||
class _FakeQwen3:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeQwen3)
|
||||
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen3", "qwen3")
|
||||
monkeypatch.setattr(
|
||||
base,
|
||||
"load_tokenizer",
|
||||
lambda name: SimpleNamespace(name_or_path=name),
|
||||
)
|
||||
|
||||
pool = create_renderer_pool(
|
||||
"fake/qwen3",
|
||||
size=1,
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
assert isinstance(pool._sole.config, Qwen3RendererConfig)
|
||||
assert pool._sole.config.enable_thinking is False
|
||||
|
||||
|
||||
def test_auto_unknown_model_rejects_chat_template_kwargs():
|
||||
tok = SimpleNamespace(name_or_path="unknown/text-model")
|
||||
|
||||
with pytest.raises(ValueError, match="chat_template_kwargs"):
|
||||
create_renderer(tok, chat_template_kwargs={"enable_thinking": False})
|
||||
|
||||
|
||||
def test_chat_template_kwargs_validate_against_resolved_config(monkeypatch):
|
||||
class _FakeQwen3:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeQwen3)
|
||||
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen3", "qwen3")
|
||||
|
||||
with pytest.raises(ValidationError, match="enable_thinkng"):
|
||||
create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/qwen3"),
|
||||
chat_template_kwargs={"enable_thinkng": False},
|
||||
)
|
||||
|
||||
|
||||
def test_chat_template_kwargs_conflict_with_explicit_config():
|
||||
with pytest.raises(ValidationError, match="thinking_retention"):
|
||||
create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/glm"),
|
||||
GLM5RendererConfig(thinking_retention="tool_cycle"),
|
||||
chat_template_kwargs={"clear_thinking": False},
|
||||
)
|
||||
|
||||
|
||||
def test_chat_template_kwargs_preserve_default_field_unset_state(monkeypatch):
|
||||
class _FakeGlm:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "glm-5", _FakeGlm)
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/glm"),
|
||||
GLM5RendererConfig(thinking_retention="all"),
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
assert renderer.config.thinking_retention == "all"
|
||||
assert renderer.config.enable_thinking is False
|
||||
|
||||
|
||||
def test_create_renderer_default_argument_is_auto():
|
||||
"""Passing no config is equivalent to passing ``AutoRendererConfig()``
|
||||
— short form for the common case."""
|
||||
tok = SimpleNamespace(name_or_path="") # no MODEL_RENDERER_MAP entry
|
||||
renderer = create_renderer(tok)
|
||||
# Falls through to DefaultRenderer when no match and no vision config.
|
||||
assert renderer.__class__.__name__ == "DefaultRenderer"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_cls,kwargs",
|
||||
[
|
||||
(GLM5RendererConfig, {"thinking_retention": "template"}),
|
||||
(
|
||||
GLM5RendererConfig,
|
||||
{"clear_thinking": False, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(GLM5RendererConfig, {"clear_thinking": True, "thinking_retention": "all"}),
|
||||
(
|
||||
Nemotron3RendererConfig,
|
||||
{
|
||||
"truncate_history_thinking": False,
|
||||
"thinking_retention": "tool_cycle",
|
||||
},
|
||||
),
|
||||
(
|
||||
Nemotron3RendererConfig,
|
||||
{"truncate_history_thinking": True, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
Qwen36RendererConfig,
|
||||
{"preserve_thinking": True, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(
|
||||
Qwen36RendererConfig,
|
||||
{"preserve_thinking": False, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
GptOssRendererConfig,
|
||||
{"auto_drop_analysis": False, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(
|
||||
GptOssRendererConfig,
|
||||
{"auto_drop_analysis": True, "thinking_retention": "all"},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_thinking_retention_conflict_raises(config_cls, kwargs):
|
||||
"""Explicit template and generic retention knobs must agree."""
|
||||
with pytest.raises(ValidationError, match="thinking_retention"):
|
||||
config_cls(**kwargs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_cls,kwargs",
|
||||
[
|
||||
(GLM5RendererConfig, {"clear_thinking": False, "thinking_retention": "all"}),
|
||||
(
|
||||
GLM5RendererConfig,
|
||||
{"clear_thinking": True, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(GLM5RendererConfig, {"clear_thinking": False}),
|
||||
(GLM5RendererConfig, {"thinking_retention": "tool_cycle"}),
|
||||
(
|
||||
Nemotron3RendererConfig,
|
||||
{"truncate_history_thinking": False, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
Nemotron3RendererConfig,
|
||||
{
|
||||
"truncate_history_thinking": True,
|
||||
"thinking_retention": "tool_cycle",
|
||||
},
|
||||
),
|
||||
(
|
||||
Qwen36RendererConfig,
|
||||
{"preserve_thinking": True, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
Qwen36RendererConfig,
|
||||
{"preserve_thinking": False, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(
|
||||
GptOssRendererConfig,
|
||||
{"auto_drop_analysis": False, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
GptOssRendererConfig,
|
||||
{"auto_drop_analysis": True, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_thinking_retention_consistent_pairs_are_accepted(config_cls, kwargs):
|
||||
config_cls(**kwargs)
|
||||
|
||||
|
||||
def test_default_renderer_rejects_explicit_retention():
|
||||
"""Opaque apply_chat_template fallback cannot implement bridge policy."""
|
||||
tok = SimpleNamespace(name_or_path="")
|
||||
create_renderer(tok, DefaultRendererConfig())
|
||||
|
||||
for retention in ("tool_cycle", "all"):
|
||||
with pytest.raises(ValueError, match="DefaultRenderer"):
|
||||
create_renderer(tok, DefaultRendererConfig(thinking_retention=retention))
|
||||
|
||||
|
||||
def test_default_renderer_config_rejects_legacy_preserve_flags():
|
||||
"""``DefaultRendererConfig`` is ``extra="allow"``, so the removed
|
||||
``preserve_*`` bools would otherwise slip into ``model_extra`` and be
|
||||
forwarded to ``apply_chat_template`` silently. A validator rejects them
|
||||
with a migration message; genuine Jinja kwargs still pass through."""
|
||||
with pytest.raises(ValidationError, match="thinking_retention"):
|
||||
DefaultRendererConfig(preserve_all_thinking=True)
|
||||
with pytest.raises(ValidationError, match="thinking_retention"):
|
||||
DefaultRendererConfig(preserve_thinking_between_tool_calls=True)
|
||||
|
||||
cfg = DefaultRendererConfig(some_jinja_kwarg=True)
|
||||
assert cfg.model_extra["some_jinja_kwarg"] is True
|
||||
@@ -0,0 +1,563 @@
|
||||
"""Parity for typed-config template fields against the upstream chat
|
||||
template.
|
||||
|
||||
Each renderer's typed config (see ``renderers.configs``) declares the
|
||||
fields that mirror chat-template kwargs via
|
||||
``Config.template_field_names()``. ``test_renderer_config.py`` covers
|
||||
the typed-config wiring; this file covers the only thing that matters
|
||||
downstream: that flipping a template field on the typed config produces
|
||||
token streams byte-identical to
|
||||
``tokenizer.apply_chat_template(messages, **{field: value})``.
|
||||
|
||||
Without this, the typed surface is a promise the renderer doesn't keep.
|
||||
|
||||
Discovery is automatic — the parity matrix is built from each config
|
||||
class's ``template_field_names()`` crossed with the per-field value list
|
||||
in ``_KWARG_VALUES``. To extend coverage to a new field: declare it on
|
||||
the typed config and add the values to exercise to ``_KWARG_VALUES``
|
||||
below.
|
||||
|
||||
``gpt-oss`` parity is against ``openai-harmony`` (its renderer diverges
|
||||
from HF Jinja by design — see ``test_gpt_oss_harmony_parity.py``); it
|
||||
lives in its own test below, with the same auto-derived discovery.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import (
|
||||
MODEL_RENDERER_MAP,
|
||||
_populate_registry,
|
||||
load_tokenizer,
|
||||
)
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
|
||||
# Models exercised by the parity tests. Mirrors ``conftest.RENDERER_MODELS``
|
||||
# in spirit — one representative model per renderer family — plus the
|
||||
# ``gpt-oss`` entry that conftest skips for HF parity (gpt-oss parity is
|
||||
# against harmony, handled separately below).
|
||||
_RENDERER_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"),
|
||||
("Qwen/Qwen3.5-9B", "auto"),
|
||||
("Qwen/Qwen3.6-35B-A3B", "auto"),
|
||||
("zai-org/GLM-5", "auto"),
|
||||
("zai-org/GLM-5.1", "auto"),
|
||||
("zai-org/GLM-4.7-Flash", "auto"),
|
||||
("THUDM/GLM-4.5-Air", "auto"),
|
||||
("moonshotai/Kimi-K2.5", "auto"),
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("deepseek-ai/DeepSeek-V3", "auto"),
|
||||
("deepseek-ai/DeepSeek-R1", "auto"),
|
||||
# Nano + Super share the ``nemotron-3`` config (incl. ``low_effort``, which
|
||||
# fires only on Super); both are exercised so the kwarg is checked where it
|
||||
# no-ops (Nano) AND where it appends (Super).
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
|
||||
# Ultra: auto-resolves to the ``nemotron-3-ultra`` config via the model
|
||||
# name; parity asserted against the Ultra apply_chat_template (``medium_effort``).
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("poolside/Laguna-XS-2.1", "auto"),
|
||||
("tencent/Hy3", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
]
|
||||
|
||||
|
||||
# Per-kwarg value list. Each template field any renderer's typed config
|
||||
# declares (via ``Config.template_field_names()``) must have an entry
|
||||
# here, or the parity matrix silently skips it. The test below asserts
|
||||
# coverage so a future kwarg can't slip through without an explicit
|
||||
# value list.
|
||||
_KWARG_VALUES: dict[str, list[Any]] = {
|
||||
"enable_thinking": [True, False],
|
||||
# Kimi K2.5 / K2.6 — same semantics as ``enable_thinking`` but the
|
||||
# upstream template uses ``thinking`` as the variable name. The
|
||||
# renderer's typed config (``KimiK25RendererConfig.thinking``)
|
||||
# mirrors that name so the field maps 1:1 onto the template gate.
|
||||
"thinking": [True, False],
|
||||
# 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>``).
|
||||
"clear_thinking": [True, False],
|
||||
# Nemotron-3 — mirror of ``clear_thinking`` under a different name.
|
||||
# ``truncate_history_thinking=False`` keeps reasoning on historical
|
||||
# assistants instead of collapsing to ``<think></think>``.
|
||||
"truncate_history_thinking": [True, False],
|
||||
# Nemotron-3 reasoning-effort hints appended to the last user message.
|
||||
# ``low_effort`` is a Super (``nemotron-3``) kwarg; ``medium_effort`` an
|
||||
# Ultra (``nemotron-3-ultra``) kwarg. On the variant that doesn't define
|
||||
# the kwarg the template — and the renderer — no-op it.
|
||||
"low_effort": [True, False],
|
||||
"medium_effort": [True, False],
|
||||
# MiniMax-M2 — fallback persona string when no system message is
|
||||
# supplied. Two arbitrary values to verify the renderer threads the
|
||||
# exact bytes through (whitespace included).
|
||||
"model_identity": [
|
||||
"You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax.",
|
||||
"You are CustomBot, a research assistant.",
|
||||
],
|
||||
# Laguna-XS.2 — switches assistant rendering to a verbatim
|
||||
# passthrough mode. The renderer paths diverge significantly under
|
||||
# this flag, so both values are exercised.
|
||||
"render_assistant_messages_raw": [True, False],
|
||||
# Qwen3.5 / Qwen3.6 / Qwen3-VL — when True, prefix each image /
|
||||
# video placeholder with ``Picture N: `` / ``Video N: ``.
|
||||
"add_vision_id": [True, False],
|
||||
# Qwen3.6 — keep historical think blocks before the last real user query.
|
||||
"preserve_thinking": [True, False],
|
||||
# gpt-oss — pin to a fixed date so the renderer's preamble matches
|
||||
# the harmony oracle built with the same date. The default
|
||||
# ``today's date`` is intentionally avoided here so the assertion
|
||||
# doesn't flake on a UTC midnight crossing.
|
||||
"conversation_start_date": ["2025-01-15"],
|
||||
}
|
||||
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "The city name"},
|
||||
},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
# (id, messages, render_kwargs). Each shape exercises a distinct branch
|
||||
# at least one renderer is known to flip on a kwarg:
|
||||
#
|
||||
# - ``system_user_gen``: forces the generation-prompt branch (e.g.
|
||||
# Qwen3 / GLM / Nemotron emit a synthesized ``<think></think>`` here
|
||||
# under ``enable_thinking=False``).
|
||||
# - ``single_turn``: terminal assistant with plain content — the
|
||||
# "render historical thinking?" branch.
|
||||
# - ``with_reasoning``: assistant carries ``reasoning_content`` — flips
|
||||
# whether thinking is emitted into the rendered history.
|
||||
# - ``multi_turn``: two assistant turns separated by a user; the
|
||||
# in-flight-vs-historical distinction matters for several renderers.
|
||||
# - ``tool_cycle``: assistant tool call + tool response + final
|
||||
# assistant, with ``add_generation_prompt=True`` so the second
|
||||
# gen-prompt branch is hit too.
|
||||
_MESSAGE_SHAPES = [
|
||||
(
|
||||
"system_user_gen",
|
||||
[
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
],
|
||||
{"add_generation_prompt": True},
|
||||
),
|
||||
(
|
||||
"single_turn",
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{"role": "assistant", "content": "4"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"with_reasoning",
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Simple arithmetic.",
|
||||
"content": "4",
|
||||
},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"multi_turn",
|
||||
[
|
||||
{"role": "user", "content": "A"},
|
||||
{"role": "assistant", "content": "B"},
|
||||
{"role": "user", "content": "C"},
|
||||
{"role": "assistant", "content": "D"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"tool_cycle",
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{"role": "assistant", "content": "It is 20 degrees."},
|
||||
],
|
||||
{"tools": TOOLS, "add_generation_prompt": True},
|
||||
),
|
||||
# ``no_system_user_gen``: no system message — exercises the
|
||||
# template fallback persona (e.g. MiniMax-M2's ``model_identity``).
|
||||
(
|
||||
"no_system_user_gen",
|
||||
[{"role": "user", "content": "Hi"}],
|
||||
{"add_generation_prompt": True},
|
||||
),
|
||||
# ``historical_reasoning``: multi-turn with ``reasoning_content`` on
|
||||
# a historical assistant. Exercises ``clear_thinking`` /
|
||||
# ``truncate_history_thinking`` (which only diverge from default
|
||||
# behaviour when a past-cycle assistant carries reasoning).
|
||||
(
|
||||
"historical_reasoning",
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Adding small ints.",
|
||||
"content": "4",
|
||||
},
|
||||
{"role": "user", "content": "Now 3+3?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Same idea.",
|
||||
"content": "6",
|
||||
},
|
||||
],
|
||||
{},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# ── Matrix discovery ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
_populate_registry()
|
||||
|
||||
|
||||
def _resolve_renderer_name(model: str, renderer_name: str) -> str:
|
||||
"""Resolve ``(model, renderer_name)`` to the concrete renderer name."""
|
||||
if renderer_name == "auto":
|
||||
return MODEL_RENDERER_MAP.get(model, "default")
|
||||
return renderer_name
|
||||
|
||||
|
||||
def _template_fields_for(model: str, renderer_name: str) -> frozenset[str]:
|
||||
"""Discover the typed-config template-field set for a renderer."""
|
||||
resolved = _resolve_renderer_name(model, renderer_name)
|
||||
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
|
||||
separately against harmony).
|
||||
"""
|
||||
out = []
|
||||
for model, name in _RENDERER_MODELS:
|
||||
if name == "gpt-oss":
|
||||
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}"
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _harmony_parity_matrix() -> list[Any]:
|
||||
"""Auto-derived ``(model, renderer_name, kwarg, value)`` matrix for
|
||||
gpt-oss (parity against ``openai-harmony``).
|
||||
"""
|
||||
out = []
|
||||
for model, name in _RENDERER_MODELS:
|
||||
if name != "gpt-oss":
|
||||
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}"
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_kwarg_values_covers_every_declared_kwarg():
|
||||
"""Every template field any renderer declares must have an entry in
|
||||
``_KWARG_VALUES`` — otherwise it silently drops out of parity
|
||||
coverage.
|
||||
"""
|
||||
declared: set[str] = set()
|
||||
for model, name in _RENDERER_MODELS:
|
||||
declared.update(_template_fields_for(model, name))
|
||||
missing = sorted(declared - _KWARG_VALUES.keys())
|
||||
assert not missing, (
|
||||
f"Typed-config template fields declared but not covered: {missing}. "
|
||||
f"Add a value list to _KWARG_VALUES in this file."
|
||||
)
|
||||
|
||||
|
||||
# ── Test caches ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _tokenizer(model_name: str):
|
||||
return load_tokenizer(model_name)
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _renderer_with_kwarg(model_name: str, renderer_name: str, kwarg: str, value: Any):
|
||||
tok = _tokenizer(model_name)
|
||||
resolved = _resolve_renderer_name(model_name, renderer_name)
|
||||
config = _config_class_for(resolved)(**{kwarg: value})
|
||||
return create_renderer(tok, config)
|
||||
|
||||
|
||||
def _expected_hf(tokenizer, messages, *, kwarg: str, value: Any, **render_kwargs):
|
||||
"""Render via ``apply_chat_template`` with the kwarg spread as a
|
||||
top-level argument.
|
||||
|
||||
transformers v5.x silently drops ``chat_template_kwargs={...}`` —
|
||||
only direct kwargs propagate into the Jinja environment. The two
|
||||
invocation styles are semantically the same for the Jinja template,
|
||||
so we pick the one that actually fires. (Our ``create_renderer``
|
||||
API accepts the dict form because it is the standard wire format
|
||||
in OpenAI-compatible servers; we translate it to constructor kwargs
|
||||
on our side.)
|
||||
"""
|
||||
render_kwargs.setdefault("add_generation_prompt", False)
|
||||
result = tokenizer.apply_chat_template(
|
||||
messages,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
**{kwarg: value},
|
||||
**render_kwargs,
|
||||
)
|
||||
if isinstance(result, dict):
|
||||
return list(result["input_ids"])
|
||||
if isinstance(result, str):
|
||||
return list(tokenizer.encode(result, add_special_tokens=False))
|
||||
return list(result)
|
||||
|
||||
|
||||
# ── HF-Jinja parity (every renderer except gpt-oss) ────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model,renderer_name,kwarg,value", _hf_parity_matrix())
|
||||
@pytest.mark.parametrize(
|
||||
"shape_id,messages,render_kwargs",
|
||||
_MESSAGE_SHAPES,
|
||||
ids=[s[0] for s in _MESSAGE_SHAPES],
|
||||
)
|
||||
def test_chat_template_kwarg_parity_hf(
|
||||
model,
|
||||
renderer_name,
|
||||
kwarg,
|
||||
value,
|
||||
shape_id,
|
||||
messages,
|
||||
render_kwargs,
|
||||
):
|
||||
tokenizer = _tokenizer(model)
|
||||
renderer = _renderer_with_kwarg(model, renderer_name, kwarg, value)
|
||||
# Guard: the typed config must actually declare the kwarg as a
|
||||
# template field. Pydantic ``extra="forbid"`` already enforces this
|
||||
# at construction; asserting here gives a louder failure on a future
|
||||
# config subclass that drops the field.
|
||||
assert kwarg in type(renderer.config).template_field_names()
|
||||
|
||||
try:
|
||||
expected = _expected_hf(
|
||||
tokenizer, messages, kwarg=kwarg, value=value, **render_kwargs
|
||||
)
|
||||
except Exception as exc:
|
||||
pytest.xfail(
|
||||
f"{model}: apply_chat_template raised {type(exc).__name__}: "
|
||||
f"{str(exc)[:160]}"
|
||||
)
|
||||
|
||||
got = renderer.render_ids(messages, **render_kwargs)
|
||||
assert got == expected, (
|
||||
f"{model} / shape={shape_id} / {kwarg}={value}: renderer diverged "
|
||||
f"from apply_chat_template (len got={len(got)}, expected={len(expected)})"
|
||||
)
|
||||
|
||||
|
||||
# ── Harmony parity (gpt-oss only) ──────────────────────────────────────
|
||||
|
||||
|
||||
_DATE_FOR_PARITY = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _gpt_oss_renderer(kwarg: str, value: Any):
|
||||
from renderers.configs import GptOssRendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
|
||||
tok = _tokenizer("openai/gpt-oss-20b")
|
||||
# Pin a default conversation_start_date so the rendered preamble
|
||||
# matches the harmony oracle's fixed date. Any explicit
|
||||
# ``conversation_start_date`` from the kwarg-under-test overrides
|
||||
# it (the per-kwarg branch replays the same value into the oracle
|
||||
# below so the assertion still holds).
|
||||
kwargs: dict[str, Any] = {"conversation_start_date": _DATE_FOR_PARITY}
|
||||
kwargs[kwarg] = value
|
||||
return GptOssRenderer(tok, GptOssRendererConfig(**kwargs))
|
||||
|
||||
|
||||
def _harmony_expected(
|
||||
kwarg: str, value: Any, messages: list[dict[str, Any]]
|
||||
) -> list[int]:
|
||||
from openai_harmony import (
|
||||
Conversation,
|
||||
HarmonyEncodingName,
|
||||
Message as HarmonyMessage,
|
||||
ReasoningEffort,
|
||||
Role,
|
||||
SystemContent,
|
||||
load_harmony_encoding,
|
||||
)
|
||||
|
||||
# Base preamble pins the same default date the renderer fixture
|
||||
# uses so the unrelated kwargs don't drift on date semantics.
|
||||
sys_content = SystemContent.new().with_conversation_start_date(_DATE_FOR_PARITY)
|
||||
if kwarg == "reasoning_effort":
|
||||
effort_enum = {
|
||||
"low": ReasoningEffort.LOW,
|
||||
"medium": ReasoningEffort.MEDIUM,
|
||||
"high": ReasoningEffort.HIGH,
|
||||
}[value]
|
||||
sys_content = sys_content.with_reasoning_effort(effort_enum)
|
||||
elif kwarg == "conversation_start_date":
|
||||
# Override the pinned date with the value under test.
|
||||
sys_content = sys_content.with_conversation_start_date(value)
|
||||
else:
|
||||
raise AssertionError(
|
||||
f"Harmony oracle: unhandled gpt-oss chat_template_kwarg {kwarg!r}. "
|
||||
"Add a branch here when extending GptOssRendererConfig's template fields."
|
||||
)
|
||||
|
||||
harmony_msgs: list[HarmonyMessage] = [
|
||||
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
|
||||
]
|
||||
for m in messages:
|
||||
role = m["role"]
|
||||
content = m.get("content", "") or ""
|
||||
if role == "user":
|
||||
harmony_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(Role.USER, content)
|
||||
)
|
||||
elif role == "assistant":
|
||||
harmony_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(
|
||||
Role.ASSISTANT, content
|
||||
).with_channel("final")
|
||||
)
|
||||
else:
|
||||
raise AssertionError(
|
||||
f"Harmony oracle helper does not handle role={role!r}; add a "
|
||||
"branch or constrain the shapes used for gpt-oss parity."
|
||||
)
|
||||
encoder = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
|
||||
return encoder.render_conversation_for_training(
|
||||
Conversation.from_messages(harmony_msgs)
|
||||
)
|
||||
|
||||
|
||||
# Harmony oracle is only wired for the simplest shapes (user-only and
|
||||
# user+assistant content). Tool-call and reasoning_content shapes have
|
||||
# a richer mapping that the dedicated ``test_gpt_oss_harmony_parity.py``
|
||||
# already covers — duplicating that here would only test the harness.
|
||||
_HARMONY_SHAPES = [
|
||||
(
|
||||
"user_only_gen",
|
||||
[{"role": "user", "content": "Hello!"}],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"user_and_assistant",
|
||||
[
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model,renderer_name,kwarg,value", _harmony_parity_matrix())
|
||||
@pytest.mark.parametrize(
|
||||
"shape_id,messages,render_kwargs",
|
||||
_HARMONY_SHAPES,
|
||||
ids=[s[0] for s in _HARMONY_SHAPES],
|
||||
)
|
||||
def test_chat_template_kwarg_parity_harmony(
|
||||
model,
|
||||
renderer_name,
|
||||
kwarg,
|
||||
value,
|
||||
shape_id,
|
||||
messages,
|
||||
render_kwargs,
|
||||
):
|
||||
renderer = _gpt_oss_renderer(kwarg, value)
|
||||
assert kwarg in type(renderer.config).template_field_names()
|
||||
|
||||
got = renderer.render_ids(messages, **render_kwargs)
|
||||
expected = _harmony_expected(kwarg, value, messages)
|
||||
assert got == expected, (
|
||||
f"{model} / shape={shape_id} / {kwarg}={value}: renderer diverged "
|
||||
f"from harmony oracle (len got={len(got)}, expected={len(expected)})"
|
||||
)
|
||||
+19
-4
@@ -25,11 +25,11 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# (HuggingFace model name, renderer name or "auto"). These are the
|
||||
# renderers we actively rely on; expand as new ones get hand-coded.
|
||||
_ROUNDTRIP_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"),
|
||||
("PrimeIntellect/Qwen3-0.6B", "auto"),
|
||||
("Qwen/Qwen3.5-9B", "auto"),
|
||||
("Qwen/Qwen3.6-35B-A3B", "auto"),
|
||||
("Qwen/Qwen3-VL-4B-Instruct", "auto"),
|
||||
@@ -43,7 +43,16 @@ _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"),
|
||||
# Laguna-XS-2.1 is deliberately absent: under the default
|
||||
# ``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"),
|
||||
]
|
||||
@@ -51,11 +60,11 @@ _ROUNDTRIP_MODELS = [
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _load_renderer(model_name: str, renderer_name: str):
|
||||
from renderers import create_renderer
|
||||
from renderers import config_from_name, create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer(model_name)
|
||||
return tok, create_renderer(tok, renderer=renderer_name)
|
||||
return tok, create_renderer(tok, config_from_name(renderer_name))
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc):
|
||||
@@ -207,6 +216,12 @@ def test_roundtrip_multiple_tool_calls(
|
||||
"""Parsers that loop over ``<tool_call>…</tool_call>`` blocks can
|
||||
silently drop the second one; this test catches that."""
|
||||
_maybe_skip_tool_calls(rt_renderer_name)
|
||||
if rt_renderer_name == "llama-3":
|
||||
pytest.skip(
|
||||
"Llama-3's chat template forbids >1 tool call per assistant "
|
||||
"message (the renderer raises, mirroring the template); the "
|
||||
"single-call path is covered by test_roundtrip_single_tool_call."
|
||||
)
|
||||
|
||||
msg = {
|
||||
"role": "assistant",
|
||||
@@ -316,7 +331,7 @@ def test_default_renderer_fallback_parser_preserves_boundary_whitespace(
|
||||
"""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
renderer = DefaultRenderer(rt_tokenizer, tool_parser=None, reasoning_parser=None)
|
||||
renderer = DefaultRenderer(rt_tokenizer)
|
||||
|
||||
# Encode `<think>reason</think>\nvisible` as text and run through
|
||||
# parse_response. We don't need the template to emit `<think>` here
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
"""Tests for per-message / per-role token-count and span helpers.
|
||||
|
||||
These methods on :class:`RenderedTokens` derive from the existing
|
||||
``message_indices`` / ``sampled_mask`` / ``message_roles`` signals —
|
||||
they're analytics helpers, not new attribution. The contract these
|
||||
tests pin:
|
||||
|
||||
- ``sum(tokens_per_message()) + scaffold_count == len(token_ids)`` — the
|
||||
helper accounts for every token exactly once, with ``-1``-attributed
|
||||
scaffolding outside the per-message bucket.
|
||||
- ``sampled_only=True`` excludes the role-tag opener
|
||||
(``<|im_start|>role\\n``) the template injects around an assistant
|
||||
message. The assistant message's sampled count must be strictly less
|
||||
than its total count.
|
||||
- ``sampled_only=True`` is zero for tool / user / system roles — the
|
||||
model never samples conversation history.
|
||||
- ``message_token_spans`` returns contiguous ``(start, end)`` slices
|
||||
per message that ``zip``s against ``message_roles``. Slicing
|
||||
``token_ids[start:end]`` recovers the message's tokens.
|
||||
|
||||
Renderers that opt out of ``sampled_mask`` (DefaultRenderer — the
|
||||
Jinja template is opaque) are exempt from the ``sampled_only``
|
||||
assertions and return all zeros from the helper under that flag.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from renderers.base import RenderedTokens
|
||||
|
||||
|
||||
def test_tokens_per_message_sum_equals_attributed(model_name, renderer):
|
||||
"""``sum(tokens_per_message()) + scaffold_count == len(token_ids)``.
|
||||
|
||||
Every token lands in exactly one of (a) a caller-relative message
|
||||
bucket, or (b) the ``-1`` scaffolding bucket. No double-counts, no
|
||||
drops.
|
||||
"""
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs, add_generation_prompt=True)
|
||||
|
||||
counts = rendered.tokens_per_message()
|
||||
scaffold = sum(1 for idx in rendered.message_indices if idx == -1)
|
||||
assert sum(counts) + scaffold == len(rendered.token_ids), (
|
||||
f"{model_name}: tokens_per_message sum {sum(counts)} + scaffold "
|
||||
f"{scaffold} != token count {len(rendered.token_ids)}"
|
||||
)
|
||||
|
||||
# message_roles populated, length matches caller input.
|
||||
assert len(rendered.message_roles) == len(msgs), (
|
||||
f"{model_name}: message_roles length {len(rendered.message_roles)} "
|
||||
f"!= len(msgs) {len(msgs)}"
|
||||
)
|
||||
assert rendered.message_roles == ["system", "user", "assistant"], (
|
||||
f"{model_name}: message_roles {rendered.message_roles} != input roles"
|
||||
)
|
||||
|
||||
# Every caller message must have a positive count.
|
||||
bad = [i for i, n in enumerate(counts) if n == 0]
|
||||
assert not bad, f"{model_name}: messages with zero attributed tokens: {bad}"
|
||||
|
||||
|
||||
def test_tokens_per_message_sampled_lt_total_for_assistant(model_name, renderer):
|
||||
"""The assistant message's ``sampled_only=True`` count must be
|
||||
strictly less than its full count.
|
||||
|
||||
The template wraps an assistant turn with at least one role-tag
|
||||
token (``<|im_start|>assistant\\n`` or equivalent) that the model
|
||||
doesn't sample at inference. Skips renderers that opt out of
|
||||
``sampled_mask`` (DefaultRenderer).
|
||||
"""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello world!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not rendered.sampled_mask:
|
||||
return
|
||||
|
||||
total = rendered.tokens_per_message()
|
||||
sampled = rendered.tokens_per_message(sampled_only=True)
|
||||
|
||||
assistant_idx = 1
|
||||
assert sampled[assistant_idx] < total[assistant_idx], (
|
||||
f"{model_name}: assistant sampled count {sampled[assistant_idx]} "
|
||||
f"not strictly less than total {total[assistant_idx]} — role-tag "
|
||||
f"opener should have been excluded"
|
||||
)
|
||||
assert sampled[assistant_idx] > 0, (
|
||||
f"{model_name}: assistant sampled count is zero — content tokens "
|
||||
f"should be is_sampled=True"
|
||||
)
|
||||
|
||||
|
||||
def test_tokens_per_message_sampled_zero_for_history_roles(model_name, renderer):
|
||||
"""``sampled_only=True`` counts are zero for user / system / tool —
|
||||
the model never samples conversation history."""
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not rendered.sampled_mask:
|
||||
return
|
||||
|
||||
sampled = rendered.tokens_per_message(sampled_only=True)
|
||||
assert sampled[0] == 0, (
|
||||
f"{model_name}: system message sampled count {sampled[0]} != 0"
|
||||
)
|
||||
assert sampled[1] == 0, (
|
||||
f"{model_name}: user message sampled count {sampled[1]} != 0"
|
||||
)
|
||||
|
||||
|
||||
def test_tokens_per_message_truncates_to_n_messages(model_name, renderer):
|
||||
"""Passing explicit ``n_messages`` smaller than the populated count
|
||||
silently drops tail messages — the helper doesn't raise."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
truncated = rendered.tokens_per_message(1)
|
||||
assert len(truncated) == 1
|
||||
assert truncated[0] > 0
|
||||
|
||||
|
||||
def test_tokens_per_message_clamps_oversized_n_messages(model_name, renderer):
|
||||
"""Passing ``n_messages`` larger than ``len(message_roles)`` is
|
||||
clamped — the helper never reports more messages than the renderer
|
||||
attributed, so callers can't read trailing-zero phantoms."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
clamped = rendered.tokens_per_message(99)
|
||||
assert len(clamped) == len(rendered.message_roles)
|
||||
assert clamped == rendered.tokens_per_message()
|
||||
|
||||
|
||||
def test_tokens_per_message_bridge_attributes_new_messages(model_name, renderer):
|
||||
"""``bridge_to_next_turn`` returns ``RenderedTokens`` with proper
|
||||
per-token attribution AND populated ``message_roles`` for
|
||||
``new_messages``. ``sampled_mask`` is uniformly ``False``.
|
||||
|
||||
DefaultRenderer's ``bridge_to_next_turn`` returns ``None``
|
||||
unconditionally, so we skip when bridge is unsupported.
|
||||
"""
|
||||
prior = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered_prior = renderer.render(prior, add_generation_prompt=False)
|
||||
new_messages = [
|
||||
{"role": "user", "content": "Tell me a longer story please"},
|
||||
]
|
||||
bridge = renderer.bridge_to_next_turn(
|
||||
previous_prompt_ids=rendered_prior.token_ids,
|
||||
previous_completion_ids=[],
|
||||
new_messages=new_messages,
|
||||
)
|
||||
if bridge is None:
|
||||
return
|
||||
|
||||
assert len(bridge.message_indices) == len(bridge.token_ids), (
|
||||
f"{model_name}: bridge message_indices length mismatch"
|
||||
)
|
||||
assert len(bridge.sampled_mask) == len(bridge.token_ids), (
|
||||
f"{model_name}: bridge sampled_mask length mismatch"
|
||||
)
|
||||
assert bridge.message_roles == ["user"], (
|
||||
f"{model_name}: bridge message_roles {bridge.message_roles} != ['user']"
|
||||
)
|
||||
assert not any(bridge.sampled_mask), (
|
||||
f"{model_name}: bridge emitted a token marked is_sampled=True"
|
||||
)
|
||||
|
||||
counts = bridge.tokens_per_message()
|
||||
assert counts == [counts[0]] and counts[0] > 0, (
|
||||
f"{model_name}: bridge attributed {counts} tokens; expected one "
|
||||
f"positive entry for the new user message"
|
||||
)
|
||||
|
||||
|
||||
def test_tokens_by_role_includes_every_input_role(model_name, renderer):
|
||||
"""``tokens_by_role`` returns a key for every role that appears in
|
||||
``message_roles``. Counts sum to the same value as
|
||||
``tokens_per_message``.
|
||||
"""
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
|
||||
by_role = rendered.tokens_by_role()
|
||||
assert set(by_role) == {"system", "user", "assistant"}, (
|
||||
f"{model_name}: tokens_by_role keys {set(by_role)} != expected roles"
|
||||
)
|
||||
assert sum(by_role.values()) == sum(rendered.tokens_per_message()), (
|
||||
f"{model_name}: tokens_by_role sum disagrees with tokens_per_message sum"
|
||||
)
|
||||
|
||||
|
||||
def test_tokens_by_role_sampled_only_assistant_only(model_name, renderer):
|
||||
"""Under ``sampled_only=True``, only ``assistant`` has a positive
|
||||
count — every other role's tokens were template-injected."""
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not rendered.sampled_mask:
|
||||
return
|
||||
|
||||
by_role = rendered.tokens_by_role(sampled_only=True)
|
||||
assert by_role["assistant"] > 0
|
||||
assert by_role["system"] == 0
|
||||
assert by_role["user"] == 0
|
||||
|
||||
|
||||
def test_message_token_spans_recover_token_ranges(model_name, renderer):
|
||||
"""``message_token_spans()`` returns ``(start, end)`` such that
|
||||
``token_ids[start:end]`` contains exactly the tokens attributed to
|
||||
that message and ``token_ids[end-1]`` is still in that message
|
||||
(i.e. the span is the inclusive token range of the message).
|
||||
|
||||
Also: spans cover every non-scaffolding token; the spans are
|
||||
ordered by message index; concatenating
|
||||
``token_ids[start:end]`` for every non-None span plus the
|
||||
``-1``-attributed scaffolding tokens equals the original
|
||||
``token_ids``.
|
||||
"""
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs, add_generation_prompt=True)
|
||||
spans = rendered.message_token_spans()
|
||||
assert len(spans) == len(msgs)
|
||||
|
||||
# Each span's tokens match the message_indices attribution.
|
||||
for i, span in enumerate(spans):
|
||||
assert span is not None, f"{model_name}: message {i} has no span"
|
||||
start, end = span
|
||||
attributed = [
|
||||
rendered.message_indices[k]
|
||||
for k in range(start, end)
|
||||
if rendered.message_indices[k] == i
|
||||
]
|
||||
# At least one token in the span belongs to this message
|
||||
# (contiguity assumption — see method docstring).
|
||||
assert attributed, (
|
||||
f"{model_name}: span {span} for msg {i} contains no msg-i tokens"
|
||||
)
|
||||
|
||||
# Spans are non-decreasing by start.
|
||||
starts = [s[0] for s in spans if s is not None]
|
||||
assert starts == sorted(starts), (
|
||||
f"{model_name}: spans not in message order: {starts}"
|
||||
)
|
||||
|
||||
|
||||
def test_role_token_spans_groups_by_role(model_name, renderer):
|
||||
"""``role_token_spans()`` groups :meth:`message_token_spans` by
|
||||
role. The total tokens captured per role should match
|
||||
``tokens_by_role()``.
|
||||
"""
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
role_spans = rendered.role_token_spans()
|
||||
by_role = rendered.tokens_by_role()
|
||||
|
||||
for role, spans in role_spans.items():
|
||||
span_total = sum(e - s for s, e in spans)
|
||||
assert span_total == by_role[role], (
|
||||
f"{model_name}: role {role!r} span-total {span_total} != "
|
||||
f"tokens_by_role {by_role[role]}"
|
||||
)
|
||||
|
||||
|
||||
def test_tokens_per_message_no_messages_helper_works():
|
||||
"""Pure-data-shape: methods on a manually-constructed RenderedTokens
|
||||
without any renderer involvement. No fixture needed."""
|
||||
r = RenderedTokens(
|
||||
token_ids=[10, 11, 12, 13, 14],
|
||||
message_indices=[0, 0, 1, 1, -1],
|
||||
sampled_mask=[False, True, False, False, False],
|
||||
message_roles=["user", "assistant"],
|
||||
)
|
||||
assert r.tokens_per_message() == [2, 2]
|
||||
assert r.tokens_per_message(sampled_only=True) == [1, 0]
|
||||
assert r.tokens_by_role() == {"user": 2, "assistant": 2}
|
||||
assert r.tokens_by_role(sampled_only=True) == {"user": 1, "assistant": 0}
|
||||
assert r.message_token_spans() == [(0, 2), (2, 4)]
|
||||
assert r.role_token_spans() == {
|
||||
"user": [(0, 2)],
|
||||
"assistant": [(2, 4)],
|
||||
}
|
||||
|
||||
|
||||
def test_message_token_spans_empty_message():
|
||||
"""A message that contributed zero tokens (rare but possible for
|
||||
empty content some templates skip) gets ``None`` as its span."""
|
||||
r = RenderedTokens(
|
||||
token_ids=[10, 11, 12],
|
||||
message_indices=[0, 0, 2],
|
||||
message_roles=["user", "assistant", "tool"],
|
||||
)
|
||||
spans = r.message_token_spans()
|
||||
assert spans[0] == (0, 2)
|
||||
assert spans[1] is None # no tokens attributed
|
||||
assert spans[2] == (2, 3)
|
||||
@@ -26,25 +26,27 @@ import pytest
|
||||
|
||||
|
||||
# (HuggingFace model name, renderer name). Two JSON-shaped controls
|
||||
# (string types already preserved by the wire format) + four XML-style
|
||||
# (string types already preserved by the wire format) + five XML-style
|
||||
# parsers that rely on the schema to preserve them.
|
||||
_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"), # hermes JSON — control
|
||||
("moonshotai/Kimi-K2-Instruct", "auto"), # section JSON — control
|
||||
("Qwen/Qwen3.5-9B", "auto"), # XML
|
||||
("PrimeIntellect/Qwen3-0.6B", "auto"), # XML
|
||||
("zai-org/GLM-5", "auto"), # XML
|
||||
("MiniMaxAI/MiniMax-M2.5", "auto"), # XML
|
||||
("poolside/Laguna-XS.2", "auto"), # XML
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"), # XML
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _load(model: str, renderer_name: str):
|
||||
from renderers import create_renderer
|
||||
from renderers import config_from_name, create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer(model)
|
||||
return tok, create_renderer(tok, renderer=renderer_name)
|
||||
return tok, create_renderer(tok, config_from_name(renderer_name))
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc):
|
||||
@@ -137,3 +139,75 @@ def test_string_arg_preserves_type(model, renderer_name, renderer, args):
|
||||
assert got == args, (
|
||||
f"{model}: tool-arg type drift — sent {args!r}, parser returned {got!r}"
|
||||
)
|
||||
|
||||
|
||||
# Schemas where ``string`` is one branch of a union (``anyOf`` / ``oneOf``).
|
||||
# These are common in practice — e.g. ``form_input.value: str | bool`` in
|
||||
# Pydantic serialises to ``{"anyOf": [{"type": "string"}, {"type": "boolean"}]}``.
|
||||
# Without the union-aware check, the XML parser's ``json.loads`` falls back
|
||||
# to raw text for bare strings, but flags the call ``INVALID_JSON`` because
|
||||
# no top-level ``type`` key declared a string — silently dropping otherwise
|
||||
# valid tool calls in the renderer client.
|
||||
UNION_WITH_STRING_SCHEMAS = [
|
||||
pytest.param(
|
||||
{"anyOf": [{"type": "string"}, {"type": "boolean"}]},
|
||||
id="anyOf-string-boolean",
|
||||
),
|
||||
pytest.param(
|
||||
{"anyOf": [{"type": "string"}, {"type": "null"}]},
|
||||
id="anyOf-string-null",
|
||||
),
|
||||
pytest.param(
|
||||
{"oneOf": [{"type": "string"}, {"type": "integer"}]},
|
||||
id="oneOf-string-integer",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("param_schema", UNION_WITH_STRING_SCHEMAS)
|
||||
def test_union_with_string_emits_ok_status(
|
||||
model, renderer_name, renderer, param_schema
|
||||
):
|
||||
"""Union schemas containing ``string`` must yield ``status=OK`` when
|
||||
the model emits a bare string. Pre-fix, ``_coerce_arg_value`` flagged
|
||||
this as ``INVALID_JSON`` because the top-level ``type`` key was
|
||||
absent (the string branch was under ``anyOf`` / ``oneOf``)."""
|
||||
from renderers.base import ToolCallParseStatus
|
||||
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "f",
|
||||
"description": "Test tool with one union-typed parameter.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"x": param_schema},
|
||||
"required": ["x"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
args = {"x": "abc"}
|
||||
msg = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "functions.f:0",
|
||||
"function": {"name": "f", "arguments": args},
|
||||
}
|
||||
],
|
||||
}
|
||||
completion_ids = _extract_assistant_tokens(renderer, PROMPT, msg, tools=tools)
|
||||
parsed = renderer.parse_response(completion_ids, tools=tools)
|
||||
|
||||
assert parsed.tool_calls, f"{model}: parser returned no tool_calls"
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.status == ToolCallParseStatus.OK, (
|
||||
f"{model}: union-with-string schema flagged {tc.status} on bare string"
|
||||
)
|
||||
got = _normalize_args(tc.arguments)
|
||||
assert got == args, (
|
||||
f"{model}: tool-arg drift — sent {args!r}, parser returned {got!r}"
|
||||
)
|
||||
|
||||
@@ -9,9 +9,12 @@ resolution-markers = [
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
|
||||
exclude-newer = "2026-06-19T02:36:32.208558271Z"
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
prime-pydantic-config = false
|
||||
|
||||
[[package]]
|
||||
name = "annotated-doc"
|
||||
version = "0.0.4"
|
||||
@@ -374,11 +377,11 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "3.13"
|
||||
version = "3.15"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ce/cc/762dfb036166873f0059f3b7de4565e1b5bc3d6f28a414c13da27e442f99/idna-3.13.tar.gz", hash = "sha256:585ea8fe5d69b9181ec1afba340451fba6ba764af97026f92a91d4eef164a242", size = 194210, upload-time = "2026-04-22T16:42:42.314Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/82/77/7b3966d0b9d1d31a36ddf1746926a11dface89a83409bf1483f0237aa758/idna-3.15.tar.gz", hash = "sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc", size = 199245, upload-time = "2026-05-12T22:45:57.011Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5d/13/ad7d7ca3808a898b4612b6fe93cde56b53f3034dcde235acb1f0e1df24c6/idna-3.13-py3-none-any.whl", hash = "sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3", size = 68629, upload-time = "2026-04-22T16:42:40.909Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1041,6 +1044,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/80/6e/4b28b62ecb6aae56769c34a8ff1d661473ec1e9519e2d5f8b2c150086b26/pre_commit-4.6.0-py2.py3-none-any.whl", hash = "sha256:e2cf246f7299edcabcf15f9b0571fdce06058527f0a06535068a86d38089f29b", size = 226472, upload-time = "2026-04-21T20:31:40.092Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-pydantic-config"
|
||||
version = "0.3.0.dev83"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b3/4e/bcdb244336d3abae60c7767626aaf635ef724bdc3f2cb46e317d11b23d91/prime_pydantic_config-0.3.0.dev83.tar.gz", hash = "sha256:7446e6439ba6de2f2c332acb292ba5b53da7c1a4ad60e4a25b78393b17859fdd", size = 73322, upload-time = "2026-05-24T02:58:49.485Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/1a/6b/372380c6f5cc3a6f0b6690acb453e9aa9d848e8c1ec421e883c1c3c7a293/prime_pydantic_config-0.3.0.dev83-py3-none-any.whl", hash = "sha256:91a8d883181aff069a4a07f56b636c399c32f1814d8177b9e167a8398643e313", size = 26259, upload-time = "2026-05-24T02:58:48.432Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pydantic"
|
||||
version = "2.13.3"
|
||||
@@ -1340,6 +1355,7 @@ dependencies = [
|
||||
{ name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "openai" },
|
||||
{ name = "openai-harmony" },
|
||||
{ name = "prime-pydantic-config" },
|
||||
{ name = "tiktoken" },
|
||||
{ name = "transformers" },
|
||||
]
|
||||
@@ -1361,7 +1377,8 @@ requires-dist = [
|
||||
{ name = "jinja2" },
|
||||
{ name = "numpy" },
|
||||
{ name = "openai", specifier = ">=1.108.1" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.8" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.4" },
|
||||
{ name = "prime-pydantic-config", specifier = ">=0.3.0.dev83" },
|
||||
{ name = "tiktoken" },
|
||||
{ name = "transformers", specifier = ">=4.50.0" },
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user