Compare commits

..
Author SHA1 Message Date
Konstantin DunasandGitHub d476cc4a30 fix: align parsing with live template continuations (#187)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-10-12 22:38:25 +02:00
Konstantin DunasandGitHub 41f9290949 feat: expose resolved renderer prefix stability (#184) 2026-10-09 11:44:38 +02:00
Konstantin DunasandGitHub 376f54fb34 Require Python 3.11 and adopt native typing and diagnostics (#186) 2026-10-09 11:34:04 +02:00
Konstantin DunasandGitHub e3ace55754 feat: select SFT messages using renderer-owned token attribution (#181) 2026-10-09 00:32:05 +02:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
a3bc9d61af build(deps): bump fsspec from 2026.2.0 to 2026.6.0 (#179)
Bumps [fsspec](https://github.com/fsspec/filesystem_spec) from 2026.2.0 to 2026.6.0.
- [Commits](https://github.com/fsspec/filesystem_spec/compare/2026.2.0...2026.6.0)

---
updated-dependencies:
- dependency-name: fsspec
  dependency-version: 2026.6.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-08 02:37:07 +02:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
802f461514 build(deps): bump virtualenv from 21.3.0 to 21.7.13 (#178)
Bumps [virtualenv](https://github.com/pypa/virtualenv) from 21.3.0 to 21.7.13.
- [Release notes](https://github.com/pypa/virtualenv/releases)
- [Changelog](https://github.com/pypa/virtualenv/blob/main/docs/changelog.rst)
- [Commits](https://github.com/pypa/virtualenv/compare/21.3.0...21.7.13)

---
updated-dependencies:
- dependency-name: virtualenv
  dependency-version: 21.7.13
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-08 01:58:59 +02:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
82e7791c93 build(deps): bump urllib3 from 2.7.0 to 2.8.0 (#173)
Bumps [urllib3](https://github.com/urllib3/urllib3) from 2.7.0 to 2.8.0.
- [Release notes](https://github.com/urllib3/urllib3/releases)
- [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst)
- [Commits](https://github.com/urllib3/urllib3/compare/2.7.0...2.8.0)

---
updated-dependencies:
- dependency-name: urllib3
  dependency-version: 2.8.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-08 01:58:04 +02:00
xianzheng shanandGitHub 64de599850 Fix Qwen3.8 user-query detection for structured text content (#169) 2026-10-02 21:46:11 +02:00
Mika SenghaasandGitHub d43c43015a feat: load custom renderers from local modules and files (#168) 2026-10-01 23:02:10 +02:00
eligottsandGitHub cde869941c fix: request deferred multimodal prompt metadata (#164) 2026-09-28 18:40:21 -07:00
HubertandGitHub 20f2b380c0 fix: treat tool-call openers as implicit reasoning ends (vLLM 0.26 parity) (#158) 2026-09-24 00:22:11 +02:00
f334a9a356 Fix Qwen3 rendering for ACP/OpenAI text content lists (#160)
Co-authored-by: hallerite <git@hallerite.com>
2026-09-23 23:49:56 +02:00
Biswa PandaandGitHub 4393729c90 feat(nemotron): support Nemotron 3.5 Super VLM rendering (#159) 2026-09-23 23:20:51 +02:00
dependabot[bot]andGitHub cbbe57afcd build(deps): bump anyio from 4.13.0 to 4.14.2 (#157) 2026-09-22 20:04:55 +02:00
samsjaandGitHub 670f450dff feat: add GLM-5.3 renderer (#156)
* feat: add GLM-5.3 renderer

* fix: preserve GLM-5.3 offsetless content masks

* style: format GLM-5.3 renderer changes
2026-09-18 15:32:47 -07:00
41f93f278e Support Python 3.14 (#155)
* Support Python 3.14

* ci: test on Python 3.14

---------

Co-authored-by: hallerite <git@hallerite.com>
2026-09-17 14:10:37 +02:00
Konstantin DunasandGitHub c21fc8fe22 fix: preserve unfinished reasoning across renderers and bridges (#152) 2026-09-11 01:17:42 +02:00
Konstantin DunasandGitHub 06bcf635f4 fix: preserve generate endpoint usage metadata (#151) 2026-09-05 20:14:34 +02:00
Mika SenghaasandGitHub f91c3e7061 feat: parse vLLM's native sampling_mask field (#144) 2026-09-01 23:30:24 +02:00
eligottsandGitHub 6797a2d8f2 Add raw multimodal content parts support (#133) 2026-08-31 23:11:34 +02:00
Konstantin DunasandGitHub 9b47901de1 Unify renderer template parity coverage (#127)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-08-31 18:40:19 +02:00
Konstantin DunasandGitHub 5d5027457a feat: add DeepSeek V4 Flash 0731 renderer (#140) 2026-08-31 15:10:47 +02:00
Konstantin DunasandGitHub c4772ac132 feat: support offsetless BYO tokenizers (#142) 2026-08-28 17:28:09 -07:00
Konstantin DunasandGitHub ef49eb9d57 feat: make transformers optional (#31) (#70)
* feat: make transformers optional

* test: cover text-only Inkling without transformers

* test: drop dedicated no-transformers coverage

* deprecate renderer pool APIs

* docs: remove renderer pool guidance

* remove renderer pool APIs

* remove final renderer pool reference
2026-08-28 23:32:36 +02:00
Benjamin ClaviéandGitHub 32e6622f16 feat: add Qwen3.8 Flash Next renderer (#141) 2026-08-28 17:47:04 +02:00
Konstantin DunasandGitHub cb82439137 ci: bump pypa/gh-action-pypi-publish to v1.14.2 for metadata 2.5 (#135)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-08-24 20:16:36 +02:00
Konstantin DunasandGitHub 1a5bd3be3f feat: add Qwen3.8 27B renderer (#130) 2026-08-20 21:23:10 +02:00
halleriteandGitHub c35f506b63 Enforce explicit chat-template kwarg allowlists (#126) 2026-08-12 20:47:07 +02:00
f9b37b6204 feat(renderers): add Inkling and Inkling-Small (#103)
* feat(renderers): add Inkling renderer (text + image + audio)

Implement InklingRenderer for thinkingmachines/Inkling — a token-delimited
vision+audio model whose chat template is a flat stream of role-tagged,
<|end_message|>-terminated blocks (no BOS) with a one-off "Thinking effort
level: {N}" system line and <|content_model_end_sampling|> as the assistant
close/eos.

- Text / tools / reasoning / reasoning_effort: byte-parity with
  apply_chat_template across all shapes (effort labels + raw floats, tool
  cycles, multi-tool-call, content=None, tool-name resolution via
  tool_call_id).
- Image + audio: byte-parity with the native InklingProcessor, including the
  Qwen-VL-style placeholder expansion (image -> num_patches image pads, audio
  -> one audio pad per mel frame); ships pixel_values / audio_input_ids in
  MultiModalData with exact placeholder anchoring.
- Full parse_response (native-JSON tool args, types preserved) and
  bridge_to_next_turn (mm carry-forward; refuses tool messages needing
  cross-turn name resolution).

The InklingProcessor is native in transformers >= 5.14 (merged upstream
2026-07-15), so it loads without trust_remote_code. Bump the transformers
floor to >=5.14.0 and fast-track it past the 7-day uv exclude-newer cooldown
(drop the fast-track once 5.14.x clears the window). The full existing suite
was re-validated on 5.14.1 with no regressions.

Wiring: InklingRendererConfig (reasoning_effort str|float, validated),
MODEL_RENDERER_MAP, MULTIMODAL_MODELS={"image","audio"}, registry, __init__
exports. Tests: tests/test_inkling.py plus Inkling rows in the shared
render/config-parity/multimodal matrices (extended with an "inkling" family
and an audio modality kit). Docs updated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* style(renderers): trim narrative comments on Inkling wiring

Condense the verbose rationale comments added with the Inkling renderer
(MODEL_RENDERER_MAP / MULTIMODAL_MODELS entries, INKLING_EFFORT_MAP, the
transformers pin, and the shared-test rows) to terse one-liners matching
the surrounding style. Comments only — no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(inkling): address Bugbot review — bridge mutation + audio hash

- bridge_to_next_turn copied only the outer mm_data dicts, so appending a
  carried-forward modality's items mutated the caller's
  previous_multi_modal_data lists in place. Copy the per-modality lists too.
  Adds a regression test (test_inkling_bridge_does_not_mutate_prior_mm_data).
- _audio_hash now folds in the sampling rate, so mm_hashes["audio"] uniquely
  identifies the clip (matching the processor cache key); identical samples
  at different rates no longer collide as media IDs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(inkling): support Inkling-Small

* fix(inkling): address compatibility review

* fix(inkling): load input_image content parts

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-12 20:46:53 +02:00
f770dcaa36 Add Gemma 4 renderer (#123)
* Add Gemma 4 renderer

* Fix multimodal processor loading in CI

* Fix Gemma 4 post-tool thinking parsing

* fix(gemma4): classify media content parts before text

`_emit_content` dispatched on `"text" in item` before `_is_image_part`.
HF Arrow schema unification (`Dataset.from_list` over a heterogeneous
content list) adds `text: None` to every image part, so any image that
round-tripped through a dataset took the text branch, emitted nothing,
and never expanded its soft tokens. Reorder to media-first, matching
`qwen35.py` and `kimi_k25.py`.

Two adjacent instances of the same hazard:

- `_emit_tool_response_body` was safe from the zombie key (strict
  `== "text"`) but silently dropped *untyped* text parts; align it on
  the same dispatch order and text acceptance.
- the system-content text-only guard accepted a schema-unified image
  part via `"text" in item` and emitted a stray space instead of
  raising; reject media parts explicitly.

Normalizing each part to `dict` also lets `_is_image_part` (which
requires `isinstance(item, dict)`) see Mapping-but-not-dict parts,
which `_emit_content` otherwise accepts.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(gemma4): address renderer stability review

* test(gemma4): carve out intentional template deviation

* fix(gemma4): preserve post-tool token identity

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 20:46:36 +02:00
minh hoangandGitHub 672aa3c0fb Merge pull request #111 from PrimeIntellect-ai/feature/laguna-s-2.1-route
feat(laguna): add poolside/Laguna-S-2.1 support via a dedicated renderer
2026-08-11 13:05:18 -07:00
eexwhyzeeandClaude Opus 5 0348d1f424 refactor(laguna): move LagunaS21Renderer to its own module
Review feedback: S-2.1 didn't belong in laguna_xs2.py. Pure code motion to
renderers/laguna_s21.py, following the qwen35.py -> qwen36.py precedent for a
cross-module renderer subclass. Updated the _LAZY_RENDERERS entry, the
_populate_registry import, the config docstring cross-ref, and the test import.

laguna_xs2.py still imports LagunaS21RendererConfig for two config-union
annotations — the base __init__s must accept an S-2.1 config forwarded up
through super().

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 12:55:45 -07:00
eexwhyzee 53dea3d35f less yapping 2026-08-11 12:47:22 -07:00
eexwhyzeeandClaude Opus 5 15702bc169 docs(laguna): list S-2.1 in the renderer config tables
The renderer/config landed in the previous commit but was missing from the
user-facing listings, which now cover its sibling M.1 (#120): the README
renderer roster, the per-renderer config table, and the thinking_retention
default table.

`LagunaS21RendererConfig.template_field_names()` is
{enable_thinking, preserve_thinking}, and the renderer inherits XS.2's
``all`` retention default, so it joins that row.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 12:30:19 -07:00
eexwhyzeeandClaude Opus 4.8 fc643aa189 fix(laguna): give Laguna-S-2.1 its own renderer for its distinct template
The initial routing (cdc158e) assumed S-2.1 shipped a byte-identical chat
template to XS-2.1 and reused LagunaXS21Renderer. It doesn't: S-2.1 shares
XS-2.1's tokenizer (same vocab/merges/special tokens) but its template
defaults enable_thinking to True (XS-2.1 defaults False) and adds a
preserve_thinking kwarg, widening the reasoning-display gate to
`enable_thinking or preserve_thinking`. Reusing the XS-2.1 renderer mismatched
apply_chat_template on the default flag (bare `</think>` vs empty
`<think></think>` wrapper), failing test_render_ids / test_build_helpers.

The config-parity barrage missed this because it always sets enable_thinking
explicitly, never exercising the differing default.

Add LagunaS21RendererConfig (enable_thinking=True, preserve_thinking=False) and
LagunaS21Renderer, a thin LagunaXS21Renderer subclass that overrides only the
reasoning-display gate. Route poolside/Laguna-S-2.1 to it. The token format is
otherwise identical, so everything else is inherited.

Verified token-exact against apply_chat_template for all enable_thinking ×
preserve_thinking combinations; added tests/test_laguna_s21.py for the
S-2.1-specific behaviours the shared barrage can't reach.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 12:29:47 -07:00
eexwhyzee 4504d2ea55 feat(laguna): route poolside/Laguna-S-2.1 to the XS-2.1 renderer
S-2.1 is a larger sibling of XS-2.1 (48 layers, hidden 3072, top-10 of
256 experts) but ships a byte-identical chat_template.jinja and tokenizer
(same special tokens/ids, same vocab). It reuses LagunaXS21Renderer via an
exact-match MODEL_RENDERER_MAP entry; no new renderer/config/parser needed.

Added to the shared render-parity matrices (config-parity, is_content,
sampled_mask); token-exact parity against apply_chat_template verified for
both enable_thinking polarities across all conversation shapes.
2026-08-11 12:29:47 -07:00
minh hoangandGitHub 2846a3dcd2 Merge pull request #124 from PrimeIntellect-ai/feat/nemotron-3.5-renderer
feat: add Nemotron 3.5 (Lightning) renderer
2026-08-11 11:42:51 -07:00
eexwhyzee d01817d551 chore: drop NVFP4 map entry, BF16 only 2026-08-11 11:34:53 -07:00
eexwhyzee c0bdb17318 feat: add Nemotron 3.5 (Lightning) renderer 2026-08-11 11:25:22 -07:00
rasdaniandGitHub 2a7e77eb14 feat: add Laguna M.1 renderer (#120) 2026-08-07 05:31:36 -07:00
Matej SirovatkaandGitHub d4707862ac fix(client): update vLLM token serving import (#115)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-07-30 21:48:33 +02:00
5fdf78c30e fix(parsing): validate GLM tool names against the provided tools list (#114)
vLLM 0.24 re-aliased "glm45" from the lenient Glm4MoeModelToolParser to
Glm47MoeModelToolParser, whose engine runs with validate_tool_names=True
(vllm/parser/glm47_moe.py:171): a completed <tool_call> block whose name
isn't in the request's tool list is silently dropped — no tool call is
emitted and the response reads as a voluntary stop. parse_glm stayed
lenient, so train-side parsing (renderer client) disagreed with what an
OpenAI chat-completions eval client sees from the engine: unknown-name
and missing-<arg_key> blocks kept episodes alive in train but killed
them in eval.

Mirror the >=0.24 semantics: when tools is passed, a parsed call whose
name isn't declared gets the new status UNKNOWN_TOOL instead of OK. The
attempt stays visible on parsed.tool_calls (unlike vLLM's silent drop)
for verifier / RL-loss consumers, but the client-side stop->tool_calls
finish-reason promotion no longer fires, matching the engine. Without
tools there is no validation, exactly like vLLM's
ParserEngine._is_valid_tool_name on tool-less requests.

Cross-validated end-to-end against the real vLLM v0.23.0 and v0.24.0
parsers (vendored from the release tags) on identical completions:
before, the renderer matched 0.23's leniency and diverged from 0.24 on
unknown-name and missing-arg_key blocks; after, all cases match 0.24.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 15:53:31 -07:00
dependabot[bot]andGitHub e528e5a70b build(deps): bump setuptools from 81.0.0 to 83.0.0 (#113) 2026-07-26 23:42:05 +02:00
minh hoangandGitHub fe140e3509 Merge pull request #112 from PrimeIntellect-ai/ci/pin-ruff-version
ci(style): pin ruff-action to 0.15.12
2026-07-24 10:35:30 -07:00
eexwhyzeeandClaude Opus 4.8 7c0cea59b4 ci(style): pin ruff-action to 0.15.12
astral-sh/ruff-action@v3 installs the latest ruff release by default. ruff
0.16.0 enabled stricter default rules that flag ~98 pre-existing issues across
the repo, turning previously-green PRs red without any code change (main's last
green Style run was 2026-07-21, before 0.16.0 shipped).

Pin both the lint and format steps to 0.15.12 — the version uv resolves
locally, against which the repo is clean — so CI stops drifting. Bump this
deliberately alongside any lint fixes when adopting a newer ruff.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 10:34:05 -07:00
Maxwill LinandGitHub d1a1c86c44 fix(client): reject malformed sampled-token evidence (#108) 2026-07-21 14:39:57 +02:00
dependabot[bot]andGitHub 430013243c build(deps-dev): bump torch from 2.11.0 to 2.13.0 (#106) 2026-07-21 14:31:05 +02:00
dependabot[bot]andGitHub 258206cba5 build(deps-dev): bump pillow from 12.2.0 to 12.3.0 (#109) 2026-07-21 14:30:34 +02:00
983901a24b fix(qwen): keep empty think wrapper on historical turns when thinking is disabled (#105)
Co-authored-by: hallerite <git@hallerite.com>
2026-07-17 11:43:54 +02:00
90 changed files with 16483 additions and 4867 deletions
+1 -1
View File
@@ -62,6 +62,6 @@ jobs:
path: dist/
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2
with:
skip-existing: true
+1 -1
View File
@@ -87,4 +87,4 @@ jobs:
path: dist/
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2
+8
View File
@@ -15,9 +15,17 @@ jobs:
uses: actions/checkout@v4
- name: Lint
uses: astral-sh/ruff-action@v3
with:
# Pin the ruff version so CI matches what contributors resolve
# locally. ruff-action defaults to the latest release, which drifts
# (e.g. 0.16.0 enabled stricter rules that flag pre-existing code)
# and turns green PRs red without any code change. Bump this
# deliberately alongside any lint fixes.
version: "0.15.12"
- name: Format
uses: astral-sh/ruff-action@v3
with:
version: "0.15.12"
args: "format --check"
ty:
name: Ty
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
python-version: ["3.11", "3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v4
+163 -23
View File
@@ -10,13 +10,30 @@ Standalone on PyPI, and portable across training and inference stacks (transform
uv add renderers
```
The base install supports text renderers with a bring-your-own tokenizer. Add
the Hugging Face integration for the tokenizer-loading helpers, or the complete
media stack for image/audio rendering:
```bash
uv add 'renderers[transformers]'
uv add 'renderers[multimodal]'
```
A BYO tokenizer must expose `encode`, `decode`, `convert_tokens_to_ids`, and
token IDs such as `eos_token_id`. Character offsets are optional: tokenizers
supporting `return_offsets_mapping=True` also receive precise per-token
`is_content` attribution; without offsets, renderers return `is_content=[]`.
`DefaultRenderer` additionally requires `apply_chat_template`. This includes
text-only Inkling training: `InklingRenderer` loads its Transformers processor
only when image or audio content is actually rendered.
## At a glance
```python
from transformers import AutoTokenizer
from renderers import create_renderer
from renderers.base import load_tokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
tok = load_tokenizer("Qwen/Qwen3-8B") # renderers[transformers]
r = create_renderer(tok) # → Qwen3Renderer (auto-resolved)
prompt_ids = r.render_ids(
@@ -26,10 +43,47 @@ prompt_ids = r.render_ids(
# Feed prompt_ids to a Token-In, Token-Out endpoint.
# It returns completion_ids sampled by the model.
parsed = r.parse_response(completion_ids)
parsed = r.parse_response(completion_ids, prompt_ids=prompt_ids)
# ParsedResponse(content=..., reasoning_content=..., tool_calls=...)
```
Pass the exact sampling `prompt_ids` into `parse_response` to identify reasoning
opened by the generation prompt. Without its closing marker, the sampled text
stays in `reasoning_content`, with empty `content` and no executable tool calls,
even if the engine reports `stop`. This applies to every supported reasoning
format, including Harmony analysis and Gemma's post-tool thought channel.
Omitting `prompt_ids`, passing `None`, and passing `[]` all parse the completion
as self-contained: reasoning needs its own initial opener or channel header.
Generation settings never supply missing parsing context. If the prompt supplied
the opener, pass that prompt; `generate` does this automatically.
Where vLLM 0.26's parser does the same, the format's atomic tool-call opener
also ends reasoning that has no closing marker: Qwen3 / Qwen3-VL / Qwen3.5+,
Prime-Qwen3, Nemotron-3, GLM, MiniMax-M2, DeepSeek-V4, Kimi-K2 / K2.5, Gemma 4,
and Inkling. The call parses normally, and `bridge_to_next_turn` extends it
without inserting a close. A closing marker later in the completion still wins:
tool markup before it stays reasoning. Inkling ends thinking and tool segments
with the same `<|end_message|>`, so there the first opener decides.
For reasoning-first formats, only an initial `<think>` (after any assistant
header) or reasoning already opened in the prompt starts reasoning. After its
first closing marker, the rest is content. Later think markers remain literal
content: `Before<think>example</think>After` is entirely content. Harmony,
Gemma, and Inkling follow their explicit channel or message-segment grammar.
`ParsedResponse.reasoning_complete` is `False` while a reasoning channel is open,
`True` when it is closed (or the format has no reasoning channel), and `None` when
its state cannot be determined. It does not certify tool syntax, normal engine
termination, nonempty final output, or task success. The generate client forwards
this narrow signal and passes prompt context automatically. Custom renderers used
with `generate` should accept `parse_response(..., tools=None, prompt_ids=None)`;
formats that do not need prompt context can ignore it.
Summary consumers should require normal termination (`finish_reason="stop"`),
nonempty final content, and no tool calls. A length-limited final answer remains
truncated even when its reasoning channel is closed. Keep rejected attempts in
usage/training accounting, and replace conversation history only after acceptance.
For the next turn, extend the previous sampled stream instead of re-rendering history:
```python
@@ -40,12 +94,14 @@ next_prompt_ids = r.bridge_to_next_turn(
)
```
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `deepseek-r1`, `kimi-k2`, `kimi-k2.5` / `kimi-k2.6`, `nemotron-3`, `nemotron-3-ultra`, `llama-3`, `gpt-oss`, `hy3`, and `prime-qwen3`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `qwen3.8`, `gemma4`, `glm-5`, `glm-5.1`, `glm-5.3`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `deepseek-r1`, `deepseek-v4` (V4 Flash 0731), `kimi-k2`, `kimi-k2.5` / `kimi-k2.6`, `laguna-xs.2`, `laguna-xs-2.1`, `laguna-s-2.1`, `laguna-m.1`, `nemotron-3`, `nemotron-3-ultra`, `nemotron-3.5`, `llama-3`, `gpt-oss`, `hy3`, `inkling` / `inkling-small`, and `prime-qwen3`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper. `qwen3-vl`, `qwen3.5`, `qwen3.6`, `qwen3.8`, `gemma4`, `kimi-k2.5` / `kimi-k2.6`, and the Inkling checkpoints are multimodal (Inkling handles both image **and** audio).
## API
```python
class Renderer(Protocol):
@property
def is_prefix_stable(self) -> bool: ...
def render(messages, *, tools=None, add_generation_prompt=False) -> RenderedTokens: ...
def render_ids(messages, *, tools=None, add_generation_prompt=False) -> list[int]: ...
def parse_response(token_ids) -> ParsedResponse: ...
@@ -53,18 +109,49 @@ class Renderer(Protocol):
def bridge_to_next_turn(prev_prompt_ids, prev_completion_ids, new_messages, *, tools=None) -> list[int] | None: ...
```
- `RenderedTokens` carries `token_ids` **and** `message_indices` — one entry per token attributing each to its source message (`-1` for structural scaffolding). Lets `build_training_sample` build a per-token loss mask in one render.
- `RenderedTokens` carries `token_ids` **and** `message_indices` — one entry per token attributing each to its owning message (`-1` for structural scaffolding). Sampled closing markers belong to their assistant, including GLM markers emitted at the next user/tool boundary; user/tool bodies keep their own ownership.
- `build_training_sample(..., message_loss_mask=[0, 0, 0, 1])` keeps all messages as context but restricts loss to selected messages. Supply one boolean or integer `0`/`1` per message, or `None` for the normal mask. Excluding an assistant also excludes its closing token. Selection never enables targets disabled by the existing role/content settings or changes token IDs.
- `ParsedResponse` is `(content, reasoning_content, tool_calls)`. It scans token ids for special-token boundaries (e.g. id `151657` for `<tool_call>` on Qwen3) — a literal `"<tool_call>"` in user content tokenizes to ordinary text ids and never matches.
- Round-trip: rendering `[user, assistant(content, reasoning, tool_calls)]`, slicing the assistant completion, and feeding it through `parse_response` returns an equivalent structured message. Tested per-renderer in `tests/test_roundtrip.py`.
### Prefix stability
`renderer.is_prefix_stable` describes the constructed renderer after config and
`chat_template_kwargs` resolution. A `True` value guarantees that full renders
of assistant-terminated conversations stay token prefixes when more
user/tool/assistant messages are appended, with a fixed system/developer
preamble, tools, and `add_generation_prompt=False`. `False` means this is not
guaranteed; opaque `DefaultRenderer` templates report `False`.
The flag follows the template's emit rules, independently of the
`thinking_retention` bridge override. For example, GLM-5 with
`clear_thinking=False` is stable, while the default strips earlier reasoning.
Disabling thinking generation alone does not guarantee stability for datasets
that already contain reasoning. Other causes include GPT-OSS's final-turn
terminator and Nemotron's moving effort hint. DeepSeek V4 reports `False`
because its task/continuation message controls can rewrite the prefix; Inkling
reports `False` because reused tool-call IDs can change earlier tool-response
names, even though it retains reasoning.
SFT consumers can use this flag to warn that a single full-conversation render
may omit earlier reasoning. `build_training_sample` still returns one sample
per conversation, without expanding it into one sample per assistant turn.
The guarantee assumes unchanged message contents and deterministic tokenization
and media preprocessing. Stability does not guarantee that the template emits
every input field (some always omit reasoning), or that rendering reproduces sampled tokens. Continue
using `bridge_to_next_turn` for sampled trajectories. Custom renderers should
expose the same property; consumers supporting older/custom implementations
can conservatively use `getattr(renderer, "is_prefix_stable", False)`.
### `bridge_to_next_turn` (the core contract)
Given `(prev_prompt_ids, prev_completion_ids)` and new environment messages, return ids for the next turn's prompt such that the result starts with `prev_prompt_ids + prev_completion_ids` byte-for-byte and continues with the new messages plus the next assistant opener. If that cannot be proven safe, return `None` and the caller falls back to a full render.
Each hand-coded bridge:
1. Anchors at the previous turn's canonical close token. On clean stops it's already in `prev_completion_ids`. On truncation, the renderer synthesizes the close as non-loss prompt context.
2. Refuses assistant content in `new_messages` — re-rendering sampled tokens would replace them with canonical template bytes.
3. Renders only the new messages in the framing the model family expects.
1. Checks the previous turn's reasoning state. If reasoning is unfinished and no stop was sampled, append its closing marker as non-loss prompt context before the canonical turn close. If a stop was already sampled inside reasoning, return `None`: inserting a close before it would violate the exact-prefix contract. Parsing never repairs the sampled output.
2. Anchors at the previous turn's canonical close token. On clean stops it's already in `prev_completion_ids`. On truncation, the renderer synthesizes the close as non-loss prompt context.
3. Refuses assistant content in `new_messages` — re-rendering sampled tokens would replace them with canonical template bytes.
4. Renders only the new messages in the framing the model family expects.
`DefaultRenderer.bridge_to_next_turn` returns `None` unconditionally — the template's close is unknown, so the contract can't be proven.
@@ -76,17 +163,10 @@ r = create_renderer(tok) # AutoRendererConfig is the implicit def
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", size=16)
with pool.checkout() as r:
ids = r.render_ids(messages)
```
Each slot owns its own tokenizer copy. Construction fans out across a thread pool so a 32-slot pool doesn't serially eat ~10–15s of `from_pretrained` calls at startup.
Without the `transformers` extra, exact-match registered models still
auto-resolve. For an unknown name, renderers cannot safely probe `AutoConfig`
to distinguish a text model from an unknown VLM; pass an explicit typed config
such as `DefaultRendererConfig()` for a known text-only model.
## Why use a renderer
@@ -109,7 +189,7 @@ Each break fragments a rollout into multiple training samples — every fragment
## Typed renderer configs
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:
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` takes one positional `config` argument and an optional keyword-only `chat_template_kwargs` mapping:
```python
from renderers import (
@@ -143,7 +223,7 @@ renderer = create_renderer(
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.
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.
When `chat_template_kwargs` is passed with `config=None` / `AutoRendererConfig`, renderers first resolves the concrete renderer from the model name, then validates each key against that renderer's explicit template-kwarg allowlist. Renderer-only fields such as `image_cache_max` must be passed through the typed config instead. `Auto + unknown model + chat_template_kwargs` fails loudly; use an explicit typed config or explicit `DefaultRendererConfig` for opaque fallback templates.
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.
@@ -153,13 +233,49 @@ One shared behaviour flag lives on typed renderer configs: `thinking_retention`,
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).
## Custom renderers
A renderer can live outside this package. Point a `custom` config at the class with `import_path`, as `my_module.Class` or `path/to/file.py:Class`; relative file paths resolve against the working directory. The class sets `config_class` to its own `BaseRendererConfig` subclass, which validates every other field of the config and supplies its `chat_template_kwargs` allowlist. For example, a GLM-5.3 renderer whose generation prompt prefills an empty think block, so the model starts at the answer:
```python
from typing import Literal
from renderers.configs import GLM53RendererConfig
from renderers.glm5 import GLM53Renderer
class NoThinkingGLM53Config(GLM53RendererConfig):
name: Literal["glm-5.3-no-thinking"] = "glm-5.3-no-thinking"
class NoThinkingGLM53Renderer(GLM53Renderer):
config_class = NoThinkingGLM53Config
def _emit_generation_prompt(self, emit_special) -> None:
emit_special(self._assistant, -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)
```
```python
from renderers import CustomRendererConfig, create_renderer
config = CustomRendererConfig(
import_path="my_renderers.glm53_no_thinking.NoThinkingGLM53Renderer",
clear_thinking=True,
)
renderer = create_renderer(tokenizer, config)
```
Downstream TOML configs select it the same way, with `name = "custom"` and an `import_path`.
## `DefaultRenderer`
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 expansion.** `ImagePart` support exists for Qwen3-VL and Qwen3.5-family multimodal templates. Remaining work: video support, broader VLM coverage, and more RL validation.
- **VLM expansion.** `ImagePart` support exists for Qwen3-VL, Qwen3.5-family, Gemma 4, and Kimi K2.5 / K2.6 multimodal templates. Install `renderers[multimodal]` for Pillow and the Hugging Face processors. Remaining work: audio/video support, broader VLM coverage, and more RL validation. Gemma 4 image preprocessing requires a Transformers release that provides `Gemma4Processor`.
- **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
@@ -169,7 +285,31 @@ uv sync --group dev
uv run pytest
```
Round-trip parity (render → parse → original) and token-level parity against `apply_chat_template` are tested per renderer. End-to-end validation runs against Reverse-Text, Wordle, OpenCode-Math, and RLM-SWE environments.
Round-trip parity (render → parse → original) and token-level parity against each model's independent reference encoder are tested per renderer. Most references use `apply_chat_template`; DeepSeek V4 uses its shipped Python encoder, and GPT-OSS uses Harmony.
Prefix-stability audit witnesses live in
[`tests/fixtures/prefix_stability.json`](tests/fixtures/prefix_stability.json).
Each case records a renderer/config, a conversation ending in an assistant,
messages to append, and the reason the original tokens stop being a prefix.
Shared scenarios keep the corpus small; paired stable settings guard the
configuration switches. `DefaultRenderer` is treated as unknown, without
inventing a witness for its opaque template.
This audit is opt-in and is not collected by the regular test suite or CI.
Run it manually when changing renderer emission rules or the stability
classification:
```bash
uv run pytest tests/audit_prefix_stability.py -q
```
The tests render both inputs and compare the original token IDs with the
same-length prefix of the extended render. They print the first differing
tokens and a decoded text diff on failure. These are executable witnesses,
not snapshots of token IDs that could pass without exercising the renderer.
Add a named case for each new instability mechanism or configuration branch.
A witness disproves stability; finite positive controls do not prove stability
for every possible conversation or third-party tokenizer/processor.
## License
+29 -15
View File
@@ -1,8 +1,7 @@
# 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.
`renderers.RendererConfig` is the typed input to `create_renderer`. It pins the
renderer choice and its config at construction time.
```python
from renderers import create_renderer, Qwen35RendererConfig
@@ -19,9 +18,11 @@ 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`.
Use `type(config).template_field_names()` to inspect the explicit allowlist of
fields accepted through `chat_template_kwargs`. Every renderer-specific field
is classified as either a template field or a renderer-only field at class
definition time. Template fields are covered by the model/scenario/kwarg
product in `tests/test_parity.py`.
| Renderer | Config class | Template fields | Renderer-only fields |
| --- | --- | --- | --- |
@@ -29,21 +30,29 @@ chat-template kwargs. Those fields are covered by parity tests against
| 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.8 | `Qwen38RendererConfig` | `enable_thinking`, `add_vision_id`, `preserve_thinking`, `reasoning_effort` | `image_cache_max` |
| Qwen3-VL | `Qwen3VLRendererConfig` | `add_vision_id` | `image_cache_max` |
| Gemma 4 | `Gemma4RendererConfig` | `enable_thinking`, `preserve_thinking` | `image_cache_max` |
| GLM-5 / 5.1 | `GLM5RendererConfig` / `GLM51RendererConfig` | `enable_thinking`, `clear_thinking` | - |
| GLM-5.3 | `GLM53RendererConfig` | `clear_thinking`, `reasoning_effort` | - |
| 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` |
| Inkling / Inkling-Small | `InklingRendererConfig` | `reasoning_effort` | `image_cache_max`, `audio_cache_max` |
| Laguna XS.2 | `LagunaXS2RendererConfig` | `enable_thinking`, `render_assistant_messages_raw` | - |
| Laguna M.1 | `LagunaM1RendererConfig` | `enable_thinking`, `render_assistant_messages_raw` | - |
| Laguna XS-2.1 | `LagunaXS21RendererConfig` | `enable_thinking` | - |
| Laguna S-2.1 | `LagunaS21RendererConfig` | `enable_thinking`, `preserve_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` | - |
| Nemotron-3.5 Lightning | `Nemotron35RendererConfig` | `enable_thinking`, `truncate_history_thinking` | - |
| DeepSeek V3 | `DeepSeekV3RendererConfig` | - | - |
| DeepSeek R1 | `DeepSeekR1RendererConfig` | - | - |
| DeepSeek V4 Flash 0731 | `DeepSeekV4RendererConfig` | `enable_thinking`, `drop_thinking`, `reasoning_effort` | - |
Configs are frozen value objects. To override a field, construct a new instance
or call `config.model_copy(update={...})`.
@@ -69,15 +78,13 @@ 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.
kwargs validate against the concrete renderer's template-field allowlist.
Unknown kwargs, renderer-only fields, or kwargs that conflict with an explicit
`thinking_retention` fail at construction. Renderer-only options remain valid
when supplied through the typed config itself.
Auto-resolution fails loudly for VLMs without an exact registered renderer.
Text-only unknown models fall back to `DefaultRenderer`, unless
@@ -86,7 +93,10 @@ 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.
intentionally want opaque `apply_chat_template` kwargs. Even for the default
renderer, typed fields such as `tool_parser`, `reasoning_parser`, and
`thinking_retention` must be passed through the config rather than through the
opaque kwargs mapping.
## `thinking_retention`
@@ -128,15 +138,19 @@ the knobs its template actually exposes:
| 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` |
| Qwen3.8 | `preserve_thinking=True -> all`; else `enable_thinking=False -> all`; else `tool_cycle` |
| Gemma 4 | `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-5.3 | `clear_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` |
| Nemotron-3 / 3.5 | `truncate_history_thinking=False -> all`; else `enable_thinking=False -> all`; else `tool_cycle` |
| DeepSeek R1 | `template` |
| DeepSeek V4 Flash 0731 | `enable_thinking=False` or `drop_thinking=False -> all`, else `tool_cycle` |
| MiniMax M2 | `tool_cycle` |
| DeepSeek V3, Qwen3-VL, Kimi K2, Laguna XS.2 / XS-2.1, Llama 3 | `all` |
| DeepSeek V3, Qwen3-VL, Kimi K2, Laguna XS.2 / M.1 / XS-2.1 / S-2.1, Llama 3, Inkling | `all` |
| PrimeIntellect Qwen3 | `all` |
Config construction raises when an explicit template knob directly contradicts
+7 -3
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10,<3.14"
# requires-python = ">=3.11,<3.14"
# dependencies = [
# "renderers>=0.1.6",
# "sglang==0.5.10.post1",
@@ -138,7 +138,7 @@ def main() -> None:
)
output1 = engine.generate(input_ids=prompt_ids, sampling_params=sampling)
completion1 = completion_ids(output1, prompt_ids)
parsed1 = renderer.parse_response(completion1)
parsed1 = renderer.parse_response(completion1, prompt_ids=prompt_ids)
print_parsed(label, "turn 1", parsed1)
assistant = {"role": "assistant", "content": parsed1.content}
@@ -197,7 +197,11 @@ def main() -> None:
output2 = engine.generate(input_ids=bridged_ids, sampling_params=sampling)
completion2 = completion_ids(output2, bridged_ids)
print_parsed(label, "turn 2", renderer.parse_response(completion2))
print_parsed(
label,
"turn 2",
renderer.parse_response(completion2, prompt_ids=bridged_ids),
)
engine.shutdown()
+5 -3
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10,<3.14"
# requires-python = ">=3.11,<3.14"
# dependencies = [
# "renderers>=0.1.6",
# "transformers>=5.3.0",
@@ -161,7 +161,7 @@ async def run_one(
max_new_tokens=max_new_tokens,
)
completion1 = completion_ids(output1, prompt_ids)
parsed1 = renderer.parse_response(completion1)
parsed1 = renderer.parse_response(completion1, prompt_ids=prompt_ids)
print_parsed(label, "turn 1", parsed1)
assistant: dict[str, Any] = {"role": "assistant", "content": parsed1.content}
@@ -226,7 +226,9 @@ async def run_one(
max_new_tokens=max_new_tokens,
)
completion2 = completion_ids(output2, bridged_ids)
print_parsed(label, "turn 2", renderer.parse_response(completion2))
print_parsed(
label, "turn 2", renderer.parse_response(completion2, prompt_ids=bridged_ids)
)
async def main() -> None:
+6 -2
View File
@@ -128,7 +128,7 @@ async def main() -> None:
sampling_params=sampling_params,
)
completion1 = list(output1.sequences[0].tokens)
parsed1 = renderer.parse_response(completion1)
parsed1 = renderer.parse_response(completion1, prompt_ids=prompt_ids)
print_parsed(label, "turn 1", parsed1)
assistant = {"role": "assistant", "content": parsed1.content}
@@ -191,7 +191,11 @@ async def main() -> None:
sampling_params=sampling_params,
)
completion2 = list(output2.sequences[0].tokens)
print_parsed(label, "turn 2", renderer.parse_response(completion2))
print_parsed(
label,
"turn 2",
renderer.parse_response(completion2, prompt_ids=bridged_ids),
)
if __name__ == "__main__":
@@ -1,6 +1,6 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10,<3.14"
# requires-python = ">=3.11,<3.14"
# dependencies = [
# "renderers>=0.1.6",
# "transformers>=4.50.0",
@@ -135,7 +135,7 @@ def main() -> None:
pad_token_id=pad_token_id,
)[0]
completion1 = output1[input_ids.shape[-1] :].tolist()
parsed1 = renderer.parse_response(completion1)
parsed1 = renderer.parse_response(completion1, prompt_ids=prompt_ids)
print_parsed(label, "turn 1", parsed1)
assistant = {"role": "assistant", "content": parsed1.content}
@@ -203,7 +203,11 @@ def main() -> None:
pad_token_id=pad_token_id,
)[0]
completion2 = output2[bridged_input_ids.shape[-1] :].tolist()
print_parsed(label, "turn 2", renderer.parse_response(completion2))
print_parsed(
label,
"turn 2",
renderer.parse_response(completion2, prompt_ids=bridged_ids),
)
del hf_model
gc.collect()
+7 -3
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10,<3.14"
# requires-python = ">=3.11,<3.14"
# dependencies = [
# "renderers>=0.1.6",
# "vllm>=0.20",
@@ -131,7 +131,7 @@ def main() -> None:
use_tqdm=False,
)[0]
completion1 = list(output1.outputs[0].token_ids)
parsed1 = renderer.parse_response(completion1)
parsed1 = renderer.parse_response(completion1, prompt_ids=prompt_ids)
print_parsed(label, "turn 1", parsed1)
assistant = {"role": "assistant", "content": parsed1.content}
@@ -194,7 +194,11 @@ def main() -> None:
use_tqdm=False,
)[0]
completion2 = list(output2.outputs[0].token_ids)
print_parsed(label, "turn 2", renderer.parse_response(completion2))
print_parsed(
label,
"turn 2",
renderer.parse_response(completion2, prompt_ids=bridged_ids),
)
del llm
gc.collect()
+23 -3
View File
@@ -13,13 +13,12 @@ description = "Chat template renderers — deterministic message-to-token conver
readme = "README.md"
license = "Apache-2.0"
license-files = ["LICENSE"]
requires-python = ">=3.10,<3.14"
requires-python = ">=3.11,<3.15"
dependencies = [
"numpy",
"openai>=1.108.1",
"tiktoken",
"jinja2",
"transformers>=4.50.0",
# 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.
@@ -28,7 +27,7 @@ dependencies = [
# 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,
# against 0.0.8) and the Harmony cells in ``tests/test_parity.py`` pass,
# so the older harmony is safe.
"openai-harmony>=0.0.4",
# ``BaseRendererConfig`` inherits from ``pydantic_config.BaseConfig`` so
@@ -38,6 +37,25 @@ dependencies = [
"prime-pydantic-config>=0.3.0.dev83",
]
[project.optional-dependencies]
# Tokenizer loading uses Hugging Face. Text-only renderers can instead be
# constructed with a compatible BYO tokenizer and do not import this
# dependency. Character offsets are optional.
transformers = [
# Keep this floor compatible with prime-rl's transformers pin. Inkling's
# tokenizer and text-only renderer work on older releases; image/audio
# processing fails lazily with an upgrade message when InklingProcessor is
# unavailable (native support starts in transformers 5.14).
"transformers>=4.50.0",
]
# Image/audio renderers also need Pillow to resolve media inputs. Keep this as
# a separate convenience extra so tokenizer-only users do not pull it in.
multimodal = [
"pillow>=12.2.0",
"transformers>=4.50.0",
]
[tool.hatch.version]
source = "vcs"
# Tags look like ``renderers-v0.1.8`` (prefix matches the publish.yml
@@ -86,6 +104,8 @@ dev = [
"torch>=2.11.0",
"torchvision>=0.26.0",
"ty>=0.0.1a29,<0.0.22",
# Optional for consumers, but required by tokenizer/parity/VLM tests.
"transformers>=4.50.0",
]
[tool.uv]
+64 -23
View File
@@ -7,13 +7,15 @@ except ImportError:
__version__ = "0+unknown"
from renderers.base import (
MULTIMODAL_MODELS,
ChatTemplateTokenizer,
Content,
ContentPart,
ImagePart,
MULTIMODAL_MODELS,
Message,
MultiModalData,
MultimodalRenderer,
OffsetTokenizer,
ParsedResponse,
ParsedToolCall,
PlaceholderRange,
@@ -21,9 +23,9 @@ from renderers.base import (
RenderedTokens,
RenderedTrainingSample,
Renderer,
RendererPool,
TextPart,
ThinkingPart,
Tokenizer,
ToolCall,
ToolCallFunction,
ToolCallParseStatus,
@@ -33,72 +35,87 @@ from renderers.base import (
build_training_sample,
build_trajectory_step,
create_renderer,
create_renderer_pool,
extract_message_tool_names,
is_multimodal,
merge_chat_template_kwargs,
reject_assistant_in_extension,
template_field_names,
trim_to_turn_close,
)
from renderers.client import OverlongPromptError
from renderers.client import MalformedGenerateResponseError, OverlongPromptError
from renderers.configs import (
AutoRendererConfig,
BaseRendererConfig,
config_from_name,
DefaultRendererConfig,
CustomRendererConfig,
DeepSeekR1RendererConfig,
DeepSeekV3RendererConfig,
DeepSeekV4RendererConfig,
DefaultRendererConfig,
Gemma4RendererConfig,
GLM5RendererConfig,
GLM45RendererConfig,
GLM51RendererConfig,
GLM5RendererConfig,
GLM53RendererConfig,
GptOssRendererConfig,
Hy3RendererConfig,
KimiK25RendererConfig,
InklingRendererConfig,
KimiK2RendererConfig,
KimiK25RendererConfig,
LagunaM1RendererConfig,
LagunaS21RendererConfig,
LagunaXS2RendererConfig,
LagunaXS21RendererConfig,
Llama3RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
Nemotron35RendererConfig,
PrimeQwen3RendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen3RendererConfig,
Qwen3VLRendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen38RendererConfig,
RendererConfig,
config_from_name,
)
from renderers.custom import custom_renderer_config, load_custom_renderer, load_target
# 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.
# Concrete renderer classes are lazy-loaded so that consumers needing only the
# config layer (``RendererConfig`` discriminated union) don't import every
# renderer module. Renderer tokenizer annotations use the local ``Tokenizer``
# protocols, so resolving a text renderer remains safe when the optional
# ``transformers`` dependency is absent. ``__getattr__`` (PEP 562) resolves the
# names on first attribute access, while ``renderers.base._populate_registry``
# handles lazy registration for ``create_renderer``.
_LAZY_RENDERERS: dict[str, str] = {
"DeepSeekR1Renderer": "renderers.deepseek_r1",
"DeepSeekV3Renderer": "renderers.deepseek_v3",
"DeepSeekV4Renderer": "renderers.deepseek_v4",
"DefaultRenderer": "renderers.default",
"GLM45Renderer": "renderers.glm45",
"GLM51Renderer": "renderers.glm5",
"GLM53Renderer": "renderers.glm5",
"GLM5Renderer": "renderers.glm5",
"GptOssRenderer": "renderers.gpt_oss",
"Gemma4Renderer": "renderers.gemma4",
"Hy3Renderer": "renderers.hy3",
"InklingRenderer": "renderers.inkling",
"KimiK25Renderer": "renderers.kimi_k25",
"KimiK2Renderer": "renderers.kimi_k2",
"LagunaM1Renderer": "renderers.laguna_xs2",
"LagunaS21Renderer": "renderers.laguna_s21",
"LagunaXS21Renderer": "renderers.laguna_xs2",
"LagunaXS2Renderer": "renderers.laguna_xs2",
"Llama3Renderer": "renderers.llama_3",
"MiniMaxM2Renderer": "renderers.minimax_m2",
"Nemotron35Renderer": "renderers.nemotron3",
"Nemotron3Renderer": "renderers.nemotron3",
"Nemotron3UltraRenderer": "renderers.nemotron3",
"PrimeQwen3Renderer": "renderers.prime_qwen3",
"Qwen35Renderer": "renderers.qwen35",
"Qwen36Renderer": "renderers.qwen36",
"Qwen38Renderer": "renderers.qwen38",
"Qwen3Renderer": "renderers.qwen3",
"Qwen3VLRenderer": "renderers.qwen3_vl",
}
@@ -122,29 +139,43 @@ def __dir__() -> list[str]:
__all__ = [
"AutoRendererConfig",
"BaseRendererConfig",
"ChatTemplateTokenizer",
"Content",
"ContentPart",
"CustomRendererConfig",
"DeepSeekR1Renderer",
"DeepSeekR1RendererConfig",
"DeepSeekV3Renderer",
"DeepSeekV3RendererConfig",
"DeepSeekV4Renderer",
"DeepSeekV4RendererConfig",
"DefaultRenderer",
"DefaultRendererConfig",
"GLM45Renderer",
"GLM45RendererConfig",
"GLM51Renderer",
"GLM51RendererConfig",
"GLM53Renderer",
"GLM53RendererConfig",
"GLM5Renderer",
"GLM5RendererConfig",
"Gemma4Renderer",
"Gemma4RendererConfig",
"GptOssRenderer",
"GptOssRendererConfig",
"Hy3Renderer",
"Hy3RendererConfig",
"ImagePart",
"InklingRenderer",
"InklingRendererConfig",
"KimiK25Renderer",
"KimiK25RendererConfig",
"KimiK2Renderer",
"KimiK2RendererConfig",
"LagunaM1Renderer",
"LagunaM1RendererConfig",
"LagunaS21Renderer",
"LagunaS21RendererConfig",
"LagunaXS2Renderer",
"LagunaXS2RendererConfig",
"LagunaXS21Renderer",
@@ -152,15 +183,19 @@ __all__ = [
"Llama3Renderer",
"Llama3RendererConfig",
"MULTIMODAL_MODELS",
"MalformedGenerateResponseError",
"Message",
"MiniMaxM2Renderer",
"MiniMaxM2RendererConfig",
"MultiModalData",
"MultimodalRenderer",
"Nemotron35Renderer",
"Nemotron35RendererConfig",
"Nemotron3Renderer",
"Nemotron3RendererConfig",
"Nemotron3UltraRenderer",
"Nemotron3UltraRendererConfig",
"OffsetTokenizer",
"OverlongPromptError",
"ParsedResponse",
"ParsedToolCall",
@@ -171,6 +206,8 @@ __all__ = [
"Qwen35RendererConfig",
"Qwen36Renderer",
"Qwen36RendererConfig",
"Qwen38Renderer",
"Qwen38RendererConfig",
"Qwen3Renderer",
"Qwen3RendererConfig",
"Qwen3VLRenderer",
@@ -180,9 +217,9 @@ __all__ = [
"RenderedTrainingSample",
"Renderer",
"RendererConfig",
"RendererPool",
"TextPart",
"ThinkingPart",
"Tokenizer",
"ToolCall",
"ToolCallFunction",
"ToolCallParseStatus",
@@ -194,9 +231,13 @@ __all__ = [
"build_trajectory_step",
"config_from_name",
"create_renderer",
"create_renderer_pool",
"custom_renderer_config",
"extract_message_tool_names",
"is_multimodal",
"load_custom_renderer",
"load_target",
"merge_chat_template_kwargs",
"reject_assistant_in_extension",
"template_field_names",
"trim_to_turn_close",
]
+477 -271
View File
File diff suppressed because it is too large Load Diff
+321 -64
View File
@@ -1,12 +1,7 @@
"""Renderer-based generate client for vLLM 0.20's /inference/v1/generate.
"""Renderer-based generate client for vLLM's /inference/v1/generate.
messages → Renderer.render_ids() → token IDs → POST /inference/v1/generate
→ completion tokens → Renderer.parse_response() → structured message
When a RendererPool is passed instead of a single Renderer, the sync tokenization
and parsing work is offloaded to threads for parallel execution across rollouts.
HuggingFace fast tokenizers release the GIL during Rust encoding, so threads
achieve real parallelism.
messages → Renderer.render_ids() → token IDs → POST /inference/v1/generate
→ completion tokens → Renderer.parse_response() → structured message
"""
from __future__ import annotations
@@ -14,6 +9,7 @@ from __future__ import annotations
import asyncio
import json
import logging
import math
from collections.abc import Mapping
from typing import Any, cast
@@ -25,14 +21,16 @@ from renderers.base import (
MultiModalData,
RenderedTokens,
Renderer,
RendererPool,
ToolCallParseStatus,
ToolSpec,
_require_transformers,
)
_request_logger = logging.getLogger("renderers.client")
ROUTED_EXPERTS_DATA_PREFIX = b'"routed_experts":{"data":"'
KEPT_TOKENS_IDS_PREFIX = b'"kept_tokens":{"ids":"'
# vLLM uses this value both when sampled-token evidence is missing and as a
# lower-bound clamp, so receiving it cannot prove the real logprob was returned.
VLLM_LOGPROB_SENTINEL = -9999.0
class OverlongPromptError(Exception):
@@ -54,11 +52,14 @@ class OverlongPromptError(Exception):
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})."
f"Prompt length ({prompt_len}) exceeds maximum context length ({max_prompt_len})."
)
class MalformedGenerateResponseError(ValueError):
"""The generate endpoint returned unusable sampled-token evidence."""
# 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
@@ -108,20 +109,6 @@ async def _resolve_max_prompt_len(client: AsyncOpenAI, model: str) -> int | None
return value
async def _maybe_offload(renderer: Renderer | RendererPool, fn):
"""Run sync renderer work on a thread iff ``renderer`` is a pool.
A pool's methods can block on its internal queue/lock (size>1 / size=1
fast path respectively), so we ``asyncio.to_thread`` to avoid stalling
the event loop. A bare ``Renderer`` runs inline — used in tests where
event-loop responsiveness isn't a concern and the thread hop would
be pure overhead.
"""
if isinstance(renderer, RendererPool):
return await asyncio.to_thread(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.
@@ -141,19 +128,70 @@ def _strip_base64_field(raw: bytes, prefix: bytes) -> tuple[bytes, memoryview |
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
def _parse_completion_logprobs(
choice: Mapping[str, Any], completion_ids: list[int]
) -> list[float]:
raw_logprobs = choice.get("logprobs")
if not isinstance(raw_logprobs, Mapping):
raise MalformedGenerateResponseError(
"Engine response choice.logprobs must be an object."
)
content = raw_logprobs.get("content")
if not isinstance(content, list):
raise MalformedGenerateResponseError(
"Engine response choice.logprobs.content must be a list."
)
if len(content) != len(completion_ids):
raise MalformedGenerateResponseError(
"Engine response completion token count "
f"({len(completion_ids)}) does not match logprob count ({len(content)})."
)
completion_logprobs: list[float] = []
for index, entry in enumerate(content):
if not isinstance(entry, Mapping):
raise MalformedGenerateResponseError(
f"Engine response choice.logprobs.content[{index}] must be an object."
)
expected_token = f"token_id:{completion_ids[index]}"
if entry.get("token") != expected_token:
raise MalformedGenerateResponseError(
f"Engine response choice.logprobs.content[{index}].token must be {expected_token!r}."
)
raw_logprob = entry.get("logprob")
if isinstance(raw_logprob, bool) or not isinstance(raw_logprob, (int, float)):
raise MalformedGenerateResponseError(
f"Engine response choice.logprobs.content[{index}].logprob must be a number."
)
try:
logprob = float(raw_logprob)
except OverflowError as exc:
raise MalformedGenerateResponseError(
f"Engine response choice.logprobs.content[{index}].logprob must be finite."
) from exc
if not math.isfinite(logprob):
raise MalformedGenerateResponseError(
f"Engine response choice.logprobs.content[{index}].logprob must be finite."
)
if logprob == VLLM_LOGPROB_SENTINEL:
raise MalformedGenerateResponseError(
f"Engine response choice.logprobs.content[{index}].logprob does not contain sampling evidence."
)
completion_logprobs.append(logprob)
return completion_logprobs
async def generate(
*,
client: AsyncOpenAI,
renderer: Renderer | RendererPool,
renderer: Renderer,
messages: list[Message],
model: str,
prompt_ids: list[int] | None = None,
@@ -165,6 +203,7 @@ async def generate(
priority: int | None = None,
extra_headers: dict[str, str] | None = None,
max_prompt_len: int | None = None,
process_multimodal: bool = True,
) -> dict[str, Any]:
"""Tokenize messages, call vLLM /inference/v1/generate, parse the response.
@@ -184,6 +223,9 @@ async def generate(
sidecar, then serializes it to vLLM's ``features`` schema (mm_hashes,
mm_placeholders, kwargs_data) before POSTing. The serializer imports
``vllm.*`` lazily so text-only consumers never pay for the import.
With ``process_multimodal=False``, rendering skips image processing and
the request carries ``content_parts`` with ``return_token_ids=true``;
vLLM returns the expanded prompt and multimodal placeholder ranges.
``max_prompt_len`` controls the pre-flight overflow check. When the
rendered prompt is strictly longer than the cap, the request is never
@@ -194,10 +236,15 @@ async def generate(
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).
Calls with ``process_multimodal=False`` skip this pre-flight because only
vLLM knows the expanded prompt length.
Returns a dict with: request_id, prompt_ids, completion_ids,
completion_logprobs, content, reasoning_content, tool_calls,
finish_reason, routed_experts, multi_modal_data, prompt_attribution.
Returns a dict with: request_id, prompt_ids, renderer_prompt_ids,
mm_placeholders, completion_ids, completion_logprobs, content,
reasoning_content, tool_calls, finish_reason, routed_experts,
multi_modal_data, prompt_attribution. ``renderer_prompt_ids`` is the
unexpanded logical prompt when ``process_multimodal=False`` and ``None``
otherwise.
``prompt_attribution`` is the renderer's :class:`RenderedTokens` for
the prompt — either the one this call computed via
@@ -216,6 +263,12 @@ async def generate(
f"{type(renderer).__name__} does not support tools. "
"Choose a model-specific renderer instead of the default fallback."
)
if not process_multimodal and not getattr(
renderer, "supports_process_multimodal", False
):
raise NotImplementedError(
f"{type(renderer).__name__} does not support process_multimodal=False"
)
def _prepare():
if prompt_ids is not None:
@@ -228,7 +281,15 @@ async def generate(
multi_modal_data,
prompt_attribution,
)
rendered = renderer.render(messages, tools=tools, add_generation_prompt=True)
render_kwargs: dict[str, Any] = {}
if not process_multimodal:
render_kwargs["process_multimodal"] = False
rendered = renderer.render(
messages,
tools=tools,
add_generation_prompt=True,
**render_kwargs,
)
return (
rendered.token_ids,
renderer.get_stop_token_ids(),
@@ -236,16 +297,15 @@ async def generate(
rendered,
)
prompt_ids, stop_token_ids, mm_data, prompt_attr = await _maybe_offload(
renderer, _prepare
)
prompt_ids, stop_token_ids, mm_data, prompt_attr = _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
)
if process_multimodal:
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
@@ -257,11 +317,15 @@ async def generate(
"token_ids": prompt_ids,
"sampling_params": sp,
}
content_parts = _content_parts(messages) if not process_multimodal else None
features = (
_build_mm_features(renderer, mm_data)
if mm_data and not mm_data.is_empty()
if process_multimodal and mm_data and not mm_data.is_empty()
else None
)
if content_parts:
body["content_parts"] = content_parts
body["return_token_ids"] = True
if features is not None:
body["features"] = features
if cache_salt is not None:
@@ -291,18 +355,29 @@ async def generate(
choice = (data.get("choices") or [{}])[0]
completion_ids = choice.get("token_ids") or []
effective_prompt_ids = data.get("prompt_token_ids")
if content_parts and not isinstance(effective_prompt_ids, list):
raise MalformedGenerateResponseError(
"Engine response must include prompt_token_ids when process_multimodal=False."
)
mm_placeholders = data.get("mm_placeholders")
if content_parts and not isinstance(mm_placeholders, dict):
raise MalformedGenerateResponseError(
"Engine response must include mm_placeholders when process_multimodal=False."
)
parsed = await _maybe_offload(
renderer, lambda: renderer.parse_response(completion_ids, tools=tools)
completion_logprobs = _parse_completion_logprobs(choice, completion_ids)
parsed = renderer.parse_response(
completion_ids,
prompt_ids=list(effective_prompt_ids or prompt_ids),
tools=tools,
)
# ChatCompletionLogProbs flatten: {"content": [{"logprob": ...}, ...]}
raw_logprobs = choice.get("logprobs") or {}
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 = choice.get("routed_experts")
kept_tokens = choice.get("kept_tokens")
# vLLM's native kept-set sampling masks (``--return-sampling-mask``):
# one list of surviving vocab ids per completion token.
sampling_mask = choice.get("sampling_mask")
# /inference/v1/generate returns finish_reason in {"stop","length",...} —
# never "tool_calls" (a chat-completions concept). Promote stop→tool_calls
@@ -321,15 +396,19 @@ async def generate(
return {
"request_id": data.get("request_id") or "",
"prompt_ids": list(prompt_ids),
"usage": data.get("usage"),
"prompt_ids": list(effective_prompt_ids or prompt_ids),
"renderer_prompt_ids": list(prompt_ids) if content_parts else None,
"mm_placeholders": mm_placeholders,
"completion_ids": list(completion_ids),
"completion_logprobs": completion_logprobs,
"content": parsed.content,
"reasoning_content": parsed.reasoning_content,
"tool_calls": parsed.tool_calls,
"finish_reason": finish_reason,
"reasoning_complete": parsed.reasoning_complete,
"routed_experts": routed_experts,
"kept_tokens": kept_tokens,
"sampling_mask": sampling_mask,
# 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.
@@ -345,8 +424,45 @@ async def generate(
}
_MEDIA_URL_TYPES = {
"image": "image_url",
"image_url": "image_url",
"audio": "audio_url",
"audio_url": "audio_url",
"video": "video_url",
"video_url": "video_url",
}
def _content_parts(messages: list[Message]) -> list[dict[str, Any]]:
"""Flatten raw media in prompt order for vLLM's token generate endpoint."""
parts: list[dict[str, Any]] = []
for message in messages:
content = message.get("content")
if not isinstance(content, list):
continue
for part in content:
if not isinstance(part, Mapping):
continue
part_type = part.get("type")
if part_type is None:
part_type = next(
(key for key in _MEDIA_URL_TYPES if part.get(key)), None
)
if not isinstance(part_type, str) or part_type not in _MEDIA_URL_TYPES:
continue
source = part.get(part_type)
if source is None:
source = part.get(_MEDIA_URL_TYPES[part_type]) or part.get("url")
url = source.get("url") if isinstance(source, Mapping) else source
if not isinstance(url, str) or not url:
raise ValueError(f"{part_type} content part is missing a URL")
parts.append({"type": _MEDIA_URL_TYPES[part_type], "url": url})
return parts
def _build_mm_features(
renderer: Renderer | RendererPool,
renderer: Renderer,
mm_data: MultiModalData,
) -> dict[str, Any] | None:
"""Serialize ``MultiModalData`` to vLLM's ``/inference/v1/generate`` features payload.
@@ -359,9 +475,9 @@ def _build_mm_features(
model-family specific. For now we dispatch on the renderer class;
extend the dispatch table as more multimodal renderers land.
NOTE — future engine pluggability: this encoder is vLLM 0.20-specific
NOTE — future engine pluggability: this encoder is vLLM-specific
(uses ``vllm.multimodal.inputs.MultiModalKwargsItems``,
``vllm.entrypoints.serve.disagg.mm_serde.encode_mm_kwargs_item``, and
``vllm.entrypoints.scale_out.token_in_token_out.mm_serde.encode_mm_kwargs_item``, and
``_create_qwen2vl_field_factory``). When a second inference engine
arrives (SGLang, MAX, ...) the renderer client should be parameterized
on engine: either (a) move the encoder onto the renderer as
@@ -370,21 +486,22 @@ def _build_mm_features(
(``MultiModalData``) is already framework-agnostic and does not need
to change. Don't pre-build the abstraction with one engine in tree.
"""
from renderers.gemma4 import Gemma4Renderer
from renderers.nemotron3 import Nemotron35Renderer
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
# out a slot just to read ``type(r)``.
renderer_cls = (
renderer.renderer_cls if isinstance(renderer, RendererPool) else type(renderer)
)
renderer_cls = type(renderer)
# 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)
if issubclass(renderer_cls, Gemma4Renderer):
return _build_gemma4_features(mm_data)
if issubclass(renderer_cls, Nemotron35Renderer):
return _build_nemotron35_features(mm_data)
raise NotImplementedError(
f"Multimodal serialization not implemented for {renderer_cls.__name__}. "
@@ -392,6 +509,143 @@ def _build_mm_features(
)
def _build_nemotron35_features(mm_data: MultiModalData) -> dict[str, Any]:
"""Encode dynamic-resolution Nemotron image inputs for vLLM."""
_require_transformers("Encoding Nemotron 3.5 multimodal features for vLLM")
try:
import torch
from transformers.feature_extraction_utils import BatchFeature
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import (
encode_mm_kwargs_item,
)
from vllm.multimodal.inputs import (
MultiModalFieldConfig,
MultiModalKwargsItems,
)
except ImportError as exc:
raise RuntimeError(
"Nemotron 3.5 multimodal generate requires vLLM and torch."
) from exc
out: dict[str, Any] = {
"mm_hashes": {},
"mm_placeholders": {},
"kwargs_data": {},
}
image_items = mm_data.mm_items.get("image") or []
if image_items:
pixel_values_flat = []
imgs_sizes = []
num_tokens_per_image = []
for item in image_items:
pixel_values = torch.as_tensor(item["pixel_values"])
if pixel_values.ndim != 4 or pixel_values.shape[0] != 1:
raise ValueError(
"Each Nemotron pixel_values item must have shape (1, C, H, W)."
)
sizes = item["imgs_sizes"]
token_counts = item["num_tokens"]
if not (len(sizes) == len(token_counts) == 1):
raise ValueError(
"Each Nemotron image item must contain one size and token count."
)
pixel_values_flat.append(pixel_values[0])
imgs_sizes.append(tuple(int(value) for value in sizes[0]))
num_tokens_per_image.append(int(token_counts[0]))
hf_inputs = BatchFeature(
data={
"pixel_values_flat": pixel_values_flat,
"imgs_sizes": imgs_sizes,
"num_tokens_per_image": num_tokens_per_image,
}
)
field_config = {
"pixel_values_flat": MultiModalFieldConfig.batched("image"),
"num_tokens_per_image": MultiModalFieldConfig.batched(
"image", keep_on_cpu=True
),
"imgs_sizes": MultiModalFieldConfig.batched("image", keep_on_cpu=True),
}
kwargs_items = MultiModalKwargsItems.from_hf_inputs(hf_inputs, field_config)
out["kwargs_data"]["image"] = [
encode_mm_kwargs_item(item) for item in kwargs_items["image"]
]
out["mm_hashes"]["image"] = list(mm_data.mm_hashes.get("image") or [])
out["mm_placeholders"]["image"] = [
{"offset": placeholder.offset, "length": placeholder.length}
for placeholder in mm_data.mm_placeholders.get("image") or []
]
if not any(out["kwargs_data"].values()):
out["kwargs_data"] = None
return out
def _build_gemma4_features(mm_data: MultiModalData) -> dict[str, Any]:
"""vLLM features payload for Gemma 4 image inputs.
Hugging Face names the position field ``image_position_ids`` while
vLLM's Gemma 4 processor schema calls it ``pixel_position_ids``. Keep
renderer output faithful to the HF processor and translate at this
engine-specific boundary.
"""
_require_transformers("Encoding Gemma 4 multimodal features for vLLM")
try:
import torch
from transformers.feature_extraction_utils import BatchFeature
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import (
encode_mm_kwargs_item,
)
from vllm.multimodal.inputs import (
MultiModalFieldConfig,
MultiModalKwargsItems,
)
except ImportError as exc:
raise RuntimeError(
"Gemma 4 multimodal generate via /inference/v1/generate requires "
"a vLLM release with Gemma 4 support and `torch`."
) from exc
out: dict[str, Any] = {
"mm_hashes": {},
"mm_placeholders": {},
"kwargs_data": {},
}
image_items = mm_data.mm_items.get("image") or []
if image_items:
pixel_values = torch.cat(
[torch.as_tensor(item["pixel_values"]) for item in image_items], dim=0
)
pixel_position_ids = torch.cat(
[torch.as_tensor(item["image_position_ids"]) for item in image_items],
dim=0,
)
hf_inputs = BatchFeature(
data={
"pixel_values": pixel_values,
"pixel_position_ids": pixel_position_ids,
}
)
field_config = {
"pixel_values": MultiModalFieldConfig.batched("image"),
"pixel_position_ids": MultiModalFieldConfig.batched("image"),
}
kwargs_items = MultiModalKwargsItems.from_hf_inputs(hf_inputs, field_config)
out["kwargs_data"]["image"] = [
encode_mm_kwargs_item(item) for item in kwargs_items["image"]
]
out["mm_hashes"]["image"] = list(mm_data.mm_hashes.get("image") or [])
out["mm_placeholders"]["image"] = [
{"offset": placeholder.offset, "length": placeholder.length}
for placeholder in mm_data.mm_placeholders.get("image") or []
]
if not any(out["kwargs_data"].values()):
out["kwargs_data"] = None
return out
def _build_qwen_vl_features(
mm_data: MultiModalData, *, spatial_merge_size: int
) -> dict[str, Any]:
@@ -405,10 +659,13 @@ def _build_qwen_vl_features(
Returns ``None`` semantics live one level up — this helper assumes
the caller already verified ``mm_data`` is non-empty.
"""
_require_transformers("Encoding Qwen-VL multimodal features for vLLM")
try:
import torch
from transformers.feature_extraction_utils import BatchFeature
from vllm.entrypoints.serve.disagg.mm_serde import encode_mm_kwargs_item
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import (
encode_mm_kwargs_item,
)
from vllm.model_executor.models.qwen2_vl import _create_qwen2vl_field_factory
from vllm.multimodal.inputs import MultiModalKwargsItems
except ImportError as exc:
+438 -35
View File
@@ -1,10 +1,11 @@
"""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
Each renderer accepts its own typed config and declares an explicit
``_template_fields`` allowlist for fields that may arrive through
``chat_template_kwargs``. Bad combinations (e.g. ``add_vision_id`` under
``name="qwen3"``) fail before renderer construction. 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.
@@ -20,7 +21,7 @@ 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 typing import Annotated, ClassVar, Literal, Self, Union
from pydantic import ConfigDict, Field, model_validator
from pydantic_config import BaseConfig
@@ -87,31 +88,36 @@ class BaseRendererConfig(BaseConfig):
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.
# Every renderer-specific field must be classified exactly once: either
# as a chat-template kwarg or as renderer-internal configuration.
_template_fields: ClassVar[frozenset[str]] = frozenset()
_internal_fields: ClassVar[frozenset[str]] = frozenset()
_allow_opaque_template_kwargs: ClassVar[bool] = False
@classmethod
def __pydantic_init_subclass__(cls, **kwargs) -> None:
super().__pydantic_init_subclass__(**kwargs)
base_fields = frozenset(BaseRendererConfig.model_fields)
renderer_fields = frozenset(cls.model_fields) - base_fields - {"name"}
overlap = cls._template_fields & cls._internal_fields
missing = renderer_fields - cls._template_fields - cls._internal_fields
unknown = (cls._template_fields | cls._internal_fields) - renderer_fields
if overlap or missing or unknown:
raise TypeError(
f"{cls.__name__} has an invalid renderer-field classification: "
f"overlap={sorted(overlap)}, missing={sorted(missing)}, "
f"unknown={sorted(unknown)}"
)
@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``.
Used both as the runtime allowlist for ``chat_template_kwargs`` and
by parity tests 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
return cls._template_fields
class AutoRendererConfig(BaseRendererConfig):
@@ -122,6 +128,7 @@ class AutoRendererConfig(BaseRendererConfig):
at the call site."""
name: Literal["auto"] = "auto"
_template_fields = frozenset()
class DefaultRendererConfig(BaseRendererConfig):
@@ -148,9 +155,11 @@ class DefaultRendererConfig(BaseRendererConfig):
# DefaultRenderer's parsing pipeline, not the underlying Jinja
# template. Jinja kwargs live in ``model_extra`` (extra="allow").
_internal_fields = frozenset({"tool_parser", "reasoning_parser"})
_template_fields = frozenset()
_allow_opaque_template_kwargs = True
@model_validator(mode="after")
def _reject_legacy_preserve_flags(self):
def _reject_legacy_preserve_flags(self) -> 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
@@ -174,29 +183,45 @@ class Qwen3RendererConfig(BaseRendererConfig):
"""Qwen3 (text-only) renderer config."""
name: Literal["qwen3"] = "qwen3"
_template_fields = frozenset({"enable_thinking"})
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."""
``enable_thinking`` kwarg.
When ``False``, the renderer deliberately deviates from the template
on historical assistant turns without ``reasoning_content``: the empty
``<think>\\n\\n</think>\\n\\n`` wrapper the generation prompt prefilled
is re-emitted instead of stripped, keeping re-renders token-stable with
the sampled stream (see ``renderers/qwen3.py`` module docstring)."""
class PrimeQwen3RendererConfig(BaseRendererConfig):
"""PrimeIntellect Qwen3 renderer config."""
name: Literal["prime-qwen3"] = "prime-qwen3"
_template_fields = frozenset()
class Qwen35RendererConfig(BaseRendererConfig):
"""Qwen3.5 renderer config."""
name: Literal["qwen3.5"] = "qwen3.5"
_template_fields = frozenset({"enable_thinking", "add_vision_id"})
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."""
the chat template's ``enable_thinking`` kwarg.
When resolved ``False``, the renderer deliberately deviates from the
template on historical assistant turns without ``reasoning_content``:
the empty ``<think>\\n\\n</think>\\n\\n`` wrapper the generation prompt
prefilled is re-emitted instead of stripped, keeping re-renders
token-stable with the sampled stream (see ``renderers/qwen35.py``
module docstring)."""
add_vision_id: bool = False
"""When ``True``, prefix each ``<|vision_start|>`` placeholder with
@@ -215,6 +240,9 @@ class Qwen36RendererConfig(BaseRendererConfig):
"""Qwen3.6 renderer config. Inherits Qwen3.5's template surface."""
name: Literal["qwen3.6"] = "qwen3.6"
_template_fields = frozenset(
{"enable_thinking", "add_vision_id", "preserve_thinking"}
)
enable_thinking: bool | None = None
"""See :class:`Qwen35RendererConfig.enable_thinking`."""
@@ -233,7 +261,53 @@ class Qwen36RendererConfig(BaseRendererConfig):
_internal_fields = frozenset({"image_cache_max"})
@model_validator(mode="after")
def _check_thinking_retention(self):
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"preserve_thinking",
true_implies="all",
false_implies="tool_cycle",
)
return self
class Qwen38RendererConfig(BaseRendererConfig):
"""Qwen3.8 renderer config.
Qwen3.8 keeps Qwen3.6's multimodal/tool template and adds native
reasoning-effort instructions. Historical thinking is preserved by
default in the upstream template.
"""
name: Literal["qwen3.8"] = "qwen3.8"
_template_fields = frozenset(
{
"enable_thinking",
"add_vision_id",
"preserve_thinking",
"reasoning_effort",
}
)
enable_thinking: bool | None = None
"""See :class:`Qwen35RendererConfig.enable_thinking`."""
add_vision_id: bool = False
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
preserve_thinking: bool = True
"""Keep historical ``<think>`` blocks. Mirrors Qwen3.8's default."""
reasoning_effort: Literal["xhigh", "medium", "low"] = "xhigh"
"""Reasoning depth hint injected into the system prompt when enabled."""
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) -> Self:
_reject_thinking_retention_conflict(
self,
"preserve_thinking",
@@ -247,6 +321,7 @@ class Qwen3VLRendererConfig(BaseRendererConfig):
"""Qwen3-VL renderer config."""
name: Literal["qwen3-vl"] = "qwen3-vl"
_template_fields = frozenset({"add_vision_id"})
add_vision_id: bool = False
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
@@ -257,10 +332,39 @@ class Qwen3VLRendererConfig(BaseRendererConfig):
_internal_fields = frozenset({"image_cache_max"})
class Gemma4RendererConfig(BaseRendererConfig):
"""Gemma 4 renderer config."""
name: Literal["gemma4"] = "gemma4"
_template_fields = frozenset({"enable_thinking", "preserve_thinking"})
enable_thinking: bool = False
"""Enable Gemma 4's thinking mode. Mirrors the canonical template kwarg."""
preserve_thinking: bool = False
"""Keep thinking on historical tool-call turns when the template permits it."""
image_cache_max: int = 256
"""FIFO bound on processed image entries. Renderer-internal."""
_internal_fields = frozenset({"image_cache_max"})
@model_validator(mode="after")
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"preserve_thinking",
true_implies="all",
false_implies="tool_cycle",
)
return self
class GLM5RendererConfig(BaseRendererConfig):
"""GLM-5 renderer config."""
name: Literal["glm-5"] = "glm-5"
_template_fields = frozenset({"enable_thinking", "clear_thinking"})
enable_thinking: bool = True
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
@@ -273,7 +377,7 @@ class GLM5RendererConfig(BaseRendererConfig):
to ``"all"``."""
@model_validator(mode="after")
def _check_thinking_retention(self):
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"clear_thinking",
@@ -288,6 +392,7 @@ class GLM51RendererConfig(BaseRendererConfig):
discriminator so the registry can route to ``GLM51Renderer``."""
name: Literal["glm-5.1"] = "glm-5.1"
_template_fields = frozenset({"enable_thinking", "clear_thinking"})
enable_thinking: bool = True
"""See :class:`GLM5RendererConfig.enable_thinking`."""
@@ -296,7 +401,30 @@ class GLM51RendererConfig(BaseRendererConfig):
"""See :class:`GLM5RendererConfig.clear_thinking`."""
@model_validator(mode="after")
def _check_thinking_retention(self):
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"clear_thinking",
true_implies="tool_cycle",
false_implies="all",
)
return self
class GLM53RendererConfig(BaseRendererConfig):
"""GLM-5.3 renderer config."""
name: Literal["glm-5.3"] = "glm-5.3"
_template_fields = frozenset({"clear_thinking", "reasoning_effort"})
clear_thinking: bool = False
"""Drop reasoning from historical assistant turns when ``True``."""
reasoning_effort: Literal["low", "high", "max"] = "max"
"""Reasoning-effort system preamble emitted by the canonical template."""
@model_validator(mode="after")
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"clear_thinking",
@@ -310,6 +438,7 @@ class GLM45RendererConfig(BaseRendererConfig):
"""GLM-4.5 Air renderer config."""
name: Literal["glm-4.5"] = "glm-4.5"
_template_fields = frozenset({"enable_thinking"})
enable_thinking: bool = True
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
@@ -337,6 +466,15 @@ class Hy3RendererConfig(BaseRendererConfig):
"""
name: Literal["hy3"] = "hy3"
_template_fields = frozenset(
{
"reasoning_effort",
"preserved_thinking",
"is_training",
"raw_last_assistant",
"fallback_strategy",
}
)
reasoning_effort: Literal["no_think", "low", "high"] = "no_think"
"""Reasoning gate. Mirrors the chat template's ``reasoning_effort`` kwarg.
@@ -368,7 +506,7 @@ class Hy3RendererConfig(BaseRendererConfig):
and suppresses the generation prompt (``add_generation_prompt=False``)."""
@model_validator(mode="after")
def _check_thinking_retention(self):
def _check_thinking_retention(self) -> 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:
@@ -380,6 +518,69 @@ class Hy3RendererConfig(BaseRendererConfig):
return self
# Inkling ``reasoning_effort`` label → float (the template's own effort_map).
INKLING_EFFORT_MAP: dict[str, float] = {
"none": 0.0,
"minimal": 0.1,
"low": 0.2,
"medium": 0.7,
"high": 0.9,
"max": 0.99,
}
class InklingRendererConfig(BaseRendererConfig):
"""Renderer config for Inkling and Inkling-Small.
Inkling gates reasoning depth via a ``reasoning_effort`` knob rather
than a boolean ``enable_thinking``. It accepts either a string label
from :data:`INKLING_EFFORT_MAP` (``none`` … ``max``) or a raw float in
``[0.0, 0.99]``; the renderer emits ``Thinking effort level: {N}`` in a
leading system message exactly as the chat template does (label mapped
to its float, ``0.0`` printed as ``"0"``). The template default —
applied when no ``reasoning_effort`` is passed — is ``0.9``, which this
config mirrors.
Reasoning is preserved on every historical assistant turn (the template
has no history-dropping knob), so the effective bridge policy is
``"all"``.
"""
name: Literal["inkling"] = "inkling"
_template_fields = frozenset({"reasoning_effort"})
reasoning_effort: str | float = 0.9
"""Reasoning-effort gate. Mirrors the chat template's ``reasoning_effort``
kwarg: a label in :data:`INKLING_EFFORT_MAP` or a float in ``[0.0, 0.99]``.
Default ``0.9`` matches the template's own default (equivalent to
``"high"``)."""
image_cache_max: int = 256
"""FIFO bound on the per-renderer image-processor cache. Renderer-
internal — not a Jinja chat-template kwarg."""
audio_cache_max: int = 256
"""FIFO bound on the per-renderer audio-processor cache. Renderer-
internal — not a Jinja chat-template kwarg."""
_internal_fields = frozenset({"image_cache_max", "audio_cache_max"})
@model_validator(mode="after")
def _check_reasoning_effort(self) -> Self:
eff = self.reasoning_effort
if isinstance(eff, str):
if eff.strip() not in INKLING_EFFORT_MAP:
raise ValueError(
f"reasoning_effort={eff!r} is not a known label. "
f"Use one of {sorted(INKLING_EFFORT_MAP)} or a float in [0.0, 0.99]."
)
else:
num = float(eff)
if num < 0.0 or num > 0.99:
raise ValueError(f"reasoning_effort={eff!r} must be in [0.0, 0.99].")
return self
class GptOssRendererConfig(BaseRendererConfig):
"""OpenAI gpt-oss (harmony) renderer config.
@@ -393,6 +594,7 @@ class GptOssRendererConfig(BaseRendererConfig):
"""
name: Literal["gpt-oss"] = "gpt-oss"
_template_fields = frozenset({"reasoning_effort", "conversation_start_date"})
reasoning_effort: Literal["low", "medium", "high"] = "medium"
"""Harmony reasoning-effort tag. Mirrors the ``apply_chat_template``
@@ -429,7 +631,7 @@ class GptOssRendererConfig(BaseRendererConfig):
)
@model_validator(mode="after")
def _check_thinking_retention(self):
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"auto_drop_analysis",
@@ -449,6 +651,7 @@ class KimiK2RendererConfig(BaseRendererConfig):
"""
name: Literal["kimi-k2"] = "kimi-k2"
_template_fields = frozenset()
enable_thinking: bool = True
"""No-op for Kimi K2 (template doesn't gate on it). Stored for
@@ -461,6 +664,7 @@ class KimiK25RendererConfig(BaseRendererConfig):
"""Kimi K2.5 renderer config."""
name: Literal["kimi-k2.5"] = "kimi-k2.5"
_template_fields = frozenset({"thinking"})
thinking: bool = True
"""When ``True``, the generation prompt prefills ``<think>``; when
@@ -478,6 +682,7 @@ class LagunaXS2RendererConfig(BaseRendererConfig):
"""Laguna XS.2 renderer config."""
name: Literal["laguna-xs.2"] = "laguna-xs.2"
_template_fields = frozenset({"enable_thinking", "render_assistant_messages_raw"})
enable_thinking: bool = False
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
@@ -492,6 +697,29 @@ class LagunaXS2RendererConfig(BaseRendererConfig):
chat template's ``render_assistant_messages_raw`` gate."""
class LagunaM1RendererConfig(BaseRendererConfig):
"""Laguna M.1 renderer config.
Laguna M.1 shares Laguna XS.2's role and tool-call format, but its
official checkpoint has a distinct chat template: it does not inject
XS.2's fallback system message and it gives ``message.reasoning``
precedence over ``message.reasoning_content``. Served by
:class:`renderers.laguna_xs2.LagunaM1Renderer`.
"""
name: Literal["laguna-m.1"] = "laguna-m.1"
_template_fields = frozenset({"enable_thinking", "render_assistant_messages_raw"})
enable_thinking: bool = False
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
the official template's ``enable_thinking`` kwarg and default."""
render_assistant_messages_raw: bool = False
"""When ``True``, assistant messages use the official template's
verbatim passthrough branch. See
:class:`LagunaXS2RendererConfig.render_assistant_messages_raw`."""
class LagunaXS21RendererConfig(BaseRendererConfig):
"""Laguna XS-2.1 renderer config.
@@ -502,6 +730,7 @@ class LagunaXS21RendererConfig(BaseRendererConfig):
"""
name: Literal["laguna-xs-2.1"] = "laguna-xs-2.1"
_template_fields = frozenset({"enable_thinking"})
enable_thinking: bool = False
"""When ``True``, the generation prompt ends with ``<think>`` and
@@ -511,6 +740,38 @@ class LagunaXS21RendererConfig(BaseRendererConfig):
upstream default."""
class LagunaS21RendererConfig(BaseRendererConfig):
"""Laguna S-2.1 renderer config.
S-2.1 is a larger sibling of XS-2.1 sharing its tokenizer (same vocab,
special tokens, and merges), but its chat template is *not* byte-identical:
``enable_thinking`` defaults to ``True`` (XS-2.1 defaults ``False``), and a
new ``preserve_thinking`` kwarg widens the reasoning-display gate to
``enable_thinking or preserve_thinking``. The token format is otherwise
identical, so this is served by
:class:`renderers.laguna_s21.LagunaS21Renderer`, a thin subclass of
``LagunaXS21Renderer`` that only overrides that gate.
"""
name: Literal["laguna-s-2.1"] = "laguna-s-2.1"
_template_fields = frozenset({"enable_thinking", "preserve_thinking"})
enable_thinking: bool = True
"""When ``True``, the generation prompt ends with ``<think>`` and every
assistant turn renders ``<think>{reasoning}</think>``; when ``False``,
turns open with a bare ``</think>``. Mirrors the template's
``enable_thinking`` kwarg — note S-2.1's upstream default is ``True``,
unlike XS-2.1's ``False``."""
preserve_thinking: bool = False
"""When ``True``, assistant turns keep their ``<think>{reasoning}</think>``
block even while ``enable_thinking`` is ``False`` — the template gates
reasoning display on ``enable_thinking or preserve_thinking``. With the
default ``False`` the gate collapses to ``enable_thinking`` and the
renderer matches XS-2.1 turn-for-turn. Mirrors the template's
``preserve_thinking`` kwarg and its upstream default."""
class Llama3RendererConfig(BaseRendererConfig):
"""Llama-3.x Instruct renderer config.
@@ -523,6 +784,7 @@ class Llama3RendererConfig(BaseRendererConfig):
"""
name: Literal["llama-3"] = "llama-3"
_template_fields = frozenset({"date_string", "tools_in_user_message"})
date_string: str = "26 Jul 2024"
"""``Today Date`` value injected into the system preamble. Pinned to
@@ -541,6 +803,7 @@ class MiniMaxM2RendererConfig(BaseRendererConfig):
"""MiniMax M2 / M2.5 renderer config."""
name: Literal["minimax-m2"] = "minimax-m2"
_template_fields = frozenset({"model_identity"})
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
@@ -558,6 +821,9 @@ class Nemotron3RendererConfig(BaseRendererConfig):
"""
name: Literal["nemotron-3"] = "nemotron-3"
_template_fields = frozenset(
{"enable_thinking", "truncate_history_thinking", "low_effort"}
)
enable_thinking: bool = True
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
@@ -570,7 +836,7 @@ class Nemotron3RendererConfig(BaseRendererConfig):
policy to ``"all"``."""
@model_validator(mode="after")
def _check_thinking_retention(self):
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"truncate_history_thinking",
@@ -600,6 +866,9 @@ class Nemotron3UltraRendererConfig(BaseRendererConfig):
"""
name: Literal["nemotron-3-ultra"] = "nemotron-3-ultra"
_template_fields = frozenset(
{"enable_thinking", "truncate_history_thinking", "medium_effort"}
)
enable_thinking: bool = True
"""See :class:`Nemotron3RendererConfig.enable_thinking`."""
@@ -608,7 +877,7 @@ class Nemotron3UltraRendererConfig(BaseRendererConfig):
"""See :class:`Nemotron3RendererConfig.truncate_history_thinking`."""
@model_validator(mode="after")
def _check_thinking_retention(self):
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"truncate_history_thinking",
@@ -622,6 +891,38 @@ class Nemotron3UltraRendererConfig(BaseRendererConfig):
user message. Mirrors the Ultra chat template's ``medium_effort`` kwarg."""
class Nemotron35RendererConfig(BaseRendererConfig):
"""Nemotron-3.5 (Lightning) renderer config.
Nemotron 3.5's chat template is the Ultra variant's minus the effort
kwarg: same reasoning-block glue (no ``\\n`` around ``</think>``, no
trim on truncated tool-call history), but its Jinja defines no
reasoning-effort variable at all. It shares the
:class:`renderers.nemotron3.Nemotron3Renderer` implementation via the
:class:`renderers.nemotron3.Nemotron35Renderer` subclass and is reached
via the ``nemotron-3.5`` discriminator.
"""
name: Literal["nemotron-3.5"] = "nemotron-3.5"
_template_fields = frozenset({"enable_thinking", "truncate_history_thinking"})
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) -> Self:
_reject_thinking_retention_conflict(
self,
"truncate_history_thinking",
true_implies="tool_cycle",
false_implies="all",
)
return self
class DeepSeekV3RendererConfig(BaseRendererConfig):
"""DeepSeek-V3 renderer config (non-reasoning).
@@ -631,6 +932,7 @@ class DeepSeekV3RendererConfig(BaseRendererConfig):
"""
name: Literal["deepseek-v3"] = "deepseek-v3"
_template_fields = frozenset()
class DeepSeekR1RendererConfig(BaseRendererConfig):
@@ -648,6 +950,82 @@ class DeepSeekR1RendererConfig(BaseRendererConfig):
"""
name: Literal["deepseek-r1"] = "deepseek-r1"
_template_fields = frozenset()
class DeepSeekV4RendererConfig(BaseRendererConfig):
"""DeepSeek-V4-Flash-0731 reference-encoder configuration.
The checkpoint ships a Python encoder rather than a Jinja template. These
fields mirror its public controls: chat vs thinking mode, historical
reasoning dropping, and the opt-in thinking-effort prefix.
"""
name: Literal["deepseek-v4"] = "deepseek-v4"
_template_fields = frozenset(
{"enable_thinking", "drop_thinking", "reasoning_effort"}
)
enable_thinking: bool = False
"""Select thinking mode. ``False`` matches the official inference script."""
drop_thinking: bool = True
"""Drop reasoning before the latest user query when no tools are present.
The reference encoder automatically preserves all reasoning whenever tools
are supplied, regardless of this value.
"""
reasoning_effort: Literal["low", "high", "max"] = "low"
"""Thinking-only effort prefix; ``low`` adds no text.
``low`` is the checkpoint Python encoder's default. DeepSeek's hosted API
independently defaults its thinking effort to ``high``.
"""
@model_validator(mode="after")
def _check_thinking_retention(self) -> Self:
_reject_thinking_retention_conflict(
self,
"drop_thinking",
true_implies="tool_cycle",
false_implies="all",
)
return self
class CustomRendererConfig(BaseRendererConfig):
"""Config for a renderer that lives outside this package.
``import_path`` names the renderer class as ``my_module.Class`` or
``path/to/file.py:Class``; relative file paths resolve against the
working directory. The class sets ``config_class`` to its own
:class:`BaseRendererConfig` subclass, and that class validates every other
field of this config. A model-specific renderer can therefore ship without
a change to this package::
[renderer]
name = "custom"
import_path = "my_renderers.glm53_no_thinking.NoThinkingGLM53Renderer"
clear_thinking = true
"""
model_config = ConfigDict(frozen=True, extra="allow")
name: Literal["custom"] = "custom"
import_path: str
"""Renderer class as ``my_module.Class`` or ``path/to/file.py:Class``."""
_internal_fields = frozenset({"import_path"})
@model_validator(mode="after")
def _validate_renderer_fields(self) -> Self:
# Fail at config load, not at the first render: the import path must
# resolve and the renderer's config must accept the other fields.
from renderers.custom import custom_renderer_config
custom_renderer_config(self)
return self
RendererConfig = Annotated[
@@ -658,22 +1036,31 @@ RendererConfig = Annotated[
PrimeQwen3RendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen38RendererConfig,
Qwen3VLRendererConfig,
Gemma4RendererConfig,
GLM5RendererConfig,
GLM51RendererConfig,
GLM53RendererConfig,
GLM45RendererConfig,
GptOssRendererConfig,
Hy3RendererConfig,
InklingRendererConfig,
KimiK2RendererConfig,
KimiK25RendererConfig,
LagunaXS2RendererConfig,
LagunaM1RendererConfig,
LagunaXS21RendererConfig,
LagunaS21RendererConfig,
Llama3RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
Nemotron35RendererConfig,
DeepSeekV3RendererConfig,
DeepSeekR1RendererConfig,
DeepSeekV4RendererConfig,
CustomRendererConfig,
],
Field(discriminator="name"),
]
@@ -698,22 +1085,30 @@ _CONFIG_BY_NAME: dict[str, type[BaseRendererConfig]] = {
"prime-qwen3": PrimeQwen3RendererConfig,
"qwen3.5": Qwen35RendererConfig,
"qwen3.6": Qwen36RendererConfig,
"qwen3.8": Qwen38RendererConfig,
"qwen3-vl": Qwen3VLRendererConfig,
"gemma4": Gemma4RendererConfig,
"glm-5": GLM5RendererConfig,
"glm-5.1": GLM51RendererConfig,
"glm-5.3": GLM53RendererConfig,
"glm-4.5": GLM45RendererConfig,
"gpt-oss": GptOssRendererConfig,
"hy3": Hy3RendererConfig,
"inkling": InklingRendererConfig,
"kimi-k2": KimiK2RendererConfig,
"kimi-k2.5": KimiK25RendererConfig,
"laguna-xs.2": LagunaXS2RendererConfig,
"laguna-m.1": LagunaM1RendererConfig,
"laguna-xs-2.1": LagunaXS21RendererConfig,
"laguna-s-2.1": LagunaS21RendererConfig,
"llama-3": Llama3RendererConfig,
"minimax-m2": MiniMaxM2RendererConfig,
"nemotron-3": Nemotron3RendererConfig,
"nemotron-3-ultra": Nemotron3UltraRendererConfig,
"nemotron-3.5": Nemotron35RendererConfig,
"deepseek-v3": DeepSeekV3RendererConfig,
"deepseek-r1": DeepSeekR1RendererConfig,
"deepseek-v4": DeepSeekV4RendererConfig,
}
@@ -721,8 +1116,7 @@ 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)}"
f"No renderer config registered for name={name!r}. Known: {sorted(_CONFIG_BY_NAME)}"
)
return cls
@@ -747,22 +1141,31 @@ __all__ = [
"DefaultRendererConfig",
"DeepSeekR1RendererConfig",
"DeepSeekV3RendererConfig",
"DeepSeekV4RendererConfig",
"GLM45RendererConfig",
"GLM51RendererConfig",
"GLM53RendererConfig",
"GLM5RendererConfig",
"Gemma4RendererConfig",
"GptOssRendererConfig",
"Hy3RendererConfig",
"INKLING_EFFORT_MAP",
"InklingRendererConfig",
"KimiK25RendererConfig",
"KimiK2RendererConfig",
"LagunaM1RendererConfig",
"LagunaS21RendererConfig",
"LagunaXS2RendererConfig",
"LagunaXS21RendererConfig",
"Llama3RendererConfig",
"MiniMaxM2RendererConfig",
"Nemotron35RendererConfig",
"Nemotron3RendererConfig",
"Nemotron3UltraRendererConfig",
"PrimeQwen3RendererConfig",
"Qwen35RendererConfig",
"Qwen36RendererConfig",
"Qwen38RendererConfig",
"Qwen3RendererConfig",
"Qwen3VLRendererConfig",
"RendererConfig",
+99
View File
@@ -0,0 +1,99 @@
"""Load custom renderers from importable modules or local Python files.
An import path is ``my_module.Name`` (dotted, like any ``import``) or
``path/to/file.py:Name``. File paths are resolved against the working
directory and imported once per process under a stable module name, so every
caller gets the same class objects.
"""
from __future__ import annotations
import hashlib
import importlib
import importlib.util
import sys
from functools import lru_cache
from pathlib import Path
from types import ModuleType
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from renderers.configs import BaseRendererConfig, CustomRendererConfig
def load_target(import_path: str) -> Any:
"""Return the object that ``import_path`` names."""
module_ref, sep, attr = import_path.rpartition(":")
if not sep and not _is_file_ref(import_path):
module_ref, sep, attr = import_path.rpartition(".")
if not sep or not module_ref or not attr:
raise ValueError(
f"Import path {import_path!r} must look like 'my_module.Name' or 'path/to/file.py:Name'"
)
module = load_module(module_ref)
try:
return getattr(module, attr)
except AttributeError:
raise ValueError(f"Module {module_ref!r} has no attribute {attr!r}") from None
def load_module(module_ref: str) -> ModuleType:
"""Import a module by dotted name or by file path."""
if _is_file_ref(module_ref):
return _load_file_module(str(Path(module_ref).expanduser().resolve()))
return importlib.import_module(module_ref)
def _is_file_ref(ref: str) -> bool:
return ref.endswith(".py") or "/" in ref
@lru_cache(maxsize=None)
def _load_file_module(path: str) -> ModuleType:
file = Path(path)
if not file.is_file():
raise FileNotFoundError(f"Custom renderer file {path!r} does not exist")
# A path-derived name keeps two files with the same name apart.
digest = hashlib.sha1(path.encode()).hexdigest()[:8]
name = f"renderers_custom_{file.stem}_{digest}"
if name in sys.modules:
return sys.modules[name]
spec = importlib.util.spec_from_file_location(name, file)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot import custom renderer file {path!r}")
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
try:
spec.loader.exec_module(module)
except BaseException:
sys.modules.pop(name, None)
raise
return module
def load_custom_renderer(import_path: str) -> Any:
"""Return the renderer class that ``import_path`` names.
The class must set ``config_class`` to its own
:class:`~renderers.configs.BaseRendererConfig` subclass.
"""
from renderers.configs import BaseRendererConfig
renderer_cls = load_target(import_path)
config_cls = getattr(renderer_cls, "config_class", None)
if not (
isinstance(config_cls, type) and issubclass(config_cls, BaseRendererConfig)
):
raise TypeError(
f"Custom renderer {import_path!r} must set config_class to a BaseRendererConfig subclass"
)
return renderer_cls
def custom_renderer_config(config: "CustomRendererConfig") -> "BaseRendererConfig":
"""The renderer's own typed config, built from the fields next to ``import_path``."""
config_cls = load_custom_renderer(config.import_path).config_class
data = dict(config.model_extra or {})
for field_name in config.model_fields_set - {"name", "import_path"}:
data[field_name] = getattr(config, field_name)
return config_cls.model_validate(data)
+37 -4
View File
@@ -14,13 +14,15 @@ from __future__ import annotations
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -54,6 +56,11 @@ class DeepSeekV3Renderer:
stored for protocol uniformity.
"""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
return True
#: Default typed config; the R1 subclass overrides this.
_config_cls: type = DeepSeekV3RendererConfig
_implied_thinking_retention = "all"
@@ -63,7 +70,7 @@ class DeepSeekV3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: DeepSeekV3RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -260,7 +267,7 @@ class DeepSeekV3Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -283,6 +290,7 @@ class DeepSeekV3Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — args land in a ```json fence, schema not needed
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_deepseek_v3(
self._tokenizer,
@@ -293,6 +301,12 @@ class DeepSeekV3Renderer:
tool_call_begin_id=self._tool_call_begin,
tool_call_end_id=self._tool_call_end,
tool_sep_id=self._tool_sep,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
assistant_prefix="<|Assistant|>",
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -312,6 +326,23 @@ class DeepSeekV3Renderer:
or reject_assistant_in_extension(new_messages)
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_calls_begin,
assistant_prefix="<|Assistant|>",
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [
*previous_completion_ids,
*list(self._tokenizer.encode("</think>", add_special_tokens=False)),
]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -409,7 +440,9 @@ class DeepSeekV3Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
+885
View File
@@ -0,0 +1,885 @@
"""DeepSeek V4 Flash 0731 renderer.
The checkpoint does not ship a Jinja chat template. Its source of truth is
``encoding/encoding_dsv4.py`` in the model repository. This module mirrors
that encoder while adapting it to the renderer protocol:
* ``enable_thinking=False`` selects the reference encoder's ``chat`` mode;
``True`` selects ``thinking`` mode.
* tools are accepted through :meth:`render` and injected on the first
developer message, otherwise the first system message (the two locations
supported by the reference encoder).
* OpenAI ``tool`` messages are merged into a DeepSeek user turn as
``<tool_result>`` blocks and parallel results are sorted by call order.
* DSML tool calls are parsed back to :class:`ParsedToolCall` records.
Special-token spelling matters: ``|`` is U+FF5C and ``▁`` is U+2581.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Any, Mapping
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
Tokenizer,
ToolSpec,
_content_mask_or_empty,
_get_offset_tokenizer,
_infer_offsets_from_decode,
extract_message_tool_names,
reject_assistant_in_extension,
resolve_thinking_retention,
should_rerender_for_thinking_retention,
trim_to_turn_close,
)
from renderers.configs import DeepSeekV4RendererConfig
from renderers.parsing import parse_deepseek_v4
from renderers.reasoning import prompt_ends_in_reasoning
_BOS = "<|begin▁of▁sentence|>"
_EOS = "<|end▁of▁sentence|>"
_USER = "<|User|>"
_ASSISTANT = "<|Assistant|>"
_LATEST_REMINDER = "<|latest_reminder|>"
_THINK_START = "<think>"
_THINK_END = "</think>"
_DSML = "|DSML|"
_QUERY_ROLES = frozenset({"user", "developer"})
_TASK_TOKENS = {
"action": "<|action|>",
"query": "<|query|>",
"authority": "<|authority|>",
"domain": "<|domain|>",
"title": "<|title|>",
"read_url": "<|read_url|>",
}
_REASONING_EFFORT_PROMPTS = {
"low": "",
"high": (
"Reasoning Effort: Absolute maximum with no shortcuts permitted.\n"
"You MUST be very thorough in your thinking and comprehensively "
"decompose the problem to resolve the root cause, rigorously "
"stress-testing your logic against all potential paths, edge cases, "
"and adversarial scenarios.\n"
"Explicitly write out your entire deliberation process, documenting "
"every intermediate step, considered alternative, and rejected "
"hypothesis to ensure absolutely no assumption is left unchecked.\n\n"
),
"max": (
"Reasoning Effort: Beyond maximum — exhaustive, relentless, and "
"uncompromising.\n"
"You MUST reason with the utmost depth and rigor, leaving absolutely "
"nothing to chance: exhaustively decompose the problem into its most "
"fundamental components, trace every causal chain to its root, and "
"resolve the underlying cause rather than any surface symptom.\n"
"Do not stop reasoning until you have independently verified the "
"solution from multiple angles and are certain that no assumption "
"remains unchecked and no error remains undiscovered.\n\n"
),
}
_TOOLS_TEMPLATE = """## Tools
You have access to a set of tools to help answer the user's question. You can invoke tools by writing a "<{dsml}tool_calls>" block like the following:
<{dsml}tool_calls>
<{dsml}invoke name="$TOOL_NAME">
<{dsml}parameter name="$PARAMETER_NAME" string="true|false">$PARAMETER_VALUE</{dsml}parameter>
...
</{dsml}invoke>
<{dsml}invoke name="$TOOL_NAME2">
...
</{dsml}invoke>
</{dsml}tool_calls>
String parameters should be specified as is and set `string="true"`. For all other types (numbers, booleans, arrays, objects), pass the value in JSON format and set `string="false"`.
If thinking_mode is enabled (triggered by {think_start}), you MUST output your complete reasoning inside {think_start}...{think_end} BEFORE any tool calls or final response.
Otherwise, output directly after {think_end} with tool calls or final response.
### Available Tool Schemas
{tool_schemas}
You MUST strictly follow the above defined tool name and parameter schemas to invoke tool calls.
"""
@dataclass
class _ContentBlock:
kind: str
content: str
message_index: int
tool_call_id: str = ""
@dataclass
class _LogicalMessage:
role: str
message_index: int
content: str = ""
blocks: list[_ContentBlock] = field(default_factory=list)
tool_calls: list[Mapping[str, Any]] = field(default_factory=list)
reasoning_content: str = ""
task: str | None = None
wo_eos: bool = False
response_format: Any = None
def _json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False)
def _text_content(value: Any) -> str:
if value is None:
return ""
if isinstance(value, str):
return value
if not isinstance(value, list):
return str(value)
parts: list[str] = []
for part in value:
if not isinstance(part, Mapping):
continue
part_type = part.get("type")
if part_type == "text":
parts.append(str(part.get("text", "")))
elif part_type == "thinking":
# Structured thinking belongs in ``reasoning_content``. Ignore it
# in visible content rather than leaking it into the answer.
continue
else:
parts.append(f"[Unsupported {part_type}]")
return "\n\n".join(parts)
def _tool_result_content(value: Any) -> str:
if not isinstance(value, list):
return "" if value is None else str(value)
parts: list[str] = []
for part in value:
if isinstance(part, Mapping) and part.get("type") == "text":
parts.append(str(part.get("text", "")))
elif isinstance(part, Mapping):
parts.append(f"[Unsupported {part.get('type')}]")
else:
parts.append(f"[Unsupported {type(part).__name__}]")
return "\n\n".join(parts)
def _reasoning_content(message: Mapping[str, Any]) -> str:
reasoning = message.get("reasoning_content")
if reasoning is None:
reasoning = message.get("reasoning")
if reasoning is not None:
return str(reasoning)
content = message.get("content")
if isinstance(content, list):
return "".join(
str(part.get("thinking", ""))
for part in content
if isinstance(part, Mapping) and part.get("type") == "thinking"
)
return ""
def _tool_function(tool: Mapping[str, Any]) -> Mapping[str, Any]:
function = tool.get("function")
return function if isinstance(function, Mapping) else tool
def _tool_call_function(tool_call: Mapping[str, Any]) -> Mapping[str, Any]:
function = tool_call.get("function")
return function if isinstance(function, Mapping) else tool_call
def _is_query_message(message: Message) -> bool:
"""Match the reference encoder's user/developer query boundary."""
return message.get("role") in _QUERY_ROLES
def _prepare_messages(messages: list[Message]) -> list[_LogicalMessage]:
"""Apply DeepSeek's user/tool merge and parallel-result ordering."""
merged: list[_LogicalMessage] = []
for index, message in enumerate(messages):
role = str(message.get("role") or "")
if role == "tool":
block = _ContentBlock(
kind="tool_result",
content=_tool_result_content(message.get("content")),
message_index=index,
tool_call_id=str(message.get("tool_call_id") or ""),
)
if merged and merged[-1].role == "user":
merged[-1].blocks.append(block)
else:
merged.append(
_LogicalMessage(
role="user",
message_index=index,
blocks=[block],
)
)
continue
if role == "user":
block = _ContentBlock(
kind="text",
content=_text_content(message.get("content")),
message_index=index,
)
if merged and merged[-1].role == "user" and merged[-1].task is None:
merged[-1].blocks.append(block)
else:
merged.append(
_LogicalMessage(
role="user",
message_index=index,
content=block.content,
blocks=[block],
task=message.get("task"),
wo_eos=bool(message.get("wo_eos", False)),
)
)
continue
logical = _LogicalMessage(
role=role,
message_index=index,
content=_text_content(message.get("content")),
task=message.get("task"),
wo_eos=bool(message.get("wo_eos", False)),
response_format=message.get("response_format"),
)
if role == "assistant":
logical.reasoning_content = _reasoning_content(message)
logical.tool_calls = list(message.get("tool_calls") or [])
merged.append(logical)
call_order: dict[str, int] = {}
for message in merged:
if message.role == "assistant" and message.tool_calls:
call_order = {}
for index, tool_call in enumerate(message.tool_calls):
function = _tool_call_function(tool_call)
call_id = tool_call.get("id") or function.get("id")
if call_id:
call_order[str(call_id)] = index
elif message.role == "user":
result_blocks = [b for b in message.blocks if b.kind == "tool_result"]
if len(result_blocks) < 2 or not call_order:
continue
result_blocks.sort(key=lambda b: call_order.get(b.tool_call_id, 0))
ordered = iter(result_blocks)
message.blocks = [
next(ordered) if block.kind == "tool_result" else block
for block in message.blocks
]
return merged
class DeepSeekV4Renderer:
"""Renderer for ``deepseek-ai/DeepSeek-V4-Flash-0731``."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# Task transitions and unterminated assistant continuations can rewrite the prefix.
return False
_implied_thinking_retention = "tool_cycle"
def __init__(
self,
tokenizer: Tokenizer,
config: DeepSeekV4RendererConfig | None = None,
):
self._tokenizer = tokenizer
self.config = config or DeepSeekV4RendererConfig()
implied_retention = (
"tool_cycle"
if self.config.enable_thinking and self.config.drop_thinking
else "all"
)
self.effective_thinking_retention = resolve_thinking_retention(
self.config,
implied_retention,
)
self._bos = self._special_id(_BOS)
self._eos = self._special_id(_EOS)
self._user = self._special_id(_USER)
self._assistant = self._special_id(_ASSISTANT)
self._latest_reminder = self._special_id(_LATEST_REMINDER)
self._think_start = self._special_id(_THINK_START)
self._think_end = self._special_id(_THINK_END)
self._dsml = self._special_id(_DSML)
self._task_ids = {
name: self._special_id(token) for name, token in _TASK_TOKENS.items()
}
def _special_id(self, token: str) -> int:
ids = self._tokenizer.encode(token, add_special_tokens=False)
if len(ids) != 1:
raise ValueError(f"Expected one token for {token!r}, got {ids}")
return ids[0]
def _reasoning_effort_prompt(self) -> str:
"""Text emitted after BOS in thinking mode; subclasses can replace it."""
return _REASONING_EFFORT_PROMPTS[self.config.reasoning_effort]
@staticmethod
def _render_tools(tools: list[ToolSpec]) -> str:
schemas = [_json(dict(_tool_function(tool))) for tool in tools]
return _TOOLS_TEMPLATE.format(
dsml=_DSML,
think_start=_THINK_START,
think_end=_THINK_END,
tool_schemas="\n".join(schemas),
)
@staticmethod
def _render_tool_call(tool_call: Mapping[str, Any]) -> str:
function = _tool_call_function(tool_call)
name = function.get("name")
raw_arguments = function.get("arguments", {})
if isinstance(raw_arguments, str):
try:
arguments = json.loads(raw_arguments)
except (json.JSONDecodeError, TypeError):
arguments = {"arguments": raw_arguments}
elif isinstance(raw_arguments, Mapping):
arguments = dict(raw_arguments)
else:
arguments = {"arguments": raw_arguments}
params: list[str] = []
for key, value in arguments.items():
is_string = isinstance(value, str)
rendered_value = value if is_string else _json(value)
params.append(
f'<{_DSML}parameter name="{key}" '
f'string="{str(is_string).lower()}">{rendered_value}'
f"</{_DSML}parameter>"
)
arguments_text = "\n".join(params)
return f'<{_DSML}invoke name="{name}">\n{arguments_text}\n</{_DSML}invoke>'
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> RenderedTokens:
return self._render(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
add_bos=True,
add_effort_prompt=True,
)
def _render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None,
add_generation_prompt: bool,
add_bos: bool,
add_effort_prompt: bool,
) -> RenderedTokens:
if not messages:
raise ValueError("No messages provided.")
logical_messages = _prepare_messages(messages)
if not logical_messages:
raise ValueError("No renderable messages provided.")
effective_drop_thinking = self.config.drop_thinking and not tools
if self.config.enable_thinking and effective_drop_thinking:
last_query = max(
(
index
for index, message in enumerate(logical_messages)
if message.role in _QUERY_ROLES
),
default=-1,
)
# The reference encoder removes internal developer/search-agent
# messages before the latest query when historical thinking is
# dropped. Public tool flows retain them because tools force
# ``effective_drop_thinking=False``.
logical_messages = [
message
for index, message in enumerate(logical_messages)
if message.role != "developer" or index >= last_query
]
token_ids: list[int] = []
message_indices: list[int] = []
sampled_mask: list[bool] = []
is_content: list[bool] = []
pending_text: list[tuple[str, int, bool, bool]] = []
def emit_ids(
ids: list[int],
message_index: int,
*,
sampled: bool = False,
content: bool = False,
) -> None:
token_ids.extend(ids)
message_indices.extend([message_index] * len(ids))
sampled_mask.extend([sampled] * len(ids))
is_content.extend([content] * len(ids))
def flush_text() -> None:
"""Tokenize contiguous text once, preserving source metadata.
The official encoder builds one prompt string. Encoding renderer
fragments independently can therefore change BPE merges at their
boundaries even when the decoded text is identical. Offset maps
let us recover message/sample/content attribution after the
required single encoding pass.
"""
if not pending_text:
return
full_text = "".join(text for text, *_ in pending_text)
if not full_text:
pending_text.clear()
return
spans: list[tuple[int, int, int, bool, bool]] = []
position = 0
for text, message_index, sampled, content in pending_text:
end = position + len(text)
if end > position:
spans.append((position, end, message_index, sampled, content))
position = end
offset_tokenizer = _get_offset_tokenizer(self._tokenizer)
if offset_tokenizer is None:
text_ids = self._tokenizer.encode(
full_text,
add_special_tokens=False,
)
offsets = _infer_offsets_from_decode(
self._tokenizer,
text_ids,
full_text,
)
has_content_attribution = False
if offsets is None:
# Token IDs remain exact even when a lossy decoder makes
# source boundaries unrecoverable. Text runs separated by
# special tokens have one sampled state, so retain that
# signal and associate the opaque run with a contributing
# caller message.
fallback_message_index = next(
(
span_message_index
for _, _, span_message_index, _, _ in spans
if span_message_index >= 0
),
spans[-1][2] if spans else -1,
)
fallback_sampled = spans[-1][3] if spans else False
emit_ids(
text_ids,
fallback_message_index,
sampled=fallback_sampled,
)
pending_text.clear()
return
else:
encoding = offset_tokenizer(
full_text,
add_special_tokens=False,
return_offsets_mapping=True,
)
text_ids = list(encoding["input_ids"])
offsets = list(encoding["offset_mapping"])
has_content_attribution = True
fallback = spans[-1][2:] if spans else (-1, False, False)
for token_id, (start, end) in zip(text_ids, offsets):
metadata: tuple[int, bool, bool] = fallback
for (
span_start,
span_end,
span_message_index,
span_sampled,
span_content,
) in spans:
if span_start <= start < span_end:
metadata = (
span_message_index,
span_sampled,
span_content,
)
break
message_index, sampled, content = metadata
if has_content_attribution and end > start:
# Preserve every body byte when a BPE token straddles a
# scaffold/content boundary. This intentionally permits a
# few adjacent scaffold bytes to share the content bit.
content = any(
span_content
for span_start, span_end, _, _, span_content in spans
if span_start < end and start < span_end
)
elif not has_content_attribution:
content = False
emit_ids(
[token_id],
message_index,
sampled=sampled,
content=content,
)
pending_text.clear()
def emit_special(
token_id: int,
message_index: int,
*,
sampled: bool = False,
content: bool = False,
) -> None:
flush_text()
emit_ids(
[token_id],
message_index,
sampled=sampled,
content=content,
)
def emit_text(
text: str,
message_index: int,
*,
sampled: bool = False,
content: bool = False,
) -> None:
if text:
pending_text.append((text, message_index, sampled, content))
if add_bos:
emit_special(self._bos, -1)
if add_effort_prompt and self.config.enable_thinking:
emit_text(self._reasoning_effort_prompt(), -1)
last_query_index = -1
for index, message in enumerate(logical_messages):
if message.role in _QUERY_ROLES:
last_query_index = index
tool_target: int | None = None
if tools:
tool_target = next(
(
index
for index, message in enumerate(logical_messages)
if message.role == "developer"
),
None,
)
if tool_target is None:
tool_target = next(
(
index
for index, message in enumerate(logical_messages)
if message.role == "system"
),
None,
)
if tool_target is None:
# Equivalent to an empty synthetic system message carrying
# tools in the reference encoder.
emit_text("\n\n" + self._render_tools(tools), -1)
for index, message in enumerate(logical_messages):
role = message.role
msg_idx = message.message_index
if role == "system":
emit_text(message.content, msg_idx, content=True)
elif role == "developer":
if not message.content:
raise ValueError("Developer messages require content.")
emit_special(self._user, msg_idx)
emit_text(message.content, msg_idx, content=True)
elif role == "user":
emit_special(self._user, msg_idx)
for block_index, block in enumerate(message.blocks):
if block_index:
emit_text("\n\n", block.message_index)
if block.kind == "tool_result":
emit_text("<tool_result>", block.message_index)
emit_text(
block.content,
block.message_index,
content=True,
)
emit_text("</tool_result>", block.message_index)
else:
emit_text(
block.content,
block.message_index,
content=True,
)
elif role == "latest_reminder":
emit_special(self._latest_reminder, msg_idx)
emit_text(message.content, msg_idx, content=True)
elif role == "assistant":
previous_has_task = (
index > 0 and logical_messages[index - 1].task is not None
)
keep_reasoning = (
self.config.enable_thinking
and not previous_has_task
and (not effective_drop_thinking or index > last_query_index)
)
if keep_reasoning:
emit_text(
message.reasoning_content,
msg_idx,
sampled=True,
content=True,
)
emit_special(
self._think_end,
msg_idx,
sampled=True,
content=True,
)
emit_text(
message.content,
msg_idx,
sampled=True,
content=True,
)
if message.tool_calls:
rendered_calls = "\n".join(
self._render_tool_call(call) for call in message.tool_calls
)
emit_text(
f"\n\n<{_DSML}tool_calls>\n{rendered_calls}\n"
f"</{_DSML}tool_calls>",
msg_idx,
sampled=True,
content=True,
)
if not message.wo_eos:
emit_special(
self._eos,
msg_idx,
sampled=True,
content=True,
)
else:
raise ValueError(f"Unsupported DeepSeek V4 role: {role!r}")
if tools and index == tool_target:
emit_text("\n\n" + self._render_tools(tools), msg_idx)
if message.response_format is not None and role in {
"system",
"developer",
}:
emit_text(
"\n\n## Response Format:\n\n"
"You MUST strictly adhere to the following schema to reply:\n"
+ _json(message.response_format),
msg_idx,
)
next_role = (
logical_messages[index + 1].role
if index + 1 < len(logical_messages)
else None
)
transition_needed = next_role in {"assistant", "latest_reminder"}
if next_role is None:
transition_needed = message.task is not None or add_generation_prompt
if not transition_needed:
continue
task = message.task
transition_msg_idx = -1
if next_role is not None:
for following in logical_messages[index + 1 :]:
if following.role == "assistant":
transition_msg_idx = following.message_index
break
if task is not None:
if task not in self._task_ids:
raise ValueError(
f"Invalid DeepSeek V4 task {task!r}; expected one of "
f"{sorted(self._task_ids)}"
)
if task != "action":
emit_special(self._task_ids[task], transition_msg_idx)
continue
emit_special(self._assistant, transition_msg_idx)
emit_special(
self._think_start
if self.config.enable_thinking
else self._think_end,
transition_msg_idx,
)
emit_special(self._task_ids[task], transition_msg_idx)
continue
if role not in _QUERY_ROLES:
continue
emit_special(self._assistant, transition_msg_idx)
open_thinking = self.config.enable_thinking and (
not effective_drop_thinking or index >= last_query_index
)
emit_special(
self._think_start if open_thinking else self._think_end,
transition_msg_idx,
)
flush_text()
return RenderedTokens(
token_ids=token_ids,
message_indices=message_indices,
sampled_mask=sampled_mask,
is_content=_content_mask_or_empty(self._tokenizer, is_content),
message_roles=[message.get("role") or "" for message 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, # noqa: ARG002
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_deepseek_v4(
self._tokenizer,
token_ids,
stop_ids={self._eos},
thinking_enabled=(
prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
assistant_prefix="<|Assistant|>",
)
if prompt_ids
else self.config.enable_thinking
),
think_end_id=self._think_end,
think_start_id=self._think_start,
)
def get_stop_token_ids(self) -> list[int]:
return [self._eos]
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
boundary = self.parse_response(
previous_completion_ids, prompt_ids=previous_prompt_ids, tools=tools
)
if boundary.reasoning_complete is False:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
is_user_query=_is_query_message,
):
return None
# Full rendering sorts parallel tool results by IDs from the issuing
# assistant. The bridge only receives the new slice, so it cannot
# prove parity when more than one result is present.
if sum(message.get("role") == "tool" for message in new_messages) > 1:
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._eos},
synthesize_close=self._eos,
)
if previous_ids is None:
return None
try:
extension = self._render(
new_messages,
tools=None,
add_generation_prompt=True,
add_bos=False,
add_effort_prompt=False,
)
except ValueError:
return None
prior_length = len(previous_ids)
return RenderedTokens(
token_ids=previous_ids + extension.token_ids,
message_indices=[-1] * prior_length + extension.message_indices,
sampled_mask=[False] * (prior_length + len(extension.token_ids)),
is_content=_content_mask_or_empty(
self._tokenizer,
[False] * prior_length + extension.is_content,
),
message_roles=extension.message_roles,
message_tool_names=extension.message_tool_names,
)
__all__ = ["DeepSeekV4Renderer"]
+58 -32
View File
@@ -11,9 +11,10 @@ from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
ChatTemplateTokenizer,
Message,
ParsedResponse,
RenderedTokens,
@@ -21,9 +22,14 @@ from renderers.base import (
extract_message_tool_names,
resolve_thinking_retention,
)
from renderers.parsing import (
_reasoning_end_token_index,
_strip_stop_tokens,
)
from renderers.configs import DefaultRendererConfig
from renderers.hermes import HermesToolParser
from renderers.parsers import (
ThinkTextReasoningParser,
get_reasoning_parser,
get_tool_parser,
)
@@ -91,9 +97,15 @@ class DefaultRenderer:
:class:`renderers.DefaultRendererConfig`).
"""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# An opaque Jinja template cannot promise prefix stability.
return False
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: ChatTemplateTokenizer,
config: DefaultRendererConfig | None = None,
):
cfg = config or DefaultRendererConfig()
@@ -110,8 +122,6 @@ class DefaultRenderer:
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
)
@@ -180,50 +190,66 @@ class DefaultRenderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — DefaultRenderer relies on configured tool_parser, schema not consulted here
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
ids = _strip_stop_tokens(token_ids, set(self.get_stop_token_ids()))
boundary = scan_reasoning(
self._tokenizer,
ids,
prefilled=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
),
)
if boundary.is_open:
return ParsedResponse(
content="", reasoning_content=boundary.text, reasoning_complete=False
)
reasoning_end = (
_reasoning_end_token_index(self._tokenizer, ids)
if boundary.text is not None
else 0
)
# 1. Extract tool calls while we still have token ids (most formats
# use special-token delimiters, so id-level matching is reliable).
if self._tool_parser is not None:
content_ids, tool_calls = self._tool_parser.extract(list(token_ids))
content_ids, tool_calls = self._tool_parser.extract(ids[reasoning_end:])
content_ids = [*ids[:reasoning_end], *content_ids]
for tc in tool_calls:
if tc.token_span is not None:
start, end = tc.token_span
tc.token_span = (start + reasoning_end, end + reasoning_end)
else:
content_ids = list(token_ids)
content_ids = ids
tool_calls = []
# 2. Decode (keep special tokens so a downstream reasoning parser can
# still see things like <think>/</think> when they're tokens).
text = self._tokenizer.decode(content_ids, skip_special_tokens=False)
# 3. Extract reasoning from the decoded text. Falls back to a built-in
# <think>...</think> sniff so unconfigured users get the same behavior
# as before. Preserve whitespace at the <think>/</think> boundary —
# the chat template round-trips it verbatim (e.g. GLM emits
# `{{ '\\n<think>' + reasoning_content + '</think>' }}` then
# `{{- content }}` with no separator), so a leading `\\n` on content
# or trailing `\\n` on reasoning_content must stay in the parsed
# fields for re-render to be byte-identical. Stripping here causes
# the re-rendered assistant message to shift by one BPE token after
# `</think>`, cascading through downstream tokenization and breaking
# the "extension property" in trajectory step tokenization.
if self._reasoning_parser is not None:
reasoning_content, text = self._reasoning_parser.extract(text)
# Use the same initial boundary for extraction and tool scanning.
# Preserve whitespace inside reasoning and after its close: templates
# may emit these fields back-to-back, so stripping shifts token offsets.
if self._reasoning_parser is None or isinstance(
self._reasoning_parser, ThinkTextReasoningParser
):
reasoning_content = boundary.text
if boundary.text is not None:
text = text.partition("</think>")[2]
else:
reasoning_content = None
if "</think>" in text:
before, after = text.split("</think>", 1)
if "<think>" in before:
reasoning_content = before.split("<think>", 1)[-1]
else:
reasoning_content = before
text = after
reasoning_content, text = self._reasoning_parser.extract(text)
# Strip any remaining special tokens from the final content (we kept
# them around for the reasoning parser above).
text = _strip_special_tokens(self._tokenizer, text)
return ParsedResponse(
content=text,
reasoning_content=reasoning_content if reasoning_content else None,
tool_calls=tool_calls,
reasoning_complete=True
if isinstance(self._reasoning_parser, ThinkTextReasoningParser)
or reasoning_content is not None
else None,
)
def get_stop_token_ids(self) -> list[int]:
@@ -258,9 +284,9 @@ def _resolve_parser(value, tokenizer, factory):
def _strip_special_tokens(tokenizer, text: str) -> str:
"""Remove any special-token substrings that slipped into decoded text."""
"""Remove framing tokens while preserving literal think markers in content."""
specials = getattr(tokenizer, "all_special_tokens", None) or []
for token in specials:
if token and token in text:
if token and token not in {"<think>", "</think>"} and token in text:
text = text.replace(token, "")
return text
+1432
View File
File diff suppressed because it is too large Load Diff
+34 -40
View File
@@ -13,13 +13,13 @@ from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
Tokenizer,
ToolSpec,
_content_mask_or_empty,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -53,9 +53,15 @@ _TOOLS_FOOTER = (
class GLM45Renderer:
"""Deterministic message → token renderer for GLM-4.5 Air models."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# Historical reasoning is stripped regardless of bridge policy.
return False
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: GLM45RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -190,20 +196,8 @@ 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.
# A user/tool role marker that closes generation belongs to
# the preceding assistant's sampled output, not the next body.
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
if role == "system":
@@ -217,9 +211,9 @@ class GLM45Renderer:
elif role == "user":
emit_special(
self._user,
i,
i - 1 if closes_assistant_turn else i,
is_sampled=closes_assistant_turn,
is_content=False,
is_content=closes_assistant_turn,
)
# ``\n`` is scaffold; ``content`` is body; the optional
# ``/nothink`` suffix is scaffold the renderer injects
@@ -262,7 +256,7 @@ class GLM45Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -285,6 +279,7 @@ class GLM45Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_glm(
self._tokenizer,
@@ -299,6 +294,7 @@ class GLM45Renderer:
arg_value_id=self._arg_value,
arg_value_end_id=self._arg_value_end,
tools=tools,
thinking_enabled=self.config.enable_thinking,
)
def get_stop_token_ids(self) -> list[int]:
@@ -319,6 +315,14 @@ class GLM45Renderer:
):
return None
boundary = self.parse_response(
previous_completion_ids, prompt_ids=previous_prompt_ids, tools=tools
)
if boundary.reasoning_complete is False:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -449,7 +453,9 @@ class GLM45Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
@@ -483,15 +489,9 @@ class GLM45Renderer:
# (think block + content + tool calls) is the model-sampled
# portion.
#
# GLM-4.5 does NOT emit an explicit per-turn close token inside
# the assistant message; the next message's role marker
# (``<|user|>`` / ``<|observation|>`` / ``<|endoftext|>``) acts
# as the stop signal at inference, and those tokens are
# attributed to the *next* message (or are absent on the final
# turn). So no sampled stop-signal token lives inside this
# assistant span — content / think / tool_calls carry the
# is_sampled=True signal.
#
# The next user/tool role marker closes this assistant turn and
# is attributed here when that later message is rendered.
# 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.
@@ -573,23 +573,17 @@ class GLM45Renderer:
emit_text,
emit_text_segments,
) -> None:
# 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.
# Tool bodies keep their own attribution; a sampled observation
# marker belongs to the assistant that generated it.
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
closes_assistant_turn = prev_role == "assistant"
if prev_role != "tool":
emit_special(
self._observation,
msg_idx,
msg_idx - 1 if closes_assistant_turn else msg_idx,
is_sampled=closes_assistant_turn,
is_content=False,
is_content=closes_assistant_turn,
)
emit_text_segments(
+250 -55
View File
@@ -14,20 +14,24 @@ from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
Tokenizer,
ToolSpec,
_content_mask_or_empty,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
resolve_thinking_retention,
should_rerender_for_thinking_retention,
)
from renderers.configs import GLM5RendererConfig, GLM51RendererConfig
from renderers.configs import (
GLM5RendererConfig,
GLM51RendererConfig,
GLM53RendererConfig,
)
from renderers.parsing import parse_glm
_TOOLS_HEADER = (
@@ -51,6 +55,14 @@ _TOOLS_FOOTER = (
class GLM5Renderer:
"""Deterministic message → token renderer for GLM-5 models."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# GLM-5.1 also changes empty thinking wrappers across user boundaries.
return not self.config.clear_thinking and not (
self.empty_think_on_last_assistant and self.config.enable_thinking
)
# GLM-5.1 flips this on: even when the most-recent assistant has no
# reasoning content, the template wraps it with ``<think></think>``
# instead of just emitting ``</think>`` as a separator. Subclassed in
@@ -64,14 +76,14 @@ class GLM5Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: GLM5RendererConfig | GLM51RendererConfig | None = None,
):
self._tokenizer = tokenizer
self.config = config or type(self)._config_cls()
if not self.config.clear_thinking:
implied_thinking_retention = "all"
elif not self.config.enable_thinking:
elif not getattr(self.config, "enable_thinking", True):
implied_thinking_retention = "all"
else:
implied_thinking_retention = "tool_cycle"
@@ -219,20 +231,8 @@ 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.
# A user/tool role marker that closes generation belongs to
# the preceding assistant's sampled output, not the next body.
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
if role == "system":
@@ -242,9 +242,9 @@ class GLM5Renderer:
elif role == "user":
emit_special(
self._user,
i,
i - 1 if closes_assistant_turn else i,
is_sampled=closes_assistant_turn,
is_content=False,
is_content=closes_assistant_turn,
)
emit_text(content, i, is_sampled=False, is_content=True)
@@ -260,35 +260,62 @@ class GLM5Renderer:
)
elif role == "tool":
self._render_tool(
messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
if i == 0 or messages[i - 1]["role"] != "tool":
for position, tool_idx in enumerate(
self._ordered_tool_indices(messages, i)
):
tool_message = messages[tool_idx]
self._render_tool(
tool_idx,
self._visible_text(tool_message.get("content")),
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
starts_block=position == 0,
closing_assistant_index=(
i - 1
if position == 0 and closes_assistant_turn
else None
),
)
# ── 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 / is_content=False.
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)
self._emit_generation_prompt(emit_special)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def _emit_generation_prompt(self, emit_special) -> None:
"""Generation prompt: ``<|assistant|><think>`` when thinking is on, or
``<|assistant|></think>`` when ``enable_thinking=False``. A subclass can
override this to prefill a different prompt."""
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
if getattr(self.config, "enable_thinking", True):
emit_special(self._think, -1, is_sampled=False, is_content=False)
else:
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
@staticmethod
def _ordered_tool_indices(messages: list[Message], block_start: int) -> list[int]:
"""Return one contiguous tool block in its source order."""
block_end = block_start
while (
block_end + 1 < len(messages)
and messages[block_end + 1].get("role") == "tool"
):
block_end += 1
return list(range(block_start, block_end + 1))
def render_ids(
self,
messages: list[Message],
@@ -307,6 +334,7 @@ class GLM5Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_glm(
self._tokenizer,
@@ -321,6 +349,7 @@ class GLM5Renderer:
arg_value_id=self._arg_value,
arg_value_end_id=self._arg_value_end,
tools=tools,
thinking_enabled=getattr(self.config, "enable_thinking", True),
)
def get_stop_token_ids(self) -> list[int]:
@@ -341,6 +370,14 @@ class GLM5Renderer:
):
return None
boundary = self.parse_response(
previous_completion_ids, prompt_ids=previous_prompt_ids, tools=tools
)
if boundary.reasoning_complete is False:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -455,18 +492,16 @@ class GLM5Renderer:
return None
# Generation prompt — match the gen-prompt branch of ``render()``.
emit_special(self._assistant, -1)
if self.config.enable_thinking:
emit_special(self._think, -1)
else:
emit_special(self._think_end, -1)
self._emit_generation_prompt(emit_special)
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
@@ -601,31 +636,29 @@ class GLM5Renderer:
def _render_tool(
self,
messages: list[Message],
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
emit_text_segments,
starts_block: bool = False,
closing_assistant_index: int | None = None,
) -> None:
# 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"
# Tool bodies keep their own attribution; a sampled observation
# marker belongs to the assistant that generated it.
# The caller supplies the block's assistant because results may
# be reordered relative to their input-message indices.
closes_assistant_turn = closing_assistant_index is not None
if prev_role != "tool":
if starts_block:
emit_special(
self._observation,
msg_idx,
closing_assistant_index
if closing_assistant_index is not None
else msg_idx,
is_sampled=closes_assistant_turn,
is_content=False,
is_content=closes_assistant_turn,
)
emit_special(
@@ -659,3 +692,165 @@ class GLM51Renderer(GLM5Renderer):
spec = tool["function"] if "function" in tool else tool
spec = {k: v for k, v in spec.items() if k not in ("defer_loading", "strict")}
return json.dumps(spec, ensure_ascii=False)
class GLM53Renderer(GLM5Renderer):
"""Deterministic message → token renderer for GLM-5.3 models.
GLM-5.3 adds a reasoning-effort system preamble and always starts an
assistant generation with ``<think>``. Its template also orders a tool
result block by the preceding assistant's tool-call IDs.
"""
_config_cls = GLM53RendererConfig
@staticmethod
def _visible_text(content: Any) -> str:
# The GLM-5.3 template omits ``None`` content instead of rendering
# Python's string representation (notably tool-call-only assistants).
return "" if content is None else GLM5Renderer._visible_text(content)
def __init__(
self,
tokenizer: Tokenizer,
config: GLM53RendererConfig | None = None,
):
super().__init__(tokenizer, config)
self.effective_thinking_retention = resolve_thinking_retention(
self.config,
"tool_cycle" if self.config.clear_thinking else "all",
)
@staticmethod
def _format_tool_spec(tool: ToolSpec) -> str:
spec = tool["function"] if "function" in tool else tool
spec = {k: v for k, v in spec.items() if k not in ("defer_loading", "strict")}
return json.dumps(spec, ensure_ascii=False)
def _ordered_tool_indices(
self, messages: list[Message], block_start: int
) -> list[int]:
"""Match the template's safe tool-result reordering rule."""
block_end = block_start
while (
block_end + 1 < len(messages)
and messages[block_end + 1].get("role") == "tool"
):
block_end += 1
previous = messages[block_start - 1] if block_start else {}
calls = (
previous.get("tool_calls") if previous.get("role") == "assistant" else None
)
if not calls:
return list(range(block_start, block_end + 1))
call_ids = [call.get("id") or call.get("tool_call_id") for call in calls]
result_ids = [
message.get("tool_call_id") or message.get("id")
for message in messages[block_start : block_end + 1]
]
if (
any(identifier is None for identifier in call_ids + result_ids)
or len(set(call_ids)) != len(call_ids)
or len(set(result_ids)) != len(result_ids)
or set(call_ids) != set(result_ids)
):
return list(range(block_start, block_end + 1))
by_id = {
identifier: index
for identifier, index in zip(result_ids, range(block_start, block_end + 1))
}
return [by_id[identifier] for identifier in call_ids]
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> RenderedTokens:
rendered = super().render(
messages, tools=tools, add_generation_prompt=add_generation_prompt
)
# GLM-5.3's preamble belongs immediately after ``[gMASK]<sop>``.
prefix = [self._gmask, self._sop]
preamble = [self._system] + self._encode(
f"Reasoning Effort: {self.config.reasoning_effort.capitalize()}"
)
assert rendered.token_ids[:2] == prefix
insertion = len(prefix)
rendered.token_ids[insertion:insertion] = preamble
rendered.message_indices[insertion:insertion] = [-1] * len(preamble)
rendered.sampled_mask[insertion:insertion] = [False] * len(preamble)
if rendered.is_content:
rendered.is_content[insertion:insertion] = [False] * len(preamble)
return rendered
def _render_assistant(
self,
msg,
msg_idx,
content,
last_user_index,
*,
emit_special,
emit_text,
emit_text_segments,
):
reasoning_content = ""
has_reasoning = False
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
has_reasoning = True
elif "</think>" in content:
before, after = content.split("</think>", 1)
reasoning_content = before.split("<think>")[-1].strip()
content = after.strip()
has_reasoning = True
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
include_thinking = has_reasoning and (
not self.config.clear_thinking or msg_idx > last_user_index
)
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
if include_thinking:
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)
if content.strip():
emit_text(content.strip(), msg_idx, is_sampled=True, is_content=True)
self._render_tool_calls(
msg, msg_idx, emit_special=emit_special, emit_text=emit_text
)
def _render_tool_calls(self, msg, msg_idx, *, emit_special, emit_text) -> None:
for tc in msg.get("tool_calls") or []:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
if isinstance(arguments, str):
arguments = json.loads(arguments)
emit_special(self._tool_call_tok, msg_idx, is_sampled=True, is_content=True)
emit_text(func.get("name", ""), msg_idx, is_sampled=True, is_content=True)
for arg_name, arg_value in arguments.items():
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)
emit_text(
arg_value
if isinstance(arg_value, str)
else 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, is_content=True
)
emit_special(
self._tool_call_end_tok, msg_idx, is_sampled=True, is_content=True
)
+74 -8
View File
@@ -49,13 +49,13 @@ from openai_harmony import (
ToolDescription,
load_harmony_encoding,
)
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
extract_message_tool_names,
reject_assistant_in_extension,
resolve_thinking_retention,
@@ -63,7 +63,7 @@ from renderers.base import (
trim_to_turn_close,
)
from renderers.configs import GptOssRendererConfig
from renderers.parsing import parse_gpt_oss
from renderers.parsing import harmony_blocks, parse_gpt_oss
def _reasoning_effort(effort: str | None) -> ReasoningEffort:
@@ -121,9 +121,15 @@ def _arguments_to_str(arguments: Any) -> str:
class GptOssRenderer:
"""Deterministic message → token renderer for OpenAI gpt-oss (harmony)."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# The final assistant terminator changes even when auto_drop_analysis=False.
return False
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: GptOssRendererConfig | None = None,
):
"""Initialise the renderer.
@@ -462,7 +468,7 @@ class GptOssRenderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -480,15 +486,39 @@ class GptOssRenderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def _response_prefix(
self, token_ids: list[int], prompt_ids: list[int] | None
) -> list[int]:
"""Recover the Harmony header supplied by the generation prompt."""
if prompt_ids and (not token_ids or token_ids[0] != self._start):
if self._start in prompt_ids:
start = len(prompt_ids) - 1 - prompt_ids[::-1].index(self._start)
tail = prompt_ids[start:]
if self._message in tail:
return tail[: tail.index(self._message) + 1]
return []
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — harmony args land in a JSON object, schema not needed
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_gpt_oss(
prefix = self._response_prefix(token_ids, prompt_ids)
if not prefix and (not token_ids or token_ids[0] != self._start):
end = next(
(i for i, t in enumerate(token_ids) if t in self.get_stop_token_ids()),
len(token_ids),
)
return ParsedResponse(
content=self._tokenizer.decode(
token_ids[:end], skip_special_tokens=False
)
)
parsed = parse_gpt_oss(
self._tokenizer,
token_ids,
[*prefix, *token_ids],
return_id=self._return,
call_id=self._call,
start_id=self._start,
@@ -498,6 +528,12 @@ class GptOssRenderer:
constrain_id=self._constrain,
)
for tc in parsed.tool_calls:
if tc.token_span is not None:
start, end = tc.token_span
tc.token_span = (max(0, start - len(prefix)), end - len(prefix))
return parsed
def get_stop_token_ids(self) -> list[int]:
return [self._return, self._call]
@@ -522,6 +558,34 @@ class GptOssRenderer:
):
return None
# Harmony closes analysis with <|end|> or <|call|>, not <|return|>.
# Inspect framing only; the bridge never needs tool arguments.
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
end = (
previous_completion_ids.index(self._return)
if self._return in previous_completion_ids
else len(previous_completion_ids)
)
ids = [
*self._response_prefix(previous_completion_ids, previous_prompt_ids),
*previous_completion_ids[:end],
]
for start, header_end, body_end, closed in harmony_blocks(
ids,
start_id=self._start,
message_id=self._message,
end_id=self._end,
call_id=self._call,
):
header = ids[start + 1 : header_end]
if not closed and body_end == len(ids) and self._channel in header:
channel = self._tokenizer.decode(
header[header.index(self._channel) + 1 :],
skip_special_tokens=False,
).split()
if channel and channel[0] == "analysis":
return None
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -598,7 +662,9 @@ class GptOssRenderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
-149
View File
@@ -1,149 +0,0 @@
"""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
+80 -13
View File
@@ -27,13 +27,17 @@ from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_get_offset_tokenizer,
_infer_offsets_from_decode,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -72,9 +76,17 @@ _TOOL_RESPONSE_END = f"</tool_response{_HYTK}>"
class Hy3Renderer:
"""Deterministic message → token renderer for Tencent Hy3 models."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# Require retention regardless of whether tools are supplied.
return not self.config.raw_last_assistant and (
self.config.is_training or self.config.preserved_thinking is True
)
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Hy3RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -239,13 +251,34 @@ class Hy3Renderer:
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"])
offset_tokenizer = _get_offset_tokenizer(self._tokenizer)
if offset_tokenizer is None:
token_ids = self._encode(full_text)
offsets = _infer_offsets_from_decode(
self._tokenizer,
token_ids,
full_text,
)
if offsets is None:
# Token IDs remain exact even when a lossy decoder prevents
# reconstructing boundaries. Associate the opaque joined run
# with a contributing caller system message rather than
# silently classifying its body as global scaffold.
fallback_idx = next(
(msg_idx for text, _, msg_idx in segments if text and msg_idx >= 0),
-1,
)
return [(token_id, False, fallback_idx) for token_id in token_ids]
has_content_attribution = False
else:
encoding = offset_tokenizer(
full_text,
add_special_tokens=False,
return_offsets_mapping=True,
)
token_ids = list(encoding["input_ids"])
offsets = list(encoding["offset_mapping"])
has_content_attribution = True
spans: list[tuple[int, int, bool, int]] = []
pos = 0
@@ -255,13 +288,19 @@ class Hy3Renderer:
total_len = pos
out: list[tuple[int, bool, int]] = []
last = (spans[-1][2], spans[-1][3])
last = (
spans[-1][2] if has_content_attribution else False,
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)
attr = (
seg_is_content if has_content_attribution else False,
seg_idx,
)
break
out.append((tok_id, attr[0], attr[1]))
return out
@@ -432,7 +471,7 @@ class Hy3Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -560,6 +599,7 @@ class Hy3Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_hy3(
self._tokenizer,
@@ -577,6 +617,14 @@ class Hy3Renderer:
arg_value_id=self._arg_value,
arg_value_end_id=self._arg_value_end,
tools=tools,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
open_marker=_THINK,
close_marker=_THINK_END,
stop_ids=set(self.get_stop_token_ids()),
assistant_prefix="<|hy_Assistant:opensource|>",
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -599,6 +647,23 @@ class Hy3Renderer:
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_calls,
open_id=self._think,
close_id=self._think_end,
open_marker=_THINK,
close_marker=_THINK_END,
assistant_prefix="<|hy_Assistant:opensource|>",
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self._thinking_retention_for(tools),
new_messages,
@@ -700,7 +765,9 @@ class Hy3Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
+1049
View File
File diff suppressed because it is too large Load Diff
+38 -4
View File
@@ -16,13 +16,15 @@ from __future__ import annotations
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
extract_message_tool_names,
reject_assistant_in_extension,
resolve_thinking_retention,
@@ -45,9 +47,14 @@ class KimiK2Renderer:
but have no effect on the byte-level output.
"""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
return True
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: KimiK2RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -310,7 +317,7 @@ class KimiK2Renderer:
token_ids=token_ids,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in caller_messages],
message_tool_names=extract_message_tool_names(caller_messages),
)
@@ -333,6 +340,7 @@ class KimiK2Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — section-JSON wire format quotes strings, schema not needed
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_kimi_k2(
self._tokenizer,
@@ -343,6 +351,12 @@ class KimiK2Renderer:
tool_call_begin_id=self._tool_call_begin,
tool_call_argument_begin_id=self._tool_call_argument_begin,
tool_call_end_id=self._tool_call_end,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
assistant_prefix="<|im_assistant|>assistant<|im_middle|>",
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -362,6 +376,24 @@ class KimiK2Renderer:
or reject_assistant_in_extension(new_messages)
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_calls_section_begin,
tool_start_closes_reasoning=True,
assistant_prefix="<|im_assistant|>assistant<|im_middle|>",
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [
*previous_completion_ids,
*list(self._tokenizer.encode("</think>", add_special_tokens=False)),
]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -465,7 +497,9 @@ class KimiK2Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
+99 -110
View File
@@ -25,7 +25,7 @@ import json
import re
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
@@ -36,6 +36,9 @@ from renderers.base import (
RenderedTokens,
ToolCallParseStatus,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_require_transformers,
extract_message_tool_names,
reject_assistant_in_extension,
resolve_thinking_retention,
@@ -43,7 +46,11 @@ from renderers.base import (
trim_to_turn_close,
)
from renderers.configs import KimiK25RendererConfig
from renderers.parsing import _reasoning_end_token_index, parse_kimi_k2_section
from renderers.parsing import (
_find,
_reasoning_end_token_index,
parse_kimi_k2_section,
)
from renderers.qwen3_vl import (
_image_hash,
_is_image_part,
@@ -422,8 +429,7 @@ def _parse_kimi_k2_response(
token_ids: list[int],
*,
stop_ids: set[int],
think_open_ids: list[int],
think_close_ids: list[int],
prefilled_thinking: bool,
tool_calls_section_begin_id: int | None,
tool_calls_section_end_id: int | None,
tool_call_begin_id: int | None,
@@ -443,8 +449,7 @@ def _parse_kimi_k2_response(
probe). Spans stay ``None`` here since text positions don't cheaply map
back to token offsets across BPE.
``<think>...</think>`` is always text-extracted from the content slice
(K2.5 emits them as plain text, not special tokens).
Initial reasoning is identified before scanning tool-call sections.
"""
# Strip stop token
ids = list(token_ids)
@@ -453,12 +458,31 @@ def _parse_kimi_k2_response(
ids = ids[:i]
break
boundary = scan_reasoning(
tokenizer,
ids,
tool_start_id=tool_calls_section_begin_id,
tool_start_closes_reasoning=True,
prefilled=prefilled_thinking,
assistant_prefix="<|im_assistant|>assistant<|im_middle|>",
)
if boundary.is_open:
return ParsedResponse(
content="", reasoning_content=boundary.text, reasoning_complete=False
)
# 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)
# Without </think>, the section opener itself ends reasoning.
if boundary.closed_by_tool:
reasoning_end = _find(ids, tool_calls_section_begin_id)
elif boundary.text is not None:
reasoning_end = _reasoning_end_token_index(tokenizer, ids)
else:
reasoning_end = 0
# Token-ID path — produces spans. Only run if every relevant special
# token resolved at init (i.e. is in the tokenizer's vocab).
@@ -481,6 +505,8 @@ def _parse_kimi_k2_response(
tool_call_end_id=tool_call_end_id,
scan_start=reasoning_end,
)
if boundary.closed_by_tool:
content_ids = content_ids[reasoning_end:]
text = (
tokenizer.decode(content_ids, skip_special_tokens=False)
if content_ids
@@ -534,32 +560,9 @@ def _parse_kimi_k2_response(
)
)
# Extract reasoning from <think>...</think> in the content text. Partition
# on <think> first so any tokens BEFORE the open tag (e.g. the assistant
# role tag, when the caller slices the completion to include the prompt's
# gen-prompt-equivalent) don't leak into reasoning_content.
reasoning: str | None = None
if "<think>" in text:
_, _, after_open = text.partition("<think>")
if "</think>" in after_open:
reasoning_raw, _, text = after_open.partition("</think>")
reasoning = reasoning_raw.strip("\n") or None
text = text.strip("\n")
else:
# Truncated reasoning (no closing tag) — discard any partial
# tool-call attempts since the model never finished thinking.
return ParsedResponse(
content="",
reasoning_content=after_open.strip() or None,
tool_calls=[],
)
elif "</think>" in text:
# Sampler stripped the prefilled <think> open tag — see
# _normalize_response_tokens. Keep prior behaviour: everything
# before </think> is reasoning, everything after is content.
before, _, after = text.partition("</think>")
reasoning = before.strip("\n") or None
text = after.strip("\n")
reasoning = boundary.text
if reasoning is not None:
text = text.partition("</think>")[2].strip("\n")
return ParsedResponse(
content=text.strip(),
@@ -590,9 +593,17 @@ class KimiK25Renderer:
The tokenizer should be ``moonshotai/Kimi-K2-Instruct`` (same as K2).
"""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# Completing a tool cycle strips its earlier reasoning, even with thinking=False.
return False
supports_process_multimodal = True
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: KimiK25RendererConfig | None = None,
*,
processor: Any = None,
@@ -630,11 +641,6 @@ class KimiK25Renderer:
self._media_pad = self._token_id("<|media_pad|>")
self._media_end = self._token_id("<|media_end|>")
# <think> / </think> may be multi-token in K2.5; we encode them as text.
# We cache the encoded IDs for use in _normalize_response_tokens.
self._think_open_ids: list[int] = self._encode("<think>")
self._think_close_ids: list[int] = self._encode("</think>")
# The stop token for generation
self._endoftext: int | None = self._try_token_id("<|endoftext|>")
@@ -655,8 +661,6 @@ class KimiK25Renderer:
def _get_processor(self):
if self._processor is not None:
return self._processor
from transformers import AutoProcessor
name = getattr(self._tokenizer, "name_or_path", None)
if not name:
raise RuntimeError(
@@ -666,10 +670,12 @@ class KimiK25Renderer:
"known name_or_path so the processor can be auto-loaded."
)
# Kimi's processor is custom Python in the model repo and requires
# trust_remote_code=True. Callers using ``create_renderer_pool`` go
# through ``load_tokenizer`` which already pins the revision; for
# auto-load here, we delegate to AutoProcessor with the same flag.
self._processor = AutoProcessor.from_pretrained(name, trust_remote_code=True)
# trust_remote_code=True, so auto-loading delegates to AutoProcessor
# with that flag.
transformers = _require_transformers("Auto-loading a Kimi K2.5 processor")
self._processor = transformers.AutoProcessor.from_pretrained(
name, trust_remote_code=True
)
return self._processor
def _process_image(self, part: dict[str, Any]):
@@ -733,6 +739,7 @@ class KimiK25Renderer:
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
process_multimodal: bool = True,
) -> RenderedTokens:
"""Render messages to tokens, matching the K2.5 chat template.
@@ -820,7 +827,10 @@ class KimiK25Renderer:
``<|media_content|>``, ``<|media_end|>``, the trailing
``\\n``) are template-injected scaffold.
"""
_, out, _num_patches, h = self._process_image(part)
if process_multimodal:
_, out, _num_patches, h = self._process_image(part)
else:
out = h = None
emit_special(
self._media_begin, msg_idx, is_sampled=is_sampled, is_content=False
)
@@ -839,6 +849,9 @@ class KimiK25Renderer:
self._media_end, msg_idx, is_sampled=is_sampled, is_content=False
)
emit_text("\n", msg_idx, is_sampled=is_sampled, is_content=False)
if not process_multimodal:
return
assert out is not None and h is not None
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=1)
@@ -955,7 +968,7 @@ class KimiK25Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, 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,
@@ -979,24 +992,22 @@ class KimiK25Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — section-JSON wire format quotes strings, schema not needed
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
stop_ids: set[int] = {self._im_end}
if self._endoftext is not None:
stop_ids.add(self._endoftext)
# Restore the synthetic <think> prefill if it was stripped by the
# sampler. ``parse`` then walks ``normalized``, so any token_span we
# emit is in the *normalized* frame. We track the prepend offset and
# shift spans back so they refer to the caller's ``token_ids``.
normalized = self._normalize_response_tokens(list(token_ids))
prepend_offset = len(normalized) - len(token_ids)
parsed = _parse_kimi_k2_response(
return _parse_kimi_k2_response(
self._tokenizer,
normalized,
token_ids,
stop_ids=stop_ids,
think_open_ids=self._think_open_ids,
think_close_ids=self._think_close_ids,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=stop_ids,
assistant_prefix="<|im_assistant|>assistant<|im_middle|>",
),
tool_calls_section_begin_id=self._tool_calls_section_begin,
tool_calls_section_end_id=self._tool_calls_section_end,
tool_call_begin_id=self._tool_call_begin,
@@ -1004,14 +1015,6 @@ class KimiK25Renderer:
tool_call_end_id=self._tool_call_end,
)
if prepend_offset:
for tc in parsed.tool_calls:
if tc.token_span is not None:
start, end = tc.token_span
tc.token_span = (start - prepend_offset, end - prepend_offset)
return parsed
def get_stop_token_ids(self) -> list[int]:
stop = [self._im_end]
if self._endoftext is not None:
@@ -1026,6 +1029,7 @@ class KimiK25Renderer:
*,
tools: list[ToolSpec] | None = None,
previous_multi_modal_data: MultiModalData | None = None,
process_multimodal: bool = True,
) -> "RenderedTokens | None":
if (
not previous_prompt_ids
@@ -1034,6 +1038,23 @@ class KimiK25Renderer:
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_calls_section_begin,
tool_start_closes_reasoning=True,
assistant_prefix="<|im_assistant|>assistant<|im_middle|>",
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [
*previous_completion_ids,
*list(self._tokenizer.encode("</think>", add_special_tokens=False)),
]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -1114,7 +1135,10 @@ class KimiK25Renderer:
is_sampled: bool = False,
is_content: bool = False,
) -> None:
_, out, _num_patches, h = self._process_image(part)
if process_multimodal:
_, out, _num_patches, h = self._process_image(part)
else:
out = h = None
emit_special(self._media_begin, msg_idx)
emit_text("image", msg_idx)
emit_special(self._media_content, msg_idx)
@@ -1124,6 +1148,9 @@ class KimiK25Renderer:
emit_special(self._media_pad, msg_idx, is_content=is_content)
emit_special(self._media_end, msg_idx)
emit_text("\n", msg_idx)
if not process_multimodal:
return
assert out is not None and h is not None
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=1)
@@ -1187,17 +1214,17 @@ class KimiK25Renderer:
# below never mutates the caller's previous_multi_modal_data.
merged_hashes: dict[str, list[str]] = (
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
merged_placeholders: dict[str, list[PlaceholderRange]] = (
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
merged_items: dict[str, list[dict[str, Any]]] = (
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
for modality, vals in new_hashes.items():
@@ -1214,7 +1241,7 @@ class KimiK25Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
)
@@ -1228,7 +1255,7 @@ class KimiK25Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
multi_modal_data=mm_data,
@@ -1476,41 +1503,3 @@ class KimiK25Renderer:
is_sampled=False,
is_content=True,
)
def _normalize_response_tokens(self, response: list[int]) -> list[int]:
"""Restore the synthetic ``<think>`` prefill if the sampler stripped it.
When thinking is enabled the generation prompt ends with a ``<think>``
prefill. Some samplers strip the prefill from the returned token IDs.
If the response contains ``</think>`` (encoded tokens) but does NOT
start with ``<think>`` (encoded tokens), we prepend the ``<think>``
tokens so the downstream text-based parser sees a complete block.
"""
if not response:
return response
open_ids = self._think_open_ids
close_ids = self._think_close_ids
if not open_ids or not close_ids:
return response
# Check whether <think> appears anywhere in the response. Checking
# anywhere (not just the start) avoids false positives when the
# caller's slicing happens to include earlier scaffolding tokens
# (e.g. the assistant role tag) before the open tag.
contains_open = any(
response[j : j + len(open_ids)] == open_ids
for j in range(len(response) - len(open_ids) + 1)
)
# Check whether </think> appears anywhere in the response
contains_close = any(
response[j : j + len(close_ids)] == close_ids
for j in range(len(response) - len(close_ids) + 1)
)
if not contains_open and contains_close:
return open_ids + response
return response
+32
View File
@@ -0,0 +1,32 @@
"""Laguna S-2.1 Renderer — a larger sibling of Laguna XS-2.1.
S-2.1 shares XS-2.1's tokenizer and token format, so this is a thin subclass of
:class:`renderers.laguna_xs2.LagunaXS21Renderer`; see that module for the shared
format. The template delta is two thinking kwargs: ``enable_thinking`` defaults
to ``True`` (XS-2.1 defaults ``False``), and ``preserve_thinking`` widens the
reasoning-display gate to ``enable_thinking or preserve_thinking``.
"""
from __future__ import annotations
from renderers.base import Tokenizer
from renderers.configs import LagunaS21RendererConfig
from renderers.laguna_xs2 import LagunaXS21Renderer
class LagunaS21Renderer(LagunaXS21Renderer):
"""Mirrors the ``poolside/Laguna-S-2.1`` chat template."""
# Narrows the inherited attribute so the S-2.1-only ``preserve_thinking``
# resolves; ``__init__`` always stores an S-2.1 config.
config: LagunaS21RendererConfig
def __init__(
self,
tokenizer: Tokenizer,
config: LagunaS21RendererConfig | None = None,
):
super().__init__(tokenizer, config or LagunaS21RendererConfig())
def _render_history_reasoning(self) -> bool:
return self.config.enable_thinking or self.config.preserve_thinking
+192 -31
View File
@@ -1,4 +1,4 @@
"""Laguna-XS.2 / XS-2.1 Renderer.
"""Poolside Laguna renderer family.
Main properties:
- Prefix is the single token ``〈|EOS|〉`` (also the EOS / stop token).
@@ -36,13 +36,21 @@ XS-2.1's template (upstream rev ``575f0f28``) is served by the
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.
Laguna M.1's official template (revision ``2bf8a4ab``) is served by
:class:`LagunaM1Renderer`. It shares XS.2's byte layout, tool syntax, and
generation prompt, but has no fallback system prompt and reads assistant
reasoning from ``reasoning`` before falling back to ``reasoning_content``.
S-2.1 subclasses :class:`LagunaXS21Renderer` from :mod:`renderers.laguna_s21`,
overriding only the ``_render_history_reasoning`` seam.
"""
from __future__ import annotations
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Content,
@@ -50,13 +58,21 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_infer_offsets_from_decode,
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.configs import (
LagunaM1RendererConfig,
LagunaS21RendererConfig,
LagunaXS2RendererConfig,
LagunaXS21RendererConfig,
)
from renderers.parsing import parse_laguna_xs2
_DEFAULT_SYSTEM_MESSAGE = (
@@ -104,10 +120,21 @@ _TOOLS_HEADER_XS21 = (
class LagunaXS2Renderer:
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
return True
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: LagunaXS2RendererConfig | LagunaXS21RendererConfig | None = None,
tokenizer: Tokenizer,
config: (
LagunaXS2RendererConfig
| LagunaM1RendererConfig
| LagunaXS21RendererConfig
| LagunaS21RendererConfig
| None
) = None,
):
self._tokenizer = tokenizer
self.config = config or LagunaXS2RendererConfig()
@@ -309,7 +336,7 @@ class LagunaXS2Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -332,6 +359,7 @@ class LagunaXS2Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_laguna_xs2(
self._tokenizer,
@@ -342,6 +370,12 @@ class LagunaXS2Renderer:
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
tools=tools,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
assistant_prefix="<assistant>",
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -361,6 +395,20 @@ class LagunaXS2Renderer:
or reject_assistant_in_extension(new_messages)
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_call,
assistant_prefix="<assistant>",
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -466,7 +514,9 @@ class LagunaXS2Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
@@ -481,12 +531,9 @@ class LagunaXS2Renderer:
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
):
# Raw passthrough is shared by XS.2 and M.1; XS-2.1's config does
# not expose this template gate.
if getattr(self.config, "render_assistant_messages_raw", False):
self._render_assistant_raw(
msg_idx,
content,
@@ -495,16 +542,7 @@ class LagunaXS2Renderer:
)
return
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
else:
# When the caller stores reasoning as a ``ThinkingPart`` inside
# a list-form ``content`` (e.g. after parse_response →
# reserialize), pull it out here so it survives the re-render.
part_thinking = self._thinking_text(msg.get("content"))
if part_thinking:
reasoning_content = part_thinking
reasoning_content, content = self._assistant_reasoning_and_content(msg, content)
# ``<assistant>\n`` is template-injected scaffolding — the chat
# template emits these as the generation prompt at inference and
@@ -567,6 +605,22 @@ class LagunaXS2Renderer:
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 _assistant_reasoning_and_content(
self, msg: Message, content: str
) -> tuple[str, str]:
"""Return the reasoning/body pair used by the XS.2 template."""
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
else:
# When the caller stores reasoning as a ``ThinkingPart`` inside
# a list-form ``content`` (e.g. after parse_response →
# reserialize), pull it out here so it survives the re-render.
part_thinking = self._thinking_text(msg.get("content"))
if part_thinking:
reasoning_content = part_thinking
return reasoning_content, content
def _render_assistant_raw(
self,
msg_idx: int,
@@ -620,6 +674,43 @@ class LagunaXS2Renderer:
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
class LagunaM1Renderer(LagunaXS2Renderer):
"""Renderer for the official ``poolside/Laguna-M.1`` checkpoint.
The token protocol is shared with XS.2, while the absent fallback
system prompt and assistant-reasoning precedence are M.1-specific.
"""
def __init__(
self,
tokenizer: Tokenizer,
config: LagunaM1RendererConfig | None = None,
):
super().__init__(tokenizer, config or LagunaM1RendererConfig())
self._default_system_message = ""
def _assistant_reasoning_and_content(
self, msg: Message, content: str
) -> tuple[str, str]:
# Match the official Jinja exactly: ``reasoning`` wins whenever it
# is a string (including the empty string), then
# ``reasoning_content`` is considered. An inline </think> block is
# removed from content and becomes the fallback reasoning source.
reasoning_content = ""
if isinstance(msg.get("reasoning"), str):
reasoning_content = msg["reasoning"]
elif isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
if "</think>" in content:
if not reasoning_content:
before_close = content.split("</think>", 1)[0].rstrip("\n")
reasoning_content = before_close.split("<think>")[-1].lstrip("\n")
content = content.rsplit("</think>", 1)[-1].lstrip("\n")
return reasoning_content, content
class LagunaXS21Renderer(LagunaXS2Renderer):
"""Laguna-XS-2.1 — mirrors the ``poolside/Laguna-XS-2.1`` chat
template (upstream rev ``575f0f28``); see the module docstring for
@@ -632,11 +723,18 @@ class LagunaXS21Renderer(LagunaXS2Renderer):
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: LagunaXS21RendererConfig | None = None,
tokenizer: Tokenizer,
config: LagunaXS21RendererConfig | LagunaS21RendererConfig | None = None,
):
super().__init__(tokenizer, config or LagunaXS21RendererConfig())
def _render_history_reasoning(self) -> bool:
"""Whether an assistant turn renders its ``<think>{reasoning}</think>``
block (vs opening with a bare ``</think>``). Mirrors the template's
reasoning-display gate; XS-2.1 gates this on ``enable_thinking`` alone.
"""
return self.config.enable_thinking
def render(
self,
messages: list[Message],
@@ -715,12 +813,52 @@ class LagunaXS21Renderer(LagunaXS2Renderer):
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(
attributed = attribute_text_segments(
self._tokenizer, header_segs, overlap_is_content=True
):
)
fallback_indices: list[int] | None = None
if not attributed.has_content_attribution:
full_header = "".join(text for text, _ in header_segs)
offsets = _infer_offsets_from_decode(
self._tokenizer,
[token_id for token_id, _ in attributed],
full_header,
)
if offsets is None:
fallback_index = 0 if caller_has_system and has_sys_content else -1
fallback_indices = [fallback_index] * len(attributed)
else:
content_spans: list[tuple[int, int]] = []
position = 0
for text, is_content in header_segs:
end = position + len(text)
if is_content:
content_spans.append((position, end))
position = end
fallback_indices = [
0
if (
any(
span_start < end and start < span_end
for span_start, span_end in content_spans
)
if end > start
else any(
span_start <= start < span_end
for span_start, span_end in content_spans
)
)
else -1
for start, end in offsets
]
for position, (tok_id, is_content) in enumerate(attributed):
if fallback_indices is not None:
message_index = fallback_indices[position]
else:
message_index = 0 if is_content else -1
emit_special(
tok_id,
0 if is_content else -1,
message_index,
is_sampled=False,
is_content=is_content,
)
@@ -774,7 +912,7 @@ class LagunaXS21Renderer(LagunaXS2Renderer):
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -784,6 +922,7 @@ class LagunaXS21Renderer(LagunaXS2Renderer):
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
# The XS-2.1 template renders reasoning and content verbatim (no
# newline wrapping), so the parse is verbatim too.
@@ -797,6 +936,12 @@ class LagunaXS21Renderer(LagunaXS2Renderer):
tool_call_end_id=self._tool_call_end,
tools=tools,
strip_newlines=False,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
assistant_prefix="<assistant>",
),
)
def bridge_to_next_turn(
@@ -813,6 +958,20 @@ class LagunaXS21Renderer(LagunaXS2Renderer):
or reject_assistant_in_extension(new_messages)
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_call,
assistant_prefix="<assistant>",
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -892,7 +1051,9 @@ class LagunaXS21Renderer(LagunaXS2Renderer):
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
@@ -920,7 +1081,7 @@ class LagunaXS21Renderer(LagunaXS2Renderer):
# scaffolding the model never samples.
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
if self.config.enable_thinking:
if self._render_history_reasoning():
# ``<think>{reasoning}</think>`` renders verbatim, even when
# the reasoning is empty; the opener is the gen-prompt
# prefill, the rest the model sampled.
+13 -5
View File
@@ -41,13 +41,13 @@ from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -91,9 +91,14 @@ _TOOLS_IN_USER_INTRO = (
class Llama3Renderer:
"""Deterministic message → token renderer for Llama-3.x Instruct models."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
return True
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Llama3RendererConfig | None = None,
):
# ``thinking_retention`` is accepted but a no-op: Llama-3 ships no
@@ -389,7 +394,7 @@ class Llama3Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -412,6 +417,7 @@ class Llama3Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_llama_3(
self._tokenizer,
@@ -521,7 +527,9 @@ class Llama3Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
+50 -8
View File
@@ -14,13 +14,16 @@ from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_get_offset_tokenizer,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -55,9 +58,15 @@ _TOOLS_INSTRUCTIONS = (
class MiniMaxM2Renderer:
"""Deterministic message → token renderer for MiniMax M2 / M2.5 models."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# Only assistants after the last user retain reasoning.
return False
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: MiniMaxM2RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -165,9 +174,14 @@ class MiniMaxM2Renderer:
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)
if offset_tok is None:
ids = self._encode(full_text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([False] * len(ids))
return
encoding = offset_tok(
full_text, add_special_tokens=False, return_offsets_mapping=True
)
@@ -275,7 +289,7 @@ class MiniMaxM2Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -298,6 +312,7 @@ class MiniMaxM2Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_minimax(
self._tokenizer,
@@ -308,6 +323,12 @@ class MiniMaxM2Renderer:
tool_call_id=self._tool_call_tok,
tool_call_end_id=self._tool_call_end_tok,
tools=tools,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
assistant_prefix="]~b]ai\n",
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -328,6 +349,20 @@ class MiniMaxM2Renderer:
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_call_tok,
tool_start_closes_reasoning=True,
assistant_prefix="]~b]ai\n",
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -401,9 +436,14 @@ class MiniMaxM2Renderer:
*,
is_sampled: bool,
) -> None:
from renderers.base import _get_offset_tokenizer
offset_tok = _get_offset_tokenizer(self._tokenizer)
if offset_tok is None:
ids = self._encode(full_text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([False] * len(ids))
return
encoding = offset_tok(
full_text, add_special_tokens=False, return_offsets_mapping=True
)
@@ -463,7 +503,9 @@ class MiniMaxM2Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
+308 -7
View File
@@ -14,16 +14,23 @@ Nemotron 3 uses the same <|im_start|>/<|im_end|> format as Qwen3.5 but differs i
from __future__ import annotations
from dataclasses import replace
import json
from pathlib import Path
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
MultiModalData,
ParsedResponse,
PlaceholderRange,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_require_transformers,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -31,8 +38,13 @@ from renderers.base import (
should_rerender_for_thinking_retention,
trim_to_turn_close,
)
from renderers.configs import Nemotron3RendererConfig, Nemotron3UltraRendererConfig
from renderers.configs import (
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
Nemotron35RendererConfig,
)
from renderers.parsing import parse_qwen35
from renderers.qwen3_vl import _image_hash, _is_image_part, _load_pil_image
# ---------------------------------------------------------------------------
# Tool system prompt constants
@@ -76,10 +88,12 @@ 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
# The Nemotron family ships three 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
# the ``Nemotron3UltraRenderer`` subclass (``name="nemotron-3-ultra"``);
# Nemotron 3.5 (Lightning) uses the Ultra glue but defines no effort kwarg and
# is the ``Nemotron35Renderer`` subclass (``name="nemotron-3.5"``). 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.
@@ -104,6 +118,12 @@ class Nemotron3Renderer:
their own discriminator and differ only by the class-level hooks here.
"""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# An effort hint moves to the newest user, independently of thinking retention.
return not self.config.truncate_history_thinking and not self._effort_hint
# Variant hooks (overridden by ``Nemotron3UltraRenderer``): the default
# config to build when none is passed, and whether to use Ultra's
# reasoning-block glue.
@@ -112,7 +132,7 @@ class Nemotron3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Nemotron3RendererConfig | Nemotron3UltraRendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -478,7 +498,7 @@ class Nemotron3Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in original_messages],
message_tool_names=extract_message_tool_names(original_messages),
)
@@ -501,6 +521,7 @@ class Nemotron3Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
stop_ids = {self._im_end}
if self._endoftext is not None:
@@ -514,6 +535,11 @@ class Nemotron3Renderer:
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
tools=tools,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -542,6 +568,20 @@ class Nemotron3Renderer:
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_call,
tool_start_closes_reasoning=True,
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
assert self._think_end is not None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -662,7 +702,9 @@ class Nemotron3Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
@@ -852,3 +894,262 @@ class Nemotron3UltraRenderer(Nemotron3Renderer):
_config_cls = Nemotron3UltraRendererConfig
_ultra = True
class Nemotron35Renderer(Nemotron3Renderer):
"""Renderer for Nemotron **3.5** (Lightning).
The 3.5 chat template is the Ultra variant's minus the effort kwarg: same
reasoning-block glue (carried by the ``_ultra`` class hook), but its Jinja
defines no reasoning-effort variable, so the config exposes none and the
effort hint is always empty.
"""
_config_cls = Nemotron35RendererConfig
_ultra = True
supports_process_multimodal = True
supports_multimodal_bridge = False
_processor_model_prefix = "nvidia/NVIDIA-Nemotron-3.5"
def __init__(
self,
tokenizer: Tokenizer,
config: Nemotron35RendererConfig | None = None,
*,
processor: Any = None,
):
super().__init__(tokenizer, config)
self._processor = processor
self._image = self._token_id("<image>", optional=True)
@property
def mm_token_type_id_map(self) -> dict[int, int]:
return {self._image: 1} if self._image is not None else {}
def _image_token_id(self) -> int:
if self._image is None:
raise RuntimeError("This Nemotron 3.5 tokenizer has no <image> token.")
return self._image
def _get_processor(self):
if self._processor is not None:
return self._processor
name = getattr(self._tokenizer, "name_or_path", None)
if not name:
raise RuntimeError(
"Nemotron35Renderer needs a processor for image content."
)
if Path(name).expanduser().is_dir():
raise RuntimeError(
"Local Nemotron remote-code processor paths require an explicitly "
"injected reviewed processor."
)
if not name.startswith(self._processor_model_prefix):
raise RuntimeError(
f"Nemotron processor {name!r} is not approved for remote-code "
"loading. Inject a reviewed processor."
)
transformers = _require_transformers("Auto-loading a Nemotron 3.5 processor")
self._processor = transformers.AutoProcessor.from_pretrained(
name, trust_remote_code=True
)
return self._processor
@staticmethod
def _is_image_part(item: Any) -> bool:
return _is_image_part(item) or (
isinstance(item, dict) and item.get("type") == "input_image"
)
@staticmethod
def _image_source(part: dict[str, Any]) -> dict[str, Any]:
if "input_image" not in part:
return part
return {**part, "image": part["input_image"]}
@classmethod
def _logical_multimodal_content(
cls, content: list[Any]
) -> tuple[str, list[dict[str, Any]]]:
text = "".join(
item if isinstance(item, str) else str(item.get("text") or "")
for item in content
if isinstance(item, str)
or (isinstance(item, dict) and item.get("type") in ("text", "input_text"))
)
image_parts = [
item
for item in content
if isinstance(item, dict) and cls._is_image_part(item)
]
emit_structured_images = "<image>" not in text
rendered: list[str] = []
image_index = 0
for item in content:
if isinstance(item, str):
rendered.append(item)
elif not isinstance(item, dict):
raise ValueError(f"Unexpected content item: {item}")
elif cls._is_image_part(item):
image_index += 1
if emit_structured_images:
if len(image_parts) > 1:
rendered.append(f"<image {image_index}><image>")
else:
rendered.append("<image>")
elif item.get("type") in ("video", "video_url", "input_video"):
raise NotImplementedError(
"Video parts are not yet supported by Nemotron35Renderer."
)
elif item.get("type") in ("text", "input_text") or "text" in item:
rendered.append(str(item.get("text") or ""))
return "".join(rendered), image_parts
@staticmethod
def _load_image(part: dict[str, Any]):
source = Nemotron35Renderer._image_source(part)
if "image" in source:
raw = source["image"]
elif "image_url" in source:
image_url = source.get("image_url")
raw = image_url.get("url") if isinstance(image_url, dict) else image_url
else:
raw = source.get("url") or source.get("path")
if isinstance(raw, str) and not raw.startswith("data:image/"):
raise ValueError(
"Nemotron 3.5 accepts in-memory images or data:image URIs; "
"network and filesystem image sources are disabled."
)
return _load_pil_image(source)
def _process_image(self, part: dict[str, Any]) -> tuple[dict[str, Any], int, str]:
self._image_token_id()
image = self._load_image(part)
output = self._get_processor().image_processor(
images=[image], return_tensors="np"
)
return output, int(output["num_tokens"][0]), _image_hash(image)
@staticmethod
def _expand_image_tokens(content: str, token_counts: list[int]) -> str:
if content.count("<image>") != len(token_counts):
raise ValueError(
"Nemotron image content must contain one <image> placeholder per image."
)
segments = content.split("<image>")
expanded = [segments[0]]
for count, suffix in zip(token_counts, segments[1:]):
expanded.append("<img>" + "<image>" * count + "</img>" + suffix)
return "".join(expanded)
def _transform_multimodal_messages(
self,
messages: list[Message],
*,
process_multimodal: bool,
) -> tuple[list[Message], list[tuple[dict[str, Any], int, str]]]:
transformed: list[Message] = []
processed_images: list[tuple[dict[str, Any], int, str]] = []
for message in messages:
copied = dict(message)
content = message.get("content")
if isinstance(content, list) and any(
self._is_image_part(item) for item in content
):
logical_content, image_parts = self._logical_multimodal_content(content)
if process_multimodal:
current_images = [self._process_image(part) for part in image_parts]
logical_content = self._expand_image_tokens(
logical_content, [item[1] for item in current_images]
)
processed_images.extend(current_images)
copied["content"] = logical_content
transformed.append(copied)
return transformed, processed_images
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
process_multimodal: bool = True,
) -> RenderedTokens:
transformed, processed_images = self._transform_multimodal_messages(
messages, process_multimodal=process_multimodal
)
rendered = super().render(
transformed,
tools=tools,
add_generation_prompt=add_generation_prompt,
)
if not processed_images:
return rendered
image_token_id = self._image_token_id()
placeholder_runs: list[PlaceholderRange] = []
cursor = 0
for _, length, _ in processed_images:
while (
cursor < len(rendered.token_ids)
and rendered.token_ids[cursor] != image_token_id
):
cursor += 1
if (
rendered.token_ids[cursor : cursor + length]
!= [image_token_id] * length
):
raise ValueError(
"Rendered Nemotron image placeholders are not contiguous."
)
placeholder_runs.append(PlaceholderRange(offset=cursor, length=length))
cursor += length
mm_data = MultiModalData(
mm_hashes={"image": [item[2] for item in processed_images]},
mm_placeholders={"image": placeholder_runs},
mm_items={
"image": [
{
key: processor_output[key]
for key in (
"pixel_values",
"imgs_sizes",
"num_tokens",
"num_patches",
)
}
for processor_output, _, _ in processed_images
],
},
)
return replace(rendered, multi_modal_data=mm_data)
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,
previous_multi_modal_data: MultiModalData | None = None,
process_multimodal: bool = True,
) -> RenderedTokens | None:
has_new_images = any(
isinstance(message.get("content"), list)
and any(self._is_image_part(item) for item in message["content"])
for message in new_messages
)
if has_new_images or (
previous_multi_modal_data is not None
and not previous_multi_modal_data.is_empty()
):
return None
return super().bridge_to_next_turn(
previous_prompt_ids,
previous_completion_ids,
new_messages,
tools=tools,
)
+4 -8
View File
@@ -20,7 +20,6 @@ import re
from typing import Protocol, runtime_checkable
from renderers.base import ParsedToolCall, ToolCallParseStatus
from renderers.hermes import HermesToolParser
# ── Shared helpers ───────────────────────────────────────────────────
@@ -441,13 +440,11 @@ class ThinkTextReasoningParser:
self._tokenizer = tokenizer # unused, for Protocol compat
def extract(self, text: str) -> tuple[str | None, str]:
if "</think>" not in text:
if not text.startswith("<think>"):
return None, text
before, _, after = text.partition("</think>")
if "<think>" in before:
reasoning = before.split("<think>", 1)[-1]
else:
reasoning = before
reasoning, close, after = text[len("<think>") :].partition("</think>")
if not close:
return reasoning, ""
# Preserve whitespace on both sides of the `</think>` boundary —
# chat templates round-trip it verbatim (GLM-4.5 emits reasoning and
# content back-to-back with no separator), so stripping here causes
@@ -459,7 +456,6 @@ class ThinkTextReasoningParser:
TOOL_PARSERS: dict[str, type] = {
"hermes": HermesToolParser,
"qwen3": Qwen3ToolParser,
"qwen3.5": Qwen35ToolParser,
"glm": GlmToolParser,
+658 -228
View File
File diff suppressed because it is too large Load Diff
+43 -7
View File
@@ -6,13 +6,16 @@ import json
from collections.abc import Mapping, Sequence
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_get_offset_tokenizer,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -120,7 +123,7 @@ def _tool_definition(tool: ToolSpec) -> str:
class _TokenBuilder:
def __init__(self, tokenizer: PreTrainedTokenizer):
def __init__(self, tokenizer: Tokenizer):
self.tokenizer = tokenizer
self.token_ids: list[int] = []
self.message_indices: list[int] = []
@@ -190,9 +193,14 @@ class _TokenBuilder:
class PrimeQwen3Renderer:
"""Renderer for PrimeIntellect/Qwen3-0.6B and Qwen3-1.7B."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
return True
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: PrimeQwen3RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -316,8 +324,12 @@ class PrimeQwen3Renderer:
return RenderedTokens(
token_ids=builder.token_ids,
message_indices=builder.message_indices,
sampled_mask=builder.sampled_mask,
is_content=builder.is_content,
sampled_mask=(
builder.sampled_mask
if _get_offset_tokenizer(self._tokenizer) is not None
else []
),
is_content=_content_mask_or_empty(self._tokenizer, builder.is_content),
message_roles=[message.get("role") or "" for message in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -611,6 +623,7 @@ class PrimeQwen3Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_qwen35(
self._tokenizer,
@@ -621,6 +634,11 @@ class PrimeQwen3Renderer:
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
tools=tools,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -640,6 +658,20 @@ class PrimeQwen3Renderer:
or reject_assistant_in_extension(new_messages)
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_call,
tool_start_closes_reasoning=True,
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -684,8 +716,12 @@ class PrimeQwen3Renderer:
return RenderedTokens(
token_ids=builder.token_ids,
message_indices=builder.message_indices,
sampled_mask=builder.sampled_mask,
is_content=builder.is_content,
sampled_mask=(
builder.sampled_mask
if _get_offset_tokenizer(self._tokenizer) is not None
else []
),
is_content=_content_mask_or_empty(self._tokenizer, builder.is_content),
message_roles=[message.get("role") or "" for message in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
+71 -12
View File
@@ -5,19 +5,30 @@ Key differences from Qwen3.5:
- Tool calls use JSON format: {"name": "...", "arguments": ...}
- Thinking blocks only inserted when loop.last OR reasoning_content present
- Generation prompt does NOT add <think> by default
One documented deviation from the Jinja template: with
``enable_thinking=False`` the empty ``<think>\n\n</think>\n\n`` wrapper is
re-emitted on historical assistant turns without ``reasoning_content`` (the
template strips it from turns at or before the last user query). The
generation prompt prefills that wrapper, so every turn sampled with thinking
disabled contains it — stripping it on re-render would make the same
conversation produce different tokens depending on when it is rendered.
See ``tests/test_disabled_thinking_stability.py``.
"""
from __future__ import annotations
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -48,9 +59,15 @@ _TOOLS_FOOTER = (
class Qwen3Renderer:
"""Deterministic message → token renderer for Qwen3 models."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# Even with thinking disabled, supplied reasoning is stripped from history.
return False
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Qwen3RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -82,9 +99,16 @@ class Qwen3Renderer:
return self._tokenizer.encode(text, add_special_tokens=False)
@staticmethod
def _query_boundary_text(content) -> str:
def _content_text(content) -> str:
"""Return the text parts of a message in a renderer-safe form.
Qwen3's native template is text-only, but text-only messages can also
use OpenAI-style content lists: ``[{"type": "text", "text": ...}]``.
Treat both representations identically instead of silently dropping
the message body.
"""
if isinstance(content, str):
return content.strip()
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
@@ -92,9 +116,13 @@ class Qwen3Renderer:
parts.append(item)
elif isinstance(item, dict) and isinstance(item.get("text"), str):
parts.append(item["text"])
return "".join(parts).strip()
return "".join(parts)
return ""
@staticmethod
def _query_boundary_text(content) -> str:
return Qwen3Renderer._content_text(content).strip()
@staticmethod
def _is_user_query_message(msg: Message) -> bool:
if msg.get("role") != "user":
@@ -175,7 +203,7 @@ class Qwen3Renderer:
# JSON as message body.
segments: list[tuple[str, bool]] = [("system\n", False)]
if first_is_system:
sys_content = messages[0].get("content") or ""
sys_content = self._content_text(messages[0].get("content"))
if sys_content:
segments.append((sys_content, True))
segments.append(("\n\n", False))
@@ -188,7 +216,7 @@ class Qwen3Renderer:
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
elif first_is_system:
emit_special(self._im_start, 0, is_sampled=False, is_content=False)
sys_content = messages[0].get("content") or ""
sys_content = self._content_text(messages[0].get("content"))
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if sys_content:
sys_segments.append((sys_content, True))
@@ -203,7 +231,7 @@ class Qwen3Renderer:
num_messages = len(messages)
for i, msg in enumerate(messages):
role = msg["role"]
content = msg.get("content") if isinstance(msg.get("content"), str) else ""
content = self._content_text(msg.get("content"))
if role == "system":
if i == 0:
@@ -260,7 +288,7 @@ class Qwen3Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
@@ -283,6 +311,7 @@ class Qwen3Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — hermes wire format quotes strings, schema not needed
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_qwen3(
self._tokenizer,
@@ -291,6 +320,11 @@ class Qwen3Renderer:
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
reasoning_end_id=self._think_end,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -311,6 +345,19 @@ class Qwen3Renderer:
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_call,
tool_start_closes_reasoning=True,
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -386,7 +433,7 @@ class Qwen3Renderer:
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = msg.get("content") if isinstance(msg.get("content"), str) else ""
content = self._content_text(msg.get("content"))
if role == "user":
emit_special(self._im_start, i)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
@@ -425,7 +472,9 @@ class Qwen3Renderer:
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,
is_content=_content_mask_or_empty(
self._tokenizer, [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),
)
@@ -477,7 +526,17 @@ class Qwen3Renderer:
emit_in_template_window = msg_idx > last_query_index and (
is_last or reasoning_content
)
if emit_in_template_window:
# With thinking disabled, the generation prompt prefilled the empty
# ``<think>\n\n</think>\n\n`` wrapper, so it is part of every sampled
# turn's token stream. Re-emit it on historical turns — deviating
# from the Jinja template, which strips it from turns at or before
# the last user query — so re-renders stay token-stable with what
# the model actually sampled. Turns that carry reasoning_content
# were not sampled under this config; those stay template-faithful.
emit_thinking = emit_in_template_window or (
not self.config.enable_thinking and not reasoning_content
)
if emit_thinking:
body = (
"<think>\n"
+ reasoning_content.strip("\n")
+180 -69
View File
@@ -3,6 +3,14 @@
Produces token-for-token identical output to tokenizer.apply_chat_template() while
also tracking which message produced each token (for per-token loss masks).
One documented deviation: with ``enable_thinking=False`` the empty
``<think>\n\n</think>\n\n`` wrapper is re-emitted on historical assistant
turns without ``reasoning_content`` (the Jinja template strips it from turns
at or before the last user query). The generation prompt prefills that
wrapper, so every turn sampled with thinking disabled contains it — stripping
it on re-render would make the same conversation produce different tokens
depending on when it is rendered. See ``tests/test_disabled_thinking_stability.py``.
Multimodal: the Qwen3.5 family is itself a VLM (HF tag ``image-text-to-text``;
processor class ``Qwen3VLProcessor``). When a user/tool message carries an
``ImagePart``, the renderer emits the same ``<|vision_start|>``+N×``<|image_pad|>``
@@ -15,9 +23,10 @@ path and remain byte-identical to ``apply_chat_template``.
from __future__ import annotations
import json
from collections.abc import Iterable
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
@@ -26,6 +35,9 @@ from renderers.base import (
PlaceholderRange,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_require_transformers,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -94,6 +106,9 @@ _ENABLE_THINKING_DEFAULTS: dict[str, bool] = {
"Qwen/Qwen3.5-397B-A17B": True,
# Qwen3.6 extends the Qwen3.5 template; same big-size polarity.
"Qwen/Qwen3.6-35B-A3B": True,
# Qwen3.8 keeps thinking enabled by default.
"Qwen/Qwen3.8-27B": True,
"Qwen/Qwen3.8-Flash-Next": True,
}
@@ -111,11 +126,18 @@ def _default_enable_thinking(tokenizer) -> bool:
class Qwen35Renderer:
"""Deterministic message → token renderer for Qwen3.5 models."""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
# Qwen3.6/3.8 can retain every thinking block through their template knob.
return bool(getattr(self.config, "preserve_thinking", False))
supports_process_multimodal = True
_config_cls: type = Qwen35RendererConfig
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Qwen35RendererConfig | None = None,
*,
processor: Any = None,
@@ -174,8 +196,6 @@ class Qwen35Renderer:
def _get_processor(self):
if self._processor is not None:
return self._processor
from transformers import AutoProcessor
name = getattr(self._tokenizer, "name_or_path", None)
if not name:
raise RuntimeError(
@@ -184,7 +204,8 @@ class Qwen35Renderer:
"constructor, or load the tokenizer with a known name_or_path "
"so the processor can be auto-loaded."
)
self._processor = AutoProcessor.from_pretrained(name)
transformers = _require_transformers("Auto-loading a Qwen3.5-family processor")
self._processor = transformers.AutoProcessor.from_pretrained(name)
return self._processor
def _process_image(self, part: dict[str, Any]):
@@ -238,7 +259,11 @@ class Qwen35Renderer:
# ------------------------------------------------------------------
@staticmethod
def _render_content(content: Any) -> str:
def _iter_content_parts(content: list[Any]) -> Iterable[Any]:
return content
@classmethod
def _render_content(cls, content: Any) -> str:
"""Render message content to a text string (before tokenization).
Handles string, list of text parts, and None. Image / video parts
@@ -254,7 +279,7 @@ class Qwen35Renderer:
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
for item in cls._iter_content_parts(content):
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
@@ -297,6 +322,41 @@ class Qwen35Renderer:
return i
return len(messages)
def _reasoning_instructions(self) -> str:
"""Optional synthetic system instruction for reasoning control.
Qwen3.5 and Qwen3.6 do not inject one. Newer family members can
override this hook without duplicating the full render path.
"""
return ""
def _omit_empty_system_message(self) -> bool:
"""Whether an empty caller-provided system message emits no tokens."""
return False
@staticmethod
def _extract_assistant_parts(msg: Message, content: str) -> tuple[str, str]:
"""Return ``(reasoning_content, visible_content)`` for an assistant.
Qwen3.5 and Qwen3.6 accept the legacy inline
``<think>...</think>content`` shape when ``reasoning_content`` is
absent. Qwen3.8 removes that compatibility branch and overrides this
hook to keep inline markers in visible 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")
return reasoning_content.strip(), content
# ------------------------------------------------------------------
# Core render method
# ------------------------------------------------------------------
@@ -307,6 +367,7 @@ class Qwen35Renderer:
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
process_multimodal: bool = True,
) -> RenderedTokens:
if not messages:
raise ValueError("No messages provided.")
@@ -378,7 +439,11 @@ class Qwen35Renderer:
# 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)
if process_multimodal:
_, out, n, h = self._process_image(part)
else:
out = h = None
n = 1
vision_counts["image"] += 1
if self.config.add_vision_id:
emit_text(
@@ -396,16 +461,18 @@ class Qwen35Renderer:
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)
)
mm_items.setdefault("image", []).append(
{
"pixel_values": out["pixel_values"],
"image_grid_thw": out["image_grid_thw"],
}
)
if process_multimodal:
assert out is not None and h is not None
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
)
mm_items.setdefault("image", []).append(
{
"pixel_values": out["pixel_values"],
"image_grid_thw": out["image_grid_thw"],
}
)
def emit_user_with_media(content_list: list[Any], msg_idx: int) -> None:
"""Emit a user message whose content list contains image parts.
@@ -433,7 +500,7 @@ class Qwen35Renderer:
emit_text_segments(buf_segments, msg_idx, is_sampled=False)
buf_segments.clear()
for item in content_list:
for item in self._iter_content_parts(content_list):
if isinstance(item, str):
if item:
buf_segments.append((item, True))
@@ -458,6 +525,7 @@ class Qwen35Renderer:
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
reasoning_instructions = self._reasoning_instructions()
if tools:
# System message index for attribution
@@ -469,10 +537,10 @@ class Qwen35Renderer:
# 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),
]
segments: list[tuple[str, bool]] = [("system\n", False)]
if reasoning_instructions:
segments.append((reasoning_instructions + "\n\n", False))
segments.append((_TOOLS_HEADER, False))
for tool in tools:
segments.append(("\n" + json.dumps(tool, ensure_ascii=False), False))
segments.append((_TOOLS_FOOTER, False))
@@ -487,13 +555,33 @@ class Qwen35Renderer:
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, 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)
if (
sys_content
or reasoning_instructions
or not self._omit_empty_system_message()
):
emit_special(self._im_start, 0, is_sampled=False, is_content=False)
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if reasoning_instructions:
separator = "\n\n" if sys_content else ""
sys_segments.append((reasoning_instructions + separator, 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)
elif reasoning_instructions:
# Qwen3.8 injects reasoning guidance even when the caller did
# not provide a system message. It is renderer scaffold, so use
# the synthetic ``-1`` attribution bucket.
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
emit_text_segments(
[("system\n", False), (reasoning_instructions, False)],
-1,
is_sampled=False,
)
emit_special(self._im_end, -1, is_sampled=False, is_content=False)
emit_text("\n", -1, is_sampled=False, is_content=False)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
@@ -571,7 +659,7 @@ class Qwen35Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, 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,
@@ -595,6 +683,7 @@ class Qwen35Renderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_qwen35(
self._tokenizer,
@@ -605,6 +694,11 @@ class Qwen35Renderer:
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
tools=tools,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -618,6 +712,7 @@ class Qwen35Renderer:
*,
tools: list[ToolSpec] | None = None,
previous_multi_modal_data: MultiModalData | None = None,
process_multimodal: bool = True,
) -> "RenderedTokens | None":
if (
not previous_prompt_ids
@@ -626,6 +721,19 @@ class Qwen35Renderer:
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_call,
tool_start_closes_reasoning=True,
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -654,6 +762,7 @@ class Qwen35Renderer:
# scratch correctly.
if (
self.config.add_vision_id
and process_multimodal
and previous_multi_modal_data is None
and self._vision_start in previous_ids
):
@@ -684,9 +793,11 @@ class Qwen35Renderer:
# ``add_vision_id`` parity across turns.
prev_image_count = 0
prev_video_count = 0
if previous_multi_modal_data is not None:
if process_multimodal and 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", []))
elif not process_multimodal:
prev_image_count = previous_ids.count(self._image_pad)
vision_counts = {"image": prev_image_count, "video": prev_video_count}
def emit_special(
@@ -729,7 +840,11 @@ class Qwen35Renderer:
content_mask.append(is_content)
def emit_image(part: dict[str, Any], msg_idx: int = -1) -> None:
_, out, n, h = self._process_image(part)
if process_multimodal:
_, out, n, h = self._process_image(part)
else:
out = h = None
n = 1
vision_counts["image"] += 1
if self.config.add_vision_id:
emit_text(f"Picture {vision_counts['image']}: ", msg_idx)
@@ -738,16 +853,18 @@ class Qwen35Renderer:
for _ in range(n):
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)
)
new_items.setdefault("image", []).append(
{
"pixel_values": out["pixel_values"],
"image_grid_thw": out["image_grid_thw"],
}
)
if process_multimodal:
assert out is not None and h is not None
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
)
new_items.setdefault("image", []).append(
{
"pixel_values": out["pixel_values"],
"image_grid_thw": out["image_grid_thw"],
}
)
def emit_user_with_media(content_list: list[Any], msg_idx: int) -> None:
emit_special(self._im_start, msg_idx)
@@ -758,7 +875,7 @@ class Qwen35Renderer:
emit_text_segments(buf_segments, msg_idx)
buf_segments.clear()
for item in content_list:
for item in self._iter_content_parts(content_list):
if isinstance(item, str):
if item:
buf_segments.append((item, True))
@@ -838,17 +955,17 @@ class Qwen35Renderer:
# below never mutates the caller's previous_multi_modal_data.
merged_hashes: dict[str, list[str]] = (
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
merged_placeholders: dict[str, list[PlaceholderRange]] = (
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
merged_items: dict[str, list[dict[str, Any]]] = (
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
for modality, vals in new_hashes.items():
@@ -865,7 +982,7 @@ class Qwen35Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
)
@@ -879,7 +996,7 @@ class Qwen35Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
multi_modal_data=mm_data,
@@ -924,22 +1041,7 @@ class Qwen35Renderer:
emit_ids,
emit_text_segments,
) -> None:
# Extract reasoning_content
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
# Split on </think> to separate reasoning from content
before_think_end, after_think_end = content.split("</think>", 1)
# Extract text after <think> (if present)
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()
reasoning_content, content = self._extract_assistant_parts(msg, content)
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
# at inference the chat template emits these as the generation
@@ -959,9 +1061,18 @@ class Qwen35Renderer:
# 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)
# With thinking disabled, the generation prompt prefilled the empty
# ``<think>\n\n</think>\n\n`` wrapper, so it is part of every sampled
# turn's token stream. Re-emit it on historical turns — deviating
# from the Jinja template, which strips it from turns at or before
# the last user query — so re-renders stay token-stable with what
# the model actually sampled. Turns that carry reasoning_content
# were not sampled under this config; those stay template-faithful.
emit_thinking = (
self._should_render_thinking(msg_idx, last_query_index)
or getattr(self.config, "preserve_thinking", False)
or (not self.config.enable_thinking and not reasoning_content)
)
if emit_thinking:
# Include thinking block
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
@@ -1092,7 +1203,7 @@ class Qwen35Renderer:
emit_text_segments(buf_segments, msg_idx, is_sampled=False)
buf_segments.clear()
for item in raw_content:
for item in self._iter_content_parts(raw_content):
if isinstance(item, str):
if item:
buf_segments.append((item, True))
+92
View File
@@ -0,0 +1,92 @@
"""Qwen3.8 Renderer — mirrors the Qwen3.8 Jinja chat template.
Qwen3.8 retains Qwen3.6's multimodal message grammar and JSON-safe tool
argument serialization, with three template changes:
- ``reasoning_effort`` can be ``xhigh`` (default), ``medium``, or ``low``;
xhigh/low inject a matching instruction into the system prompt.
- ``preserve_thinking`` defaults to true, so historical reasoning blocks are
retained unless explicitly disabled.
- Legacy inline ``<think>...</think>`` text is no longer split out of
assistant ``content``; only ``reasoning_content`` populates the reasoning
block.
"""
from __future__ import annotations
from collections.abc import Iterable
from typing import Any
from renderers.base import Message
from renderers.configs import Qwen38RendererConfig
from renderers.qwen36 import Qwen36Renderer
from renderers.qwen3_vl import _is_image_part, _is_video_part
_REASONING_INSTRUCTIONS = {
"xhigh": (
"Reasoning effort is set to xhigh. Please think carefully through the "
"task, validate key assumptions, consider plausible alternatives, and "
"prioritize correctness, consistency, and clarity in the final answer."
),
"medium": "",
"low": (
"Reasoning effort is set to low. Keep your thinking brief and focused, "
"moving directly to the conclusion without unnecessary elaboration."
),
}
class Qwen38Renderer(Qwen36Renderer):
"""Deterministic message-to-token renderer for Qwen3.8 models."""
config: Qwen38RendererConfig
_config_cls = Qwen38RendererConfig
def _reasoning_instructions(self) -> str:
if not self.config.enable_thinking:
return ""
return _REASONING_INSTRUCTIONS[self.config.reasoning_effort]
def _omit_empty_system_message(self) -> bool:
return True
@staticmethod
def _iter_content_parts(content: list[Any]) -> Iterable[Any]:
"""Keep media and string-valued text in every rendering path."""
for item in content:
if isinstance(item, str):
yield item
elif isinstance(item, dict) and (
_is_image_part(item)
or _is_video_part(item)
or isinstance(item.get("text"), str)
):
yield item
@staticmethod
def _is_user_query_message(msg: Message) -> bool:
if msg.get("role") != "user":
return False
content = Qwen38Renderer._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:
for i in range(len(messages) - 1, -1, -1):
if Qwen38Renderer._is_user_query_message(messages[i]):
return i
raise ValueError("No user query found in messages.")
@staticmethod
def _extract_assistant_parts(msg: Message, content: str) -> tuple[str, str]:
reasoning_content = msg.get("reasoning_content")
if not isinstance(reasoning_content, str):
reasoning_content = ""
return reasoning_content.strip(), content
__all__ = ["Qwen38Renderer"]
+81 -35
View File
@@ -33,7 +33,7 @@ import json
from typing import Any
from urllib.parse import urlparse
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.reasoning import scan_reasoning, prompt_ends_in_reasoning
from renderers.base import (
Message,
@@ -42,6 +42,9 @@ from renderers.base import (
PlaceholderRange,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_require_transformers,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -277,8 +280,8 @@ class _Emitter:
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.
# each segment via offset_mapping when available. A basic tokenizer
# still preserves the joined token IDs but leaves attribution empty.
assert self._tokenizer is not None, (
"_Emitter mixed-is_content flush requires a tokenizer; "
"pass one to the constructor."
@@ -309,9 +312,16 @@ class Qwen3VLRenderer:
``thinking_retention`` still controls whether the bridge is attempted.
"""
@property
def is_prefix_stable(self) -> bool:
"""Whether full renders preserve completed conversation prefixes."""
return True
supports_process_multimodal = True
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Qwen3VLRendererConfig | None = None,
*,
processor: Any = None,
@@ -375,8 +385,6 @@ class Qwen3VLRenderer:
def _get_processor(self):
if self._processor is not None:
return self._processor
from transformers import AutoProcessor
name = getattr(self._tokenizer, "name_or_path", None)
if not name:
raise RuntimeError(
@@ -385,7 +393,8 @@ class Qwen3VLRenderer:
"constructor, or load the tokenizer with a known name_or_path "
"so the processor can be auto-loaded."
)
self._processor = AutoProcessor.from_pretrained(name)
transformers = _require_transformers("Auto-loading a Qwen3-VL processor")
self._processor = transformers.AutoProcessor.from_pretrained(name)
return self._processor
@staticmethod
@@ -457,6 +466,7 @@ class Qwen3VLRenderer:
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
process_multimodal: bool = True,
) -> RenderedTokens:
if not messages:
raise ValueError("No messages provided.")
@@ -480,7 +490,11 @@ class Qwen3VLRenderer:
# 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)
if process_multimodal:
_, out, n, h = self._process_image(part)
else:
out = h = None
n = 1
vision_counts["image"] += 1
if self.config.add_vision_id:
em.text(
@@ -493,16 +507,18 @@ class Qwen3VLRenderer:
for _ in range(n):
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)
)
mm_items.setdefault("image", []).append(
{
"pixel_values": out["pixel_values"],
"image_grid_thw": out["image_grid_thw"],
}
)
if process_multimodal:
assert out is not None and h is not None
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
)
mm_items.setdefault("image", []).append(
{
"pixel_values": out["pixel_values"],
"image_grid_thw": out["image_grid_thw"],
}
)
def render_media_content(content: Any) -> None:
"""Emit a user/tool content list with media handled inline.
@@ -620,7 +636,7 @@ class Qwen3VLRenderer:
token_ids=em.token_ids,
message_indices=em.message_indices,
sampled_mask=em.sampled,
is_content=em.is_content,
is_content=_content_mask_or_empty(self._tokenizer, 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,
@@ -644,6 +660,7 @@ class Qwen3VLRenderer:
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — hermes wire format quotes strings, schema not needed
prompt_ids: list[int] | None = None,
) -> ParsedResponse:
return parse_qwen3(
self._tokenizer,
@@ -652,6 +669,11 @@ class Qwen3VLRenderer:
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
reasoning_end_id=self._think_end,
prefilled_thinking=prompt_ends_in_reasoning(
self._tokenizer,
prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
),
)
def get_stop_token_ids(self) -> list[int]:
@@ -665,6 +687,7 @@ class Qwen3VLRenderer:
*,
tools: list[ToolSpec] | None = None,
previous_multi_modal_data: MultiModalData | None = None,
process_multimodal: bool = True,
) -> "RenderedTokens | None":
"""Extend the prior turn with ``new_messages``.
@@ -681,6 +704,20 @@ class Qwen3VLRenderer:
or reject_assistant_in_extension(new_messages)
):
return None
boundary = scan_reasoning(
self._tokenizer,
previous_completion_ids,
prompt_ids=previous_prompt_ids,
stop_ids=set(self.get_stop_token_ids()),
tool_start_id=self._tool_call,
tool_start_closes_reasoning=True,
)
if boundary.is_open:
if any(t in self.get_stop_token_ids() for t in previous_completion_ids):
return None
previous_completion_ids = [*previous_completion_ids, self._think_end]
if should_rerender_for_thinking_retention(
self.effective_thinking_retention,
new_messages,
@@ -709,6 +746,7 @@ class Qwen3VLRenderer:
# correctly.
if (
self.config.add_vision_id
and process_multimodal
and previous_multi_modal_data is None
and self._vision_start in previous_ids
):
@@ -746,13 +784,19 @@ class Qwen3VLRenderer:
# ``add_vision_id`` parity across turns.
prev_image_count = 0
prev_video_count = 0
if previous_multi_modal_data is not None:
if process_multimodal and 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", []))
elif not process_multimodal:
prev_image_count = previous_ids.count(self._image_pad)
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)
if process_multimodal:
_, out, n, h = self._process_image(part)
else:
out = h = None
n = 1
vision_counts["image"] += 1
if self.config.add_vision_id:
em.text(
@@ -765,16 +809,18 @@ class Qwen3VLRenderer:
for _ in range(n):
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)
)
new_items.setdefault("image", []).append(
{
"pixel_values": out["pixel_values"],
"image_grid_thw": out["image_grid_thw"],
}
)
if process_multimodal:
assert out is not None and h is not None
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
)
new_items.setdefault("image", []).append(
{
"pixel_values": out["pixel_values"],
"image_grid_thw": out["image_grid_thw"],
}
)
def render_media_content(content: Any) -> None:
if isinstance(content, str):
@@ -833,17 +879,17 @@ class Qwen3VLRenderer:
# caller's previous_multi_modal_data.
merged_hashes = (
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
merged_placeholders = (
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
merged_items = (
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
if previous_multi_modal_data
if process_multimodal and previous_multi_modal_data
else {}
)
for modality, vals in new_hashes.items():
@@ -865,7 +911,7 @@ class Qwen3VLRenderer:
token_ids=em.token_ids,
message_indices=em.message_indices,
sampled_mask=em.sampled,
is_content=em.is_content,
is_content=_content_mask_or_empty(self._tokenizer, 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,
+244
View File
@@ -0,0 +1,244 @@
"""Reasoning boundaries, independent of response parsing and renderer classes."""
from dataclasses import dataclass
@dataclass(frozen=True)
class ReasoningBoundary:
"""Reasoning state and text; None means no reasoning region was opened.
``closed_by_tool`` marks a region ended by a tool-call opener rather than
the format's close marker; the tool call then starts the content.
"""
is_open: bool
text: str | None
closed_by_tool: bool = False
def _decode(tokenizer, ids: list[int]) -> str:
return tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
def _single_marker_id(tokenizer, marker: str) -> int | None:
"""Prefer grammar token IDs when the tokenizer exposes atomic markers."""
convert = getattr(tokenizer, "convert_tokens_to_ids", None)
if convert is None:
return None
token = convert(marker)
if isinstance(token, int) and token != getattr(tokenizer, "unk_token_id", None):
return token
return None
def _after_header(
tokenizer, ids: list[int], header: str, *, last: bool = False
) -> list[int]:
"""Skip a renderer-declared assistant header, including its framing newlines."""
prefix = list(tokenizer.encode(header, add_special_tokens=False))
positions = range(len(ids) - len(prefix), -1, -1) if last else [0]
for i in positions:
if prefix and ids[i : i + len(prefix)] == prefix:
ids = ids[i + len(prefix) :]
while ids and _decode(tokenizer, ids[:1]).strip("\n") == "":
ids = ids[1:]
break
return ids
def prompt_ends_in_reasoning(
tokenizer,
prompt_ids: list[int] | None,
*,
open_marker: str = "<think>",
close_marker: str = "</think>",
stop_ids: set[int] | frozenset[int] = frozenset(),
assistant_prefix: str = "<|im_start|>assistant\n",
initial_only: bool = True,
) -> bool:
"""Determine the initial channel from the current assistant prompt prefix."""
if not prompt_ids:
return False
start = next(
(
i + 1
for i in range(len(prompt_ids) - 1, -1, -1)
if prompt_ids[i] in stop_ids
),
0,
)
tail = _after_header(tokenizer, prompt_ids[start:], assistant_prefix, last=True)
if not initial_only:
text = _decode(tokenizer, tail)
return text.rfind(open_marker) > text.rfind(close_marker)
return scan_reasoning(
tokenizer,
tail,
open_id=_single_marker_id(tokenizer, open_marker),
close_id=_single_marker_id(tokenizer, close_marker),
open_marker=open_marker,
close_marker=close_marker,
assistant_prefix=assistant_prefix,
).is_open
def scan_reasoning(
tokenizer,
ids: list[int],
*,
prefilled: bool = False,
initial_only: bool = True,
assistant_prefix: str = "<|im_start|>assistant\n",
open_id: int | None = None,
close_id: int | None = None,
tool_start_id: int | None = None,
tool_start_closes_reasoning: bool = False,
prompt_ids: list[int] | None = None,
stop_ids: set[int] | frozenset[int] = frozenset(),
open_marker: str = "<think>",
close_marker: str = "</think>",
) -> ReasoningBoundary:
"""Read the initial reasoning region without interpreting final content.
Tagged formats recognize an opener after leading whitespace in the assistant
body, or continue reasoning opened in the prompt. A first close permanently
switches to content. Atomic delimiters match token IDs, not lookalike text.
Explicit channel formats can opt into channel transitions instead.
``tool_start_closes_reasoning`` lets an atomic tool-call opener end a
region that has no close marker, as vLLM's parsers do for these formats.
An explicit close still wins: tool markup before it stays reasoning.
"""
if prompt_ids is not None:
prefilled = prompt_ends_in_reasoning(
tokenizer,
prompt_ids,
stop_ids=stop_ids,
open_marker=open_marker,
close_marker=close_marker,
assistant_prefix=assistant_prefix,
initial_only=initial_only,
)
end = next((i for i, token in enumerate(ids) if token in stop_ids), len(ids))
ids = (
_after_header(tokenizer, ids[:end], assistant_prefix)
if initial_only
else ids[:end]
)
if open_id is None:
open_id = _single_marker_id(tokenizer, "<think>")
if close_id is None:
close_id = _single_marker_id(tokenizer, "</think>")
if initial_only:
# Reasoning-first grammars have one initial reasoning region. Once it
# closes, later markers are content, not a new reasoning channel.
if open_id is not None and close_id is not None:
opening = next((i for i, token in enumerate(ids) if token == open_id), -1)
explicit = opening != -1 and not _decode(tokenizer, ids[:opening]).strip()
if not prefilled and not explicit:
return ReasoningBoundary(False, None)
start = opening + 1 if explicit else 0
close = next((i for i in range(start, len(ids)) if ids[i] == close_id), -1)
by_tool = False
if close == -1 and tool_start_closes_reasoning:
close = next(
(i for i in range(start, len(ids)) if ids[i] == tool_start_id), -1
)
by_tool = close != -1
return ReasoningBoundary(
close == -1,
_decode(
tokenizer,
[
token
for token in ids[start : close if close != -1 else len(ids)]
if token != open_id
],
),
by_tool,
)
text = _decode(tokenizer, ids)
opening = text.find(open_marker)
explicit = opening != -1 and not text[:opening].strip()
if not prefilled and not explicit:
return ReasoningBoundary(False, None)
start = opening + len(open_marker) if explicit else 0
close = text.find(close_marker, start)
by_tool = False
if close == -1 and tool_start_closes_reasoning:
tool = next((i for i, t in enumerate(ids) if t == tool_start_id), -1)
tool_pos = len(_decode(tokenizer, ids[:tool])) if tool != -1 else -1
if tool_pos >= start:
close, by_tool = tool_pos, True
return ReasoningBoundary(
close == -1,
text[start : close if close != -1 else len(text)].replace(open_marker, ""),
by_tool,
)
events: list[tuple[int, int, bool | None]]
if open_id is None or close_id is None:
text = _decode(tokenizer, ids)
import re
events = [
(m.start(), m.end(), m.group() == "<think>")
for m in re.finditer(r"<think>|</think>", text)
]
events.extend(
(len(_decode(tokenizer, ids[:i])), 0, None)
for i, token in enumerate(ids)
if token == tool_start_id
)
end = len(text)
def decode_region(a, b):
return text[a:b]
else:
events = [
(i, i + 1, t == open_id)
for i, t in enumerate(ids)
if t in {open_id, close_id}
]
events.extend(
(i, 0, None) for i, token in enumerate(ids) if token == tool_start_id
)
end = len(ids)
def decode_region(a, b):
return _decode(tokenizer, ids[a:b])
active = prefilled
start = 0
by_tool = False
closed_regions: list[tuple[int, int]] = []
events.sort()
for n, (pos, after, opening) in enumerate(events):
if opening is None:
if not active:
break
# While a region is active, its next close ends it; without one,
# the tool opener does.
if tool_start_closes_reasoning and all(
o is not False for _, _, o in events[n + 1 :]
):
closed_regions.append((start, pos))
active = False
by_tool = True
continue
if opening:
if not active:
active = True
start = after
elif pos == 0:
start = after
elif active:
closed_regions.append((start, pos))
active = False
if active:
closed_regions.append((start, end))
return ReasoningBoundary(
is_open=active,
text="".join(decode_region(a, b) for a, b in closed_regions),
closed_by_tool=by_tool,
)
+192
View File
@@ -0,0 +1,192 @@
"""Token-aware boundaries and state transitions for tagged completion grammars."""
import re
from collections.abc import Iterator, Mapping
from dataclasses import dataclass, field
from renderers.reasoning import ReasoningBoundary
@dataclass(frozen=True)
class TaggedGrammar:
transitions: Mapping[tuple[str, str], str]
text_markers: Mapping[str, str] = field(default_factory=dict)
@dataclass(frozen=True)
class TaggedToolBlock:
text: str
token_span: tuple[int, int]
closed: bool
@dataclass(frozen=True)
class TaggedResponse:
boundary: ReasoningBoundary
content: str
tools: list[TaggedToolBlock]
@dataclass(frozen=True)
class _Lexeme:
terminal: str
text: str
start: int
end: int
def _decode(tokenizer, ids: list[int]) -> str:
return tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
def _text_lexemes(
tokenizer, ids: list[int], offset: int, markers: Mapping[str, str]
) -> Iterator[_Lexeme]:
text = _decode(tokenizer, ids)
if not markers:
yield _Lexeme("text", text, offset, offset + len(ids))
return
pattern = "|".join(
re.escape(marker)
for marker in sorted(markers, key=lambda marker: len(marker), reverse=True)
)
cursor = 0
token_cursor = 0
decoded_end = 0
def token_boundary(char_offset: int, *, end: bool) -> int:
nonlocal token_cursor, decoded_end
while decoded_end < char_offset and token_cursor < len(ids):
token_cursor += 1
decoded_end = len(_decode(tokenizer, ids[:token_cursor]))
# A token may contain both framing whitespace and part of a delimiter.
# Cover the whole token without re-encoding or editing sampled IDs.
return offset + token_cursor - int(not end and decoded_end > char_offset)
for match in re.finditer(pattern, text):
start = token_boundary(match.start(), end=False)
end = token_boundary(match.end(), end=True)
yield _Lexeme("text", text[cursor : match.start()], offset, start)
yield _Lexeme(markers[match.group()], match.group(), start, end)
cursor = match.end()
yield _Lexeme("text", text[cursor:], offset, offset + len(ids))
def _lex(
tokenizer,
ids: list[int],
atomic_markers: Mapping[int, str],
text_markers: Mapping[str, str],
) -> Iterator[_Lexeme]:
"""Atomic terminals match IDs; textual terminals match only decoded runs.
In particular, spelling an atomic marker with ordinary tokens leaves it as
text. Splitting at atomic tokens also prevents a textual match across one.
"""
start = 0
for i, token_id in enumerate(ids):
if token_id not in atomic_markers:
continue
yield from _text_lexemes(tokenizer, ids[start:i], start, text_markers)
yield _Lexeme(
atomic_markers[token_id], _decode(tokenizer, [token_id]), i, i + 1
)
start = i + 1
yield from _text_lexemes(tokenizer, ids[start:], start, text_markers)
def scan_tagged_response(
tokenizer,
ids: list[int],
*,
thinking: bool,
atomic_markers: Mapping[int, str],
grammar: TaggedGrammar,
) -> TaggedResponse:
"""Classify channels and tool blocks in one pass over the same terminals.
``tool`` owns its payload until the grammar transitions out of it: reasoning
delimiters and nested openers there are payload, not independent scans.
Tool argument conversion is left to the model-specific parser.
"""
state = "reasoning" if thinking else "content"
opened = thinking
reasoning: list[str] = []
content: list[str] = []
tools: list[TaggedToolBlock] = []
tool_text: list[str] = []
tool_start = 0
for lexeme in _lex(tokenizer, ids, atomic_markers, grammar.text_markers):
next_state = grammar.transitions.get((state, lexeme.terminal))
if next_state is None:
if state == "tool":
tool_text.append(lexeme.text)
elif state == "reasoning":
reasoning.append(lexeme.text)
elif state == "content":
content.append(lexeme.text)
continue
if state == "tool" and next_state != "tool":
closed = lexeme.terminal == "tool_end"
if closed:
tool_text.append(lexeme.text)
tools.append(
TaggedToolBlock(
"".join(tool_text),
(tool_start, lexeme.end if closed else lexeme.start),
closed,
)
)
elif state != "tool" and next_state == "tool":
tool_start = lexeme.start
tool_text = [lexeme.text]
state = next_state
opened |= state == "reasoning"
if state == "tool":
tools.append(TaggedToolBlock("".join(tool_text), (tool_start, len(ids)), False))
return TaggedResponse(
ReasoningBoundary(state == "reasoning", "".join(reasoning) if opened else None),
"".join(content),
tools,
)
_REASONING_TRANSITIONS = {
("content", "think_start"): "reasoning",
("reasoning", "think_start"): "reasoning",
("reasoning", "think_end"): "content",
("content", "think_end"): "content",
}
# vLLM 0.31: GLM resumes content after a call; DeepSeek stays between calls
# and drops trailing prose. Keep those format rules separate from lexing.
GLM_GRAMMAR = TaggedGrammar(
{
**_REASONING_TRANSITIONS,
("content", "tool_start"): "tool",
("reasoning", "tool_start"): "tool",
("tool", "tool_end"): "content",
}
)
DEEPSEEK_V4_GRAMMAR = TaggedGrammar(
{
**_REASONING_TRANSITIONS,
("content", "section_start"): "preamble",
("reasoning", "section_start"): "preamble",
("between", "section_start"): "preamble",
("content", "tool_start"): "tool",
("preamble", "tool_start"): "tool",
("between", "tool_start"): "tool",
("tool", "tool_end"): "between",
("tool", "section_end"): "between",
},
{
"<|DSML|tool_calls>": "section_start",
"<|DSML|toolcalls>": "section_start",
"<|DSML|tool>": "section_start",
"</|DSML|tool_calls>": "section_end",
"<|DSML|invoke": "tool_start",
"</|DSML|invoke>": "tool_end",
},
)
+81
View File
@@ -0,0 +1,81 @@
"""Manual audit: uv run pytest tests/audit_prefix_stability.py -q."""
import json
from difflib import unified_diff
from pathlib import Path
import pytest
from conftest import _load
from renderers import DefaultRenderer, create_renderer
from renderers.base import RENDERER_REGISTRY, _populate_registry
from renderers.configs import _config_class_for
_CORPUS = json.loads(
(Path(__file__).parent / "fixtures" / "prefix_stability.json").read_text()
)
def _prefix_diff(tokenizer, before, after):
candidate = after[: len(before)]
if before == candidate:
return "No differing token: this witness now preserves the original prefix."
index = next(
(i for i, (left, right) in enumerate(zip(before, candidate)) if left != right),
min(len(before), len(candidate)),
)
diff = "\n".join(
unified_diff(
tokenizer.decode(before).splitlines(),
tokenizer.decode(candidate).splitlines(),
fromfile="original render",
tofile="same-length prefix after append",
lineterm="",
)
)
return (
f"First differing token: {index}\n"
f"Before: {before[index : index + 8]}\n"
f"After: {candidate[index : index + 8]}\n{diff}"
)
@pytest.mark.parametrize("case", _CORPUS["cases"], ids=lambda case: case["id"])
def test_prefix_stability_witness(case):
config = dict(case["config"])
name = config.pop("name")
config_cls = _config_class_for(name)
tokenizer, _ = _load(case["model"], name)
renderer = create_renderer(tokenizer, config_cls(**config))
scenario = _CORPUS["scenarios"][case["scenario"]]
messages = scenario["messages"]
assert messages[-1]["role"] == "assistant" and scenario["append"]
before = renderer.render_ids(messages, tools=scenario.get("tools"))
after = renderer.render_ids(
messages + scenario["append"], tools=scenario.get("tools")
)
extends = after[: len(before)] == before
assert renderer.is_prefix_stable is case["stable"], case["reason"]
assert extends is case["stable"], (
f"{case['reason']}\n{_prefix_diff(tokenizer, before, after)}"
)
def test_corpus_covers_builtin_renderers():
_populate_registry()
assert {case["config"]["name"] for case in _CORPUS["cases"]} | {"default"} == set(
RENDERER_REGISTRY
)
assert len({case["id"] for case in _CORPUS["cases"]}) == len(_CORPUS["cases"])
# An opaque template is unknown; inventing a counterexample would be wrong.
assert DefaultRenderer(object()).is_prefix_stable is False
def test_stability_uses_auto_resolved_template_kwargs():
tokenizer, _ = _load("Qwen/Qwen3.8-27B", "qwen3.8")
assert create_renderer(tokenizer).is_prefix_stable is True
assert (
create_renderer(
tokenizer, chat_template_kwargs={"preserve_thinking": False}
).is_prefix_stable
is False
)
+29 -111
View File
@@ -2,66 +2,34 @@
Each (model_name, renderer_name) pair gets a tokenizer + renderer.
The same barrage of tests runs against every pair.
Modules with their own model caches release them in ``teardown_module``.
The module-scoped fixture below releases shared models and cyclic references.
"""
import os
import gc
from pathlib import Path
import pytest
from parity import models_for
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")
#
# Baseline matrix for render-parity, parse, and per-token-attribution
# tests. Models here are exercised by every shared test in this folder.
# Additional models for narrower tests (e.g. roundtrip) live with their
# 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"),
("zai-org/GLM-5", "auto"),
("zai-org/GLM-5.1", "auto"),
("zai-org/GLM-4.7-Flash", "auto"),
("THUDM/GLM-4.5-Air", "auto"),
("MiniMaxAI/MiniMax-M2.5", "auto"),
("moonshotai/Kimi-K2-Instruct", "auto"),
("moonshotai/Kimi-K2.5", "auto"),
("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"),
]
# Backwards-compatible view used by documentation and a few invariant tests.
RENDERER_MODELS = [(case.model, case.renderer) for case in models_for("shared")]
_cache: dict[str, tuple] = {}
@pytest.fixture(scope="module", autouse=True)
def release_shared_models():
"""Keep model caches local to a test module, including cyclic HF objects."""
yield
_cache.clear()
gc.collect()
def _load(model_name: str, renderer_name: str):
key = f"{model_name}:{renderer_name}"
if key not in _cache:
@@ -73,10 +41,21 @@ def _load(model_name: str, renderer_name: str):
def pytest_generate_tests(metafunc):
if "model_name" in metafunc.fixturenames:
filename = Path(str(metafunc.definition.path)).name
if filename == "test_build_helpers.py":
suite = "build-helpers"
elif filename in {
"test_parse_response.py",
"test_parse_response_robustness.py",
}:
suite = "plain-parser"
else:
suite = "shared"
cases = models_for(suite)
metafunc.parametrize(
"model_name,renderer_name",
RENDERER_MODELS,
ids=[m for m, _ in RENDERER_MODELS],
[(case.model, case.renderer) for case in cases],
ids=[case.model for case in cases],
)
@@ -90,64 +69,3 @@ def tokenizer(model_name, renderer_name):
def renderer(model_name, renderer_name):
_, r = _load(model_name, renderer_name)
return r
# Tests that compare the renderer output (or downstream tokens) against
# HF's ``apply_chat_template`` — or that feed plain text through the
# parser expecting a non-empty content. Both fail for gpt-oss because:
# 1. Our GptOssRenderer matches openai-harmony / vLLM, not HF's Jinja
# (they disagree on a trailing ``\n\n`` and the function-tools
# layout). Harmony parity is covered separately in
# ``test_gpt_oss_harmony_parity.py``.
# 2. The harmony parser only emits content from messages bracketed by
# ``<|start|>...<|message|>...<|end|>`` channel markers; plain text
# never matches a block, so the test's "Hello there!" probe
# trivially returns empty content. The parsing-test fixtures aren't
# designed for harmony format.
_GPT_OSS_HF_PARITY_TEST_FILES = {
"test_render_ids.py",
"test_build_helpers.py",
"test_parse_response.py",
"test_parse_response_robustness.py",
}
@pytest.fixture(autouse=True)
def _skip_gpt_oss_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 != "openai/gpt-oss-20b":
return
test_file = os.path.basename(str(request.node.fspath))
if test_file in _GPT_OSS_HF_PARITY_TEST_FILES:
pytest.skip(
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"
)
+792
View File
@@ -0,0 +1,792 @@
{
"scenarios": {
"later-user-with-reasoning": {
"messages": [
{
"role": "user",
"content": "First question?"
},
{
"role": "assistant",
"content": "First answer.",
"reasoning_content": "First reasoning."
}
],
"append": [
{
"role": "user",
"content": "Second question?"
}
]
},
"later-user-with-empty-reasoning": {
"messages": [
{
"role": "user",
"content": "First question?"
},
{
"role": "assistant",
"content": "First answer.",
"reasoning_content": ""
}
],
"append": [
{
"role": "user",
"content": "Second question?"
}
]
},
"complete-tool-cycle": {
"messages": [
{
"role": "user",
"content": "Weather in Paris?"
},
{
"role": "assistant",
"content": "First answer.",
"reasoning_content": "First reasoning.",
"tool_calls": [
{
"id": "call_0",
"type": "function",
"function": {
"name": "get_weather",
"arguments": {
"city": "Paris"
}
}
}
]
}
],
"append": [
{
"role": "tool",
"name": "get_weather",
"tool_call_id": "call_0",
"content": "Sunny."
},
{
"role": "assistant",
"content": "It is sunny.",
"reasoning_content": "Summarize."
}
],
"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"
]
}
}
}
]
},
"assistant-task-marker": {
"messages": [
{
"role": "user",
"content": "Question?"
},
{
"role": "assistant",
"content": "Answer.",
"task": "query"
}
],
"append": [
{
"role": "user",
"content": "Follow up?"
}
]
},
"reused-tool-call-id": {
"messages": [
{
"role": "user",
"content": "First?"
},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_0",
"function": {
"name": "first",
"arguments": {}
}
}
]
},
{
"role": "tool",
"tool_call_id": "call_0",
"content": "Result."
},
{
"role": "assistant",
"content": "Done."
}
],
"append": [
{
"role": "user",
"content": "Second?"
},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_0",
"function": {
"name": "second",
"arguments": {}
}
}
]
}
]
},
"open-continuation": {
"messages": [
{
"role": "user",
"content": "Question?"
},
{
"role": "assistant",
"content": "a",
"wo_eos": true
}
],
"append": [
{
"role": "assistant",
"content": "b"
}
]
}
},
"cases": [
{
"id": "qwen3-default",
"model": "Qwen/Qwen3-8B",
"config": {
"name": "qwen3"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning, even when thinking generation is disabled."
},
{
"id": "qwen3-enable_thinking=false",
"model": "Qwen/Qwen3-8B",
"config": {
"name": "qwen3",
"enable_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning, even when thinking generation is disabled."
},
{
"id": "qwen3-thinking_retention=all",
"model": "Qwen/Qwen3-8B",
"config": {
"name": "qwen3",
"thinking_retention": "all"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning, even when thinking generation is disabled."
},
{
"id": "prime-qwen3-default",
"model": "PrimeIntellect/Qwen3-0.6B",
"config": {
"name": "prime-qwen3"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "qwen3.5-default",
"model": "Qwen/Qwen3.5-9B",
"config": {
"name": "qwen3.5"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier thinking blocks."
},
{
"id": "qwen3.5-enable_thinking=false",
"model": "Qwen/Qwen3.5-9B",
"config": {
"name": "qwen3.5",
"enable_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier thinking blocks."
},
{
"id": "qwen3.6-default",
"model": "Qwen/Qwen3.6-35B-A3B",
"config": {
"name": "qwen3.6"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "preserve_thinking=False removes earlier thinking blocks."
},
{
"id": "qwen3.6-preserve_thinking=true",
"model": "Qwen/Qwen3.6-35B-A3B",
"config": {
"name": "qwen3.6",
"preserve_thinking": true
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "qwen3.8-default",
"model": "Qwen/Qwen3.8-27B",
"config": {
"name": "qwen3.8"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "qwen3.8-preserve_thinking=false",
"model": "Qwen/Qwen3.8-27B",
"config": {
"name": "qwen3.8",
"preserve_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "preserve_thinking=False removes earlier thinking blocks."
},
{
"id": "qwen3-vl-default",
"model": "Qwen/Qwen3-VL-4B-Instruct",
"config": {
"name": "qwen3-vl"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "gemma4-default",
"model": "google/gemma-4-31B-it",
"config": {
"name": "gemma4"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "Historical final-answer reasoning is removed even when tool reasoning is preserved."
},
{
"id": "gemma4-preserve_thinking=true",
"model": "google/gemma-4-31B-it",
"config": {
"name": "gemma4",
"preserve_thinking": true
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "Historical final-answer reasoning is removed even when tool reasoning is preserved."
},
{
"id": "gemma4-enable_thinking=false",
"model": "google/gemma-4-31B-it",
"config": {
"name": "gemma4",
"enable_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "Historical final-answer reasoning is removed even when tool reasoning is preserved."
},
{
"id": "glm-5-default",
"model": "zai-org/GLM-5",
"config": {
"name": "glm-5"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "clear_thinking=True removes earlier reasoning."
},
{
"id": "glm-5-clear_thinking=false",
"model": "zai-org/GLM-5",
"config": {
"name": "glm-5",
"clear_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "glm-5-enable_thinking=false",
"model": "zai-org/GLM-5",
"config": {
"name": "glm-5",
"enable_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "clear_thinking=True removes earlier reasoning."
},
{
"id": "glm-5.1-default",
"model": "zai-org/GLM-5.1",
"config": {
"name": "glm-5.1"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "glm-5.1-clear_thinking=false",
"model": "zai-org/GLM-5.1",
"config": {
"name": "glm-5.1",
"clear_thinking": false
},
"scenario": "later-user-with-empty-reasoning",
"stable": false,
"reason": "The final empty thinking wrapper is removed from history."
},
{
"id": "glm-5.1-clear_thinking=false-enable_thinking=false",
"model": "zai-org/GLM-5.1",
"config": {
"name": "glm-5.1",
"clear_thinking": false,
"enable_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "glm-5.3-default",
"model": "zai-org/GLM-5.3",
"config": {
"name": "glm-5.3"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "glm-5.3-clear_thinking=true",
"model": "zai-org/GLM-5.3",
"config": {
"name": "glm-5.3",
"clear_thinking": true
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "clear_thinking=True removes earlier reasoning."
},
{
"id": "glm-4.5-default",
"model": "THUDM/GLM-4.5-Air",
"config": {
"name": "glm-4.5"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "minimax-m2-default",
"model": "MiniMaxAI/MiniMax-M2.5",
"config": {
"name": "minimax-m2"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "kimi-k2-default",
"model": "moonshotai/Kimi-K2-Instruct",
"config": {
"name": "kimi-k2"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "kimi-k2.5-default",
"model": "moonshotai/Kimi-K2.5",
"config": {
"name": "kimi-k2.5"
},
"scenario": "complete-tool-cycle",
"stable": false,
"reason": "Completing a tool cycle removes its earlier reasoning."
},
{
"id": "kimi-k2.5-thinking=false",
"model": "moonshotai/Kimi-K2.5",
"config": {
"name": "kimi-k2.5",
"thinking": false
},
"scenario": "complete-tool-cycle",
"stable": false,
"reason": "Completing a tool cycle removes its earlier reasoning."
},
{
"id": "deepseek-v4-default",
"model": "deepseek-ai/DeepSeek-V4-Flash-0731",
"config": {
"name": "deepseek-v4"
},
"scenario": "assistant-task-marker",
"stable": false,
"reason": "A task marker at the end of an assistant disappears when a user is appended."
},
{
"id": "deepseek-v4-enable_thinking=true",
"model": "deepseek-ai/DeepSeek-V4-Flash-0731",
"config": {
"name": "deepseek-v4",
"enable_thinking": true
},
"scenario": "assistant-task-marker",
"stable": false,
"reason": "A task marker at the end of an assistant disappears when a user is appended."
},
{
"id": "deepseek-v4-enable_thinking=true-drop_thinking=false",
"model": "deepseek-ai/DeepSeek-V4-Flash-0731",
"config": {
"name": "deepseek-v4",
"enable_thinking": true,
"drop_thinking": false
},
"scenario": "assistant-task-marker",
"stable": false,
"reason": "A task marker at the end of an assistant disappears when a user is appended."
},
{
"id": "nemotron-3-default",
"model": "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
"config": {
"name": "nemotron-3"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "nemotron-3-truncate_history_thinking=false",
"model": "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
"config": {
"name": "nemotron-3",
"truncate_history_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "nemotron-3-enable_thinking=false",
"model": "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
"config": {
"name": "nemotron-3",
"enable_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "nemotron-3-default-super",
"model": "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
"config": {
"name": "nemotron-3"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "nemotron-3-truncate_history_thinking=false-super",
"model": "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
"config": {
"name": "nemotron-3",
"truncate_history_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "nemotron-3-enable_thinking=false-super",
"model": "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
"config": {
"name": "nemotron-3",
"enable_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "nemotron-3-truncate_history_thinking=false-low_effort=true-super",
"model": "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
"config": {
"name": "nemotron-3",
"truncate_history_thinking": false,
"low_effort": true
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "The effort hint moves from the first user to the appended user."
},
{
"id": "nemotron-3-ultra-default",
"model": "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
"config": {
"name": "nemotron-3-ultra"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "nemotron-3-ultra-truncate_history_thinking=false",
"model": "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
"config": {
"name": "nemotron-3-ultra",
"truncate_history_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "nemotron-3-ultra-truncate_history_thinking=false-medium_effort=true",
"model": "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
"config": {
"name": "nemotron-3-ultra",
"truncate_history_thinking": false,
"medium_effort": true
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "The effort hint moves from the first user to the appended user."
},
{
"id": "nemotron-3.5-default",
"model": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16",
"config": {
"name": "nemotron-3.5"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "nemotron-3.5-truncate_history_thinking=false",
"model": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16",
"config": {
"name": "nemotron-3.5",
"truncate_history_thinking": false
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "laguna-xs.2-default",
"model": "poolside/Laguna-XS.2",
"config": {
"name": "laguna-xs.2"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "laguna-m.1-default",
"model": "poolside/Laguna-M.1",
"config": {
"name": "laguna-m.1"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "laguna-xs-2.1-default",
"model": "poolside/Laguna-XS-2.1",
"config": {
"name": "laguna-xs-2.1"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "laguna-s-2.1-default",
"model": "poolside/Laguna-S-2.1",
"config": {
"name": "laguna-s-2.1"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "llama-3-default",
"model": "meta-llama/Llama-3.2-1B-Instruct",
"config": {
"name": "llama-3"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "gpt-oss-default",
"model": "openai/gpt-oss-20b",
"config": {
"name": "gpt-oss"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "The last assistant terminator changes when another turn is appended."
},
{
"id": "gpt-oss-auto_drop_analysis=false",
"model": "openai/gpt-oss-20b",
"config": {
"name": "gpt-oss",
"auto_drop_analysis": false
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "The last assistant terminator changes when another turn is appended."
},
{
"id": "hy3-default",
"model": "tencent/Hy3",
"config": {
"name": "hy3"
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A later user query removes earlier reasoning."
},
{
"id": "hy3-preserved_thinking=true",
"model": "tencent/Hy3",
"config": {
"name": "hy3",
"preserved_thinking": true
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "hy3-is_training=true",
"model": "tencent/Hy3",
"config": {
"name": "hy3",
"is_training": true
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "hy3-preserved_thinking=true-raw_last_assistant=true",
"model": "tencent/Hy3",
"config": {
"name": "hy3",
"preserved_thinking": true,
"raw_last_assistant": true
},
"scenario": "later-user-with-reasoning",
"stable": false,
"reason": "A raw final assistant becomes a wrapped historical turn."
},
{
"id": "inkling-default",
"model": "thinkingmachines/Inkling",
"config": {
"name": "inkling"
},
"scenario": "reused-tool-call-id",
"stable": false,
"reason": "A reused tool-call ID changes a historical tool response name."
},
{
"id": "deepseek-v4-default-open-continuation",
"model": "deepseek-ai/DeepSeek-V4-Flash-0731",
"config": {
"name": "deepseek-v4"
},
"scenario": "open-continuation",
"stable": false,
"reason": "Unterminated assistant content is re-tokenized with the appended continuation."
},
{
"id": "deepseek-v3-default",
"model": "deepseek-ai/DeepSeek-V3",
"config": {
"name": "deepseek-v3"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
},
{
"id": "deepseek-r1-default",
"model": "deepseek-ai/DeepSeek-R1",
"config": {
"name": "deepseek-r1"
},
"scenario": "later-user-with-reasoning",
"stable": true,
"reason": "Stable control: these tokens must remain a prefix."
}
]
}
+786
View File
@@ -0,0 +1,786 @@
"""Shared catalog and scenario corpus for renderer reference-parity tests."""
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import field as dataclass_field
from itertools import product
from typing import Any, Iterable, Mapping
from renderers.base import MODEL_RENDERER_MAP
from renderers.configs import _config_class_for
from tests.reference_rendering import reference_oracle_for_renderer
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"],
},
},
}
]
@dataclass(frozen=True)
class ModelCase:
model: str
renderer: str = "auto"
suites: frozenset[str] = frozenset({"parity"})
excluded_scenarios: frozenset[str] = frozenset()
oracle_defaults: tuple[tuple[str, Any], ...] = ()
@property
def resolved_renderer(self) -> str:
if self.renderer != "auto":
return self.renderer
return MODEL_RENDERER_MAP.get(self.model, "default")
@property
def oracle(self) -> str:
return reference_oracle_for_renderer(self.resolved_renderer)
def _model(
model: str,
*,
renderer: str = "auto",
shared: bool = True,
roundtrip: bool = True,
bridge: bool = False,
excluded: Iterable[str] = (),
oracle_defaults: Mapping[str, Any] | None = None,
extra_suites: Iterable[str] = (),
) -> ModelCase:
suites = {"parity"}
if shared:
suites.update({"shared", "plain-parser", "build-helpers"})
if roundtrip:
suites.add("roundtrip")
if bridge:
suites.add("bridge")
resolved_renderer = (
MODEL_RENDERER_MAP.get(model, "default") if renderer == "auto" else renderer
)
if reference_oracle_for_renderer(resolved_renderer) == "harmony":
suites.discard("plain-parser")
suites.discard("build-helpers")
if model.startswith("meta-llama/"):
suites.discard("build-helpers")
suites.update(extra_suites)
return ModelCase(
model=model,
renderer=renderer,
suites=frozenset(suites),
excluded_scenarios=frozenset(excluded),
oracle_defaults=tuple((oracle_defaults or {}).items()),
)
# This is the only test-side model catalog. Suites select views of it instead
# of maintaining their own nearly-identical model lists.
MODEL_CATALOG = (
_model(
"Qwen/Qwen3-8B",
bridge=True,
extra_suites={"tool-arg-types", "disabled-thinking"},
),
_model(
"PrimeIntellect/Qwen3-0.6B",
bridge=True,
extra_suites={"tool-arg-types"},
),
_model("PrimeIntellect/Qwen3-1.7B", shared=False, roundtrip=False),
_model("Qwen/Qwen3.5-0.8B", shared=False, roundtrip=False),
_model("Qwen/Qwen3.5-2B", shared=False, roundtrip=False),
_model("Qwen/Qwen3.5-4B", shared=False, roundtrip=False),
_model(
"Qwen/Qwen3.5-9B",
bridge=True,
extra_suites={"tool-arg-types", "disabled-thinking"},
),
_model("Qwen/Qwen3.5-35B-A3B", shared=False, roundtrip=False),
_model("Qwen/Qwen3.5-122B-A10B", shared=False, roundtrip=False),
_model("Qwen/Qwen3.5-397B-A17B", shared=False, roundtrip=False),
_model(
"Qwen/Qwen3.6-35B-A3B",
bridge=True,
extra_suites={"disabled-thinking"},
),
_model(
"Qwen/Qwen3.8-27B",
bridge=True,
extra_suites={"disabled-thinking"},
),
_model(
"Qwen/Qwen3.8-Flash-Next",
bridge=True,
extra_suites={"disabled-thinking"},
),
_model(
"Qwen/Qwen3-VL-4B-Instruct",
bridge=False,
excluded={"tool-call-none"},
),
_model(
"google/gemma-4-E2B-it",
shared=False,
roundtrip=False,
extra_suites={"gemma-checkpoints"},
),
_model(
"google/gemma-4-E4B-it",
shared=False,
roundtrip=False,
extra_suites={"gemma-checkpoints"},
),
_model(
"google/gemma-4-26B-A4B-it",
shared=False,
roundtrip=False,
extra_suites={"gemma-checkpoints", "disabled-thinking"},
),
_model(
"google/gemma-4-31B-it",
bridge=True,
extra_suites={"gemma-checkpoints"},
),
_model(
"zai-org/GLM-5",
bridge=True,
extra_suites={"tool-arg-types", "glm-tool-names"},
),
_model("zai-org/GLM-5.1", bridge=True),
_model(
"zai-org/GLM-5.3",
bridge=True,
extra_suites={"tool-arg-types", "glm-tool-names"},
),
_model("zai-org/GLM-4.7-Flash"),
_model(
"THUDM/GLM-4.5-Air",
bridge=True,
extra_suites={"glm-tool-names"},
),
_model(
"MiniMaxAI/MiniMax-M2.5",
bridge=True,
extra_suites={"tool-arg-types"},
),
_model(
"moonshotai/Kimi-K2-Instruct",
bridge=True,
extra_suites={"tool-arg-types"},
),
_model(
"moonshotai/Kimi-K2.5",
bridge=True,
excluded={"inline-thinking-history"},
),
_model(
"moonshotai/Kimi-K2.6",
bridge=False,
excluded={"inline-thinking-history"},
),
_model(
"deepseek-ai/DeepSeek-V3",
shared=False,
roundtrip=False,
excluded={
"tool-call-content",
"tool-call-none",
"multiple-tool-calls",
"tool-response",
"named-tool-response",
"consecutive-tool-responses",
"full-tool-cycle",
"multi-step-tool-cycle",
},
),
_model(
"deepseek-ai/DeepSeek-R1",
shared=False,
roundtrip=False,
excluded={
"tool-call-content",
"tool-call-none",
"multiple-tool-calls",
"tool-response",
"named-tool-response",
"consecutive-tool-responses",
"full-tool-cycle",
"multi-step-tool-cycle",
},
),
# DeepSeek V4 ships a Python encoder instead of a Jinja chat template.
# tests/reference_rendering.py supplies its independent reference oracle.
_model("deepseek-ai/DeepSeek-V4-Flash-0731", bridge=True),
_model(
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
bridge=True,
extra_suites={"tool-arg-types"},
),
_model("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"),
_model("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16"),
_model("nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16", bridge=True),
_model(
"poolside/Laguna-XS.2",
bridge=False,
extra_suites={"tool-arg-types"},
),
_model("poolside/Laguna-M.1", bridge=False),
_model("poolside/Laguna-XS-2.1", roundtrip=False, bridge=False),
_model("poolside/Laguna-S-2.1", roundtrip=False, bridge=False),
_model(
"meta-llama/Llama-3.2-1B-Instruct",
bridge=True,
excluded={"multiple-tool-calls", "consecutive-tool-responses"},
oracle_defaults={"date_string": "26 Jul 2024"},
extra_suites={"llama-checkpoints"},
),
_model(
"meta-llama/Llama-3.2-3B-Instruct",
shared=False,
roundtrip=False,
excluded={"multiple-tool-calls", "consecutive-tool-responses"},
oracle_defaults={"date_string": "26 Jul 2024"},
extra_suites={"llama-checkpoints"},
),
_model(
"openai/gpt-oss-20b",
renderer="gpt-oss",
bridge=True,
excluded={"multi-step-tool-cycle"},
),
_model("tencent/Hy3", bridge=True),
_model("thinkingmachines/Inkling", bridge=True),
_model("thinkingmachines/Inkling-Small", bridge=True),
_model(
"Qwen/Qwen2.5-0.5B-Instruct",
renderer="default",
roundtrip=True,
bridge=False,
),
)
def models_for(suite: str) -> tuple[ModelCase, ...]:
return tuple(case for case in MODEL_CATALOG if suite in case.suites)
@dataclass(frozen=True)
class Scenario:
id: str
messages: tuple[Mapping[str, Any], ...]
tools: tuple[Mapping[str, Any], ...] = ()
add_generation_prompt: bool = False
only_renderers: frozenset[str] = dataclass_field(default_factory=frozenset)
@property
def render_kwargs(self) -> dict[str, Any]:
kwargs: dict[str, Any] = {"add_generation_prompt": self.add_generation_prompt}
if self.tools:
kwargs["tools"] = list(self.tools)
return kwargs
def _scenario(
id: str,
messages: list[dict[str, Any]],
*,
tools: list[dict[str, Any]] | None = None,
add_generation_prompt: bool = False,
only_renderers: Iterable[str] = (),
) -> Scenario:
return Scenario(
id=id,
messages=tuple(messages),
tools=tuple(tools or ()),
add_generation_prompt=add_generation_prompt,
only_renderers=frozenset(only_renderers),
)
def _call(city: str, *, id: str | None = None) -> dict:
call: dict[str, Any] = {
"type": "function",
"function": {"name": "get_weather", "arguments": {"city": city}},
}
if id is not None:
call["id"] = id
return call
# Scenarios are deliberately renderer-agnostic. Renderer/template limitations
# live in MODEL_CATALOG, so the corpus itself stays reusable and auditable.
SCENARIOS = (
_scenario("user", [{"role": "user", "content": "Hello!"}]),
_scenario(
"system-user",
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hello!"},
],
),
_scenario(
"terminal-assistant",
[
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
],
),
_scenario(
"multi-turn",
[
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
],
),
_scenario(
"empty-assistant",
[
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": ""},
],
),
_scenario(
"reasoning",
[
{"role": "user", "content": "What is 2+2?"},
{
"role": "assistant",
"reasoning_content": "Simple arithmetic.",
"content": "4",
},
],
),
_scenario(
"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",
},
],
),
_scenario(
"inline-thinking-history",
[
{"role": "user", "content": "First"},
{
"role": "assistant",
"content": "<think>raw reasoning</think>visible answer",
},
{"role": "user", "content": "Second"},
],
only_renderers={
"prime-qwen3",
"kimi-k2",
"nemotron-3",
"nemotron-3-ultra",
"nemotron-3.5",
"deepseek-v3",
"deepseek-r1",
},
),
_scenario(
"whitespace",
[
{"role": "system", "content": " system text \n"},
{"role": "user", "content": " user text \n"},
{
"role": "assistant",
"reasoning_content": " reasoning \n",
"content": " answer \n",
},
],
only_renderers={"nemotron-3", "nemotron-3-ultra", "nemotron-3.5"},
),
_scenario(
"generation-prompt",
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
],
add_generation_prompt=True,
),
_scenario(
"generation-prompt-no-system",
[{"role": "user", "content": "Hi"}],
add_generation_prompt=True,
),
_scenario(
"tools-with-system",
[
{"role": "system", "content": "You are a weather assistant."},
{"role": "user", "content": "Weather?"},
],
tools=TOOLS,
),
_scenario(
"tools-without-system",
[{"role": "user", "content": "Weather?"}],
tools=TOOLS,
),
_scenario(
"tool-call-content",
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "Let me check.",
"tool_calls": [_call("Paris", id="call_1")],
},
],
tools=TOOLS,
),
_scenario(
"tool-call-none",
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": None,
"tool_calls": [_call("Paris", id="call_1")],
},
],
tools=TOOLS,
),
_scenario(
"multiple-tool-calls",
[
{"role": "user", "content": "Weather in Paris and London?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
_call("Paris", id="call_1"),
_call("London", id="call_2"),
],
},
],
tools=TOOLS,
),
_scenario(
"tool-response",
[
{"role": "user", "content": "Weather?"},
{
"role": "assistant",
"content": "",
"tool_calls": [_call("Paris", id="call_1")],
},
{"role": "tool", "content": '{"temp": 20}', "tool_call_id": "call_1"},
{"role": "assistant", "content": "It is 20 degrees."},
],
tools=TOOLS,
),
_scenario(
"named-tool-response",
[
{"role": "user", "content": "Weather?"},
{
"role": "assistant",
"content": "",
"tool_calls": [_call("Paris", id="call_1")],
},
{
"role": "tool",
"name": "get_weather",
"content": '{"temp": 20}',
"tool_call_id": "call_1",
},
{"role": "assistant", "content": "It is 20 degrees."},
],
tools=TOOLS,
),
_scenario(
"consecutive-tool-responses",
[
{"role": "user", "content": "Weather in Paris and London?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
_call("Paris", id="call_1"),
_call("London", id="call_2"),
],
},
{"role": "tool", "content": '{"temp": 20}', "tool_call_id": "call_1"},
{"role": "tool", "content": '{"temp": 15}', "tool_call_id": "call_2"},
{"role": "assistant", "content": "Paris: 20, London: 15."},
],
tools=TOOLS,
),
_scenario(
"full-tool-cycle",
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "I should use the tool.",
"content": "",
"tool_calls": [_call("Paris", id="call_1")],
},
{"role": "tool", "content": '{"temp": 20}', "tool_call_id": "call_1"},
{"role": "assistant", "content": "It is 20 degrees."},
],
tools=TOOLS,
add_generation_prompt=True,
),
_scenario(
"complex-tool-cycle",
[
{"role": "user", "content": "Compare Paris and London"},
{
"role": "assistant",
"reasoning_content": "Two cities need two calls.",
"content": "",
"tool_calls": [
{
"type": "function",
"function": {
"name": "get_weather",
"arguments": {
"city": "Paris",
"options": {"unit": "c", "days": [1, 2]},
},
},
},
_call("London"),
],
},
{"role": "tool", "content": '{"temp": 20}'},
{"role": "tool", "content": '{"temp": 15}'},
{"role": "assistant", "content": "Paris is warmer."},
],
tools=TOOLS,
only_renderers={
"prime-qwen3",
"nemotron-3",
"nemotron-3-ultra",
"nemotron-3.5",
},
),
_scenario(
"empty-reasoning-assistant",
[
{"role": "user", "content": "Think"},
{
"role": "assistant",
"reasoning_content": "working",
"content": "",
},
],
only_renderers={
"prime-qwen3",
"nemotron-3",
"nemotron-3-ultra",
"nemotron-3.5",
},
),
_scenario(
"generation-after-tool-response",
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "",
"tool_calls": [_call("Paris")],
},
{"role": "tool", "content": '{"temp": 20}'},
],
tools=TOOLS,
add_generation_prompt=True,
only_renderers={
"nemotron-3",
"nemotron-3-ultra",
"nemotron-3.5",
"laguna-m.1",
},
),
_scenario(
"multi-step-tool-cycle",
[
{"role": "user", "content": "Compare Paris and London"},
{
"role": "assistant",
"content": "",
"tool_calls": [_call("Paris", id="call_1")],
},
{"role": "tool", "content": '{"temp": 20}', "tool_call_id": "call_1"},
{
"role": "assistant",
"content": "",
"tool_calls": [_call("London", id="call_2")],
},
{"role": "tool", "content": '{"temp": 15}', "tool_call_id": "call_2"},
{"role": "assistant", "content": "Paris: 20, London: 15."},
],
tools=TOOLS,
),
_scenario(
"empty-system",
[
{"role": "system", "content": ""},
{"role": "user", "content": "Hi"},
],
add_generation_prompt=True,
),
_scenario(
"later-system",
[
{"role": "user", "content": "A"},
{"role": "system", "content": "Late instruction"},
{"role": "user", "content": "B"},
],
only_renderers={"laguna-xs-2.1", "laguna-s-2.1"},
),
_scenario(
"tool-declare-message",
[
{
"role": "tool_declare",
"content": "function calc(x: number): number;",
},
{"role": "user", "content": "Use the calc tool"},
],
only_renderers={"kimi-k2.5"},
),
)
# Representative values for each finite semantic branch. Pydantic validation
# filters the shared union down to the domain accepted by a renderer config.
KWARG_VALUES: Mapping[str, tuple[Any, ...]] = {
"enable_thinking": (True, False, None),
"thinking": (True, False),
"reasoning_effort": (
"no_think",
"low",
"medium",
"high",
"xhigh",
"none",
"minimal",
"max",
0.0,
0.37,
0.99,
),
"preserved_thinking": (True, False, None),
"is_training": (True, False),
"raw_last_assistant": (True, False),
"fallback_strategy": ("reasoning_toolcall_retry", None),
"clear_thinking": (True, False),
"drop_thinking": (True, False),
"truncate_history_thinking": (True, False),
"low_effort": (True, False),
"medium_effort": (True, False),
"model_identity": (
"You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax.",
"You are CustomBot, a research assistant.",
),
"render_assistant_messages_raw": (True, False),
"add_vision_id": (True, False),
"preserve_thinking": (True, False),
"conversation_start_date": ("2025-01-15", None),
"date_string": ("26 Jul 2024", "01 Jan 2030"),
"tools_in_user_message": (True, False),
}
def kwarg_combinations(case: ModelCase) -> tuple[dict[str, Any], ...]:
"""Cartesian product of every valid explicit reference-control value."""
config_cls = _config_class_for(case.resolved_renderer)
fields = sorted(config_cls.template_field_names())
missing = set(fields) - KWARG_VALUES.keys()
if missing:
raise AssertionError(
f"{case.resolved_renderer} declares uncovered template fields: {sorted(missing)}"
)
if not fields:
return ({},)
combinations = [{}]
for values in product(*(KWARG_VALUES[field] for field in fields)):
kwargs = dict(zip(fields, values))
try:
config_cls(**kwargs)
except Exception:
continue
combinations.append(kwargs)
return tuple(combinations)
def scenario_is_valid(
case: ModelCase, scenario: Scenario, kwargs: Mapping[str, Any]
) -> bool:
if scenario.id in case.excluded_scenarios:
return False
if (
scenario.only_renderers
and case.resolved_renderer not in scenario.only_renderers
):
return False
# These renderers intentionally retain a generated empty thinking wrapper
# on plain historical turns when thinking is disabled. That stability
# contract is tested separately; it is not upstream-reference parity.
thinking_disabled = kwargs.get("enable_thinking") is False or (
kwargs.get("enable_thinking") is None
and case.model in {"Qwen/Qwen3.5-0.8B", "Qwen/Qwen3.5-2B"}
)
if (
case.resolved_renderer in {"qwen3", "qwen3.5", "qwen3.6", "qwen3.8"}
and thinking_disabled
and kwargs.get("preserve_thinking") is not True
and scenario.id
in (
{
"multi-turn",
"tool-response",
"named-tool-response",
"consecutive-tool-responses",
"full-tool-cycle",
"multi-step-tool-cycle",
}
if case.resolved_renderer == "qwen3"
else {"multi-turn"}
)
):
return False
# Gemma 4's 26B/31B template revision strips the empty disabled-thinking
# generation prefill from assistant history. The renderer deliberately
# retains it so sampled streams remain byte-prefix-stable across rerenders.
# That behavior is covered by the stability suite, not reference parity.
if (
case.model in {"google/gemma-4-26B-A4B-it", "google/gemma-4-31B-it"}
and kwargs.get("enable_thinking", False) is False
and any(
message.get("role") == "assistant"
and not (message.get("reasoning") or message.get("reasoning_content"))
for message in scenario.messages
)
):
return False
return True
+164
View File
@@ -0,0 +1,164 @@
"""Live responses derived from the independent template/encoder oracle.
History serialization is not always a live completion: R1 drops reasoning,
Harmony drops final-turn analysis, and Gemma drops empty thinking prefills.
These explicit adapters describe those reference contracts. Never repair a
prefix mismatch by silently slicing at a common prefix or asking our renderer
to supply the expected output.
"""
import json
import re
from reference_rendering import _harmony_messages, render_reference
REASONING = "Check the weather carefully."
ANSWER = "It is sunny in Tokyo."
def reference_continuation(tok, case, kwargs, messages, tools, *, calls=0):
options = {
k: v for k, v in (dict(case.oracle_defaults) | kwargs).items() if v is not None
}
def render(conversation, generation=False, **overrides):
return render_reference(
tok,
conversation,
oracle=case.oracle,
tools=tools,
add_generation_prompt=generation,
**(options | overrides),
)
prompt = render(messages, generation=True)
prompt_text = tok.decode(prompt, skip_special_tokens=False)
# Resolve the mode from a reference user-turn prefix even when a tool
# observation continues the same assistant turn without repeating it.
first_user = next(
i for i, message in enumerate(messages) if message["role"] == "user"
)
mode_prefix = tok.decode(render(messages[: first_user + 1], generation=True))
disabled = bool(
re.search(r"(?:</think>|</think:opensource>|<channel\|>)\s*$", mode_prefix)
)
assistant = {"role": "assistant", "content": "" if calls else ANSWER}
if not disabled:
assistant["reasoning_content"] = REASONING
if calls:
assistant["tool_calls"] = [
{
"id": f"functions.get_weather:{index}",
"type": "function",
"function": {"name": "get_weather", "arguments": {"city": city}},
}
for index, city in enumerate(["Tokyo", "Berlin"][:calls])
]
if case.resolved_renderer in {"deepseek-v3", "deepseek-r1"}:
# These upstream templates require null content and JSON strings.
assistant["content"] = None
for call in assistant["tool_calls"]:
fn = call["function"]
fn["arguments"] = json.dumps(fn["arguments"])
# Raw-history modes expect an already serialized assistant body. Serialize
# our structured fixture through the reference's normal branch; these flags
# do not change the live generation prefix (checked independently below).
serialization = {
key: False
for key in ("raw_last_assistant", "render_assistant_messages_raw")
if options.get(key)
}
assert render(messages, generation=True, **serialization) == prompt
full = render(messages + [assistant], **serialization)
full_text = tok.decode(full, skip_special_tokens=False)
if case.oracle == "harmony" and not calls:
from openai_harmony import (
Conversation,
HarmonyEncodingName,
Message,
Role,
RenderConversationConfig,
load_harmony_encoding,
)
encoder = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
history = _harmony_messages(
messages,
tools=tools,
reasoning_effort=options.get("reasoning_effort", "medium"),
conversation_start_date=options.get("conversation_start_date"),
)
history += [
Message.from_role_and_content(Role.ASSISTANT, REASONING).with_channel(
"analysis"
),
Message.from_role_and_content(Role.ASSISTANT, ANSWER).with_channel("final"),
]
full = encoder.render_conversation_for_training(
Conversation.from_messages(history),
RenderConversationConfig(auto_drop_analysis=False),
)
elif case.resolved_renderer == "deepseek-r1" and prompt_text.endswith("<think>\n"):
# R1's generation prompt opens thinking, but its history branch removes
# it. Restore the live reasoning segment before the template's answer.
prefill = "<think>\n"
assert prompt_text.endswith(prefill)
history_prefix = prompt_text[: -len(prefill)]
assert full_text.startswith(history_prefix)
full_text = (
prompt_text + REASONING + "</think>" + full_text[len(history_prefix) :]
)
full = tok.encode(full_text, add_special_tokens=False)
elif case.resolved_renderer == "gemma4" and prompt_text.endswith(
"<|channel>thought\n<channel|>"
):
prefill = "<|channel>thought\n<channel|>"
assert prompt_text.endswith(prefill)
history_prefix = prompt_text[: -len(prefill)]
assert full_text.startswith(history_prefix)
full_text = prompt_text + full_text[len(history_prefix) :]
full = tok.encode(full_text, add_special_tokens=False)
elif (
case.resolved_renderer == "laguna-s-2.1"
and disabled
and options.get("preserve_thinking")
):
# History preserves an empty opener; generation supplies only the close.
history_prefix = prompt_text.removesuffix("</think>") + "<think></think>"
assert full_text.startswith(history_prefix)
full_text = prompt_text + full_text[len(history_prefix) :]
full = tok.encode(full_text, add_special_tokens=False)
if (
case.resolved_renderer in {"kimi-k2.5", "kimi-k2.6"}
and messages[-1]["role"] == "tool"
):
# Kimi's final-answer history branch strips the preceding tool turn's
# reasoning as well as the final turn's reasoning. Extract only the
# last assistant body and preserve the actual sampling prompt.
header = "<|im_assistant|>assistant<|im_middle|>"
body = tok.decode(full).rsplit(header, 1)[1]
if not disabled:
assert prompt_text.endswith(header + "<think>")
assert body.startswith("<think></think>")
body = REASONING + body[len("<think>") :]
else:
assert prompt_text.endswith(header + "</think>")
assert body.startswith("</think>")
body = body[len("</think>") :]
full = tok.encode(prompt_text + body, add_special_tokens=False)
assert full[: len(prompt)] == prompt, (
"Reference history is not a live continuation; add an explicit oracle adapter",
case.model,
kwargs,
prompt_text[-200:],
tok.decode(full)[-300:],
)
completion = full[len(prompt) :]
# Expectations come from the reference, never from parse_response. Some
# non-reasoning templates intentionally ignore reasoning_content inputs.
reasoning = REASONING if REASONING in tok.decode(completion) else ""
return prompt, completion, reasoning
+668
View File
@@ -0,0 +1,668 @@
"""Reference-oracle registry for the shared test barrage.
The oracle is selected from the resolved renderer, not assumed to be Hugging
Face ``apply_chat_template``. Most checkpoints currently route to that adapter,
DeepSeek V4 routes to its shipped Python-encoder contract, and GPT-OSS routes to
Harmony. ``render_reference`` is the single invocation path for all three.
The compact DSV4 implementation below is deliberately test-side and independent
of ``renderers.deepseek_v4``. It mirrors the public chat/tool branches of the
official encoder needed by the shared barrage; the official repository fixtures
remain covered separately in ``test_deepseek_v4.py``.
"""
from __future__ import annotations
import copy
import json
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
from types import MappingProxyType
from typing import Any, Protocol
from renderers.base import MODEL_RENDERER_MAP
DEEPSEEK_V4_MODEL = "deepseek-ai/DeepSeek-V4-Flash-0731"
class OracleRenderer(Protocol):
"""Common callable contract implemented by every reference oracle."""
def __call__(
self,
tokenizer: Any,
messages: list[dict[str, Any]],
**kwargs: Any,
) -> list[int]: ...
@dataclass(frozen=True)
class ReferenceOracle:
"""Named adapter that renders one conversation to reference token IDs."""
name: str
render: OracleRenderer
_BOS = "<|begin▁of▁sentence|>"
_EOS = "<|end▁of▁sentence|>"
_USER = "<|User|>"
_ASSISTANT = "<|Assistant|>"
_LATEST_REMINDER = "<|latest_reminder|>"
_THINK_START = "<think>"
_THINK_END = "</think>"
_DSML = "|DSML|"
_TASK_TOKENS = {
"action": "<|action|>",
"query": "<|query|>",
"authority": "<|authority|>",
"domain": "<|domain|>",
"title": "<|title|>",
"read_url": "<|read_url|>",
}
_REASONING_EFFORT_PROMPTS = {
"low": "",
"high": (
"Reasoning Effort: Absolute maximum with no shortcuts permitted.\n"
"You MUST be very thorough in your thinking and comprehensively "
"decompose the problem to resolve the root cause, rigorously "
"stress-testing your logic against all potential paths, edge cases, "
"and adversarial scenarios.\n"
"Explicitly write out your entire deliberation process, documenting "
"every intermediate step, considered alternative, and rejected "
"hypothesis to ensure absolutely no assumption is left unchecked.\n\n"
),
"max": (
"Reasoning Effort: Beyond maximum — exhaustive, relentless, and "
"uncompromising.\n"
"You MUST reason with the utmost depth and rigor, leaving absolutely "
"nothing to chance: exhaustively decompose the problem into its most "
"fundamental components, trace every causal chain to its root, and "
"resolve the underlying cause rather than any surface symptom.\n"
"Do not stop reasoning until you have independently verified the "
"solution from multiple angles and are certain that no assumption "
"remains unchecked and no error remains undiscovered.\n\n"
),
}
_TOOLS_TEMPLATE = """## Tools
You have access to a set of tools to help answer the user's question. You can invoke tools by writing a "<{dsml}tool_calls>" block like the following:
<{dsml}tool_calls>
<{dsml}invoke name="$TOOL_NAME">
<{dsml}parameter name="$PARAMETER_NAME" string="true|false">$PARAMETER_VALUE</{dsml}parameter>
...
</{dsml}invoke>
<{dsml}invoke name="$TOOL_NAME2">
...
</{dsml}invoke>
</{dsml}tool_calls>
String parameters should be specified as is and set `string="true"`. For all other types (numbers, booleans, arrays, objects), pass the value in JSON format and set `string="false"`.
If thinking_mode is enabled (triggered by {think_start}), you MUST output your complete reasoning inside {think_start}...{think_end} BEFORE any tool calls or final response.
Otherwise, output directly after {think_end} with tool calls or final response.
### Available Tool Schemas
{tool_schemas}
You MUST strictly follow the above defined tool name and parameter schemas to invoke tool calls.
"""
def _json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False)
def _function(spec: Mapping[str, Any]) -> Mapping[str, Any]:
function = spec.get("function")
return function if isinstance(function, Mapping) else spec
def _text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, str):
return value
if not isinstance(value, list):
return str(value)
return "\n\n".join(
str(part.get("text", ""))
for part in value
if isinstance(part, Mapping) and part.get("type") == "text"
)
def _render_tools(tools: list[dict[str, Any]]) -> str:
return _TOOLS_TEMPLATE.format(
dsml=_DSML,
think_start=_THINK_START,
think_end=_THINK_END,
tool_schemas="\n".join(_json(dict(_function(tool))) for tool in tools),
)
def _render_tool_call(tool_call: Mapping[str, Any]) -> str:
function = _function(tool_call)
raw_arguments = function.get("arguments", {})
if isinstance(raw_arguments, str):
try:
arguments = json.loads(raw_arguments)
except (json.JSONDecodeError, TypeError):
arguments = {"arguments": raw_arguments}
elif isinstance(raw_arguments, Mapping):
# Renderer inputs allow decoded dictionaries even though the OpenAI
# wire format normally carries a JSON string.
arguments = dict(raw_arguments)
else:
arguments = {"arguments": raw_arguments}
parameters = []
for key, value in arguments.items():
is_string = isinstance(value, str)
encoded = value if is_string else _json(value)
parameters.append(
f'<{_DSML}parameter name="{key}" '
f'string="{str(is_string).lower()}">{encoded}'
f"</{_DSML}parameter>"
)
return (
f'<{_DSML}invoke name="{function.get("name")}">\n'
+ "\n".join(parameters)
+ f"\n</{_DSML}invoke>"
)
def _merge_tool_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
merged: list[dict[str, Any]] = []
for original in messages:
message = copy.deepcopy(original)
role = message.get("role")
if role == "tool":
block = {
"type": "tool_result",
"tool_use_id": message.get("tool_call_id", ""),
"content": message.get("content", ""),
}
if (
merged
and merged[-1].get("role") == "user"
and "content_blocks" in merged[-1]
):
merged[-1]["content_blocks"].append(block)
else:
merged.append({"role": "user", "content_blocks": [block]})
elif role == "user":
block = {"type": "text", "text": _text(message.get("content"))}
if (
merged
and merged[-1].get("role") == "user"
and "content_blocks" in merged[-1]
and merged[-1].get("task") is None
):
merged[-1]["content_blocks"].append(block)
else:
message["content"] = block["text"]
message["content_blocks"] = [block]
merged.append(message)
else:
merged.append(message)
call_order: dict[str, int] = {}
for message in merged:
if message.get("role") == "assistant" and message.get("tool_calls"):
call_order = {}
for index, tool_call in enumerate(message["tool_calls"]):
function = _function(tool_call)
call_id = tool_call.get("id") or function.get("id")
if call_id:
call_order[str(call_id)] = index
elif message.get("role") == "user" and message.get("content_blocks"):
blocks = message["content_blocks"]
results = [b for b in blocks if b.get("type") == "tool_result"]
if len(results) > 1 and call_order:
results.sort(
key=lambda block: call_order.get(block.get("tool_use_id", ""), 0)
)
ordered = iter(results)
message["content_blocks"] = [
next(ordered) if block.get("type") == "tool_result" else block
for block in blocks
]
return merged
def _drop_historical_thinking(
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
last_user = max(
(
index
for index, message in enumerate(messages)
if message.get("role") in {"user", "developer"}
),
default=-1,
)
kept = []
for index, original in enumerate(messages):
role = original.get("role")
if role in {"user", "system", "tool", "latest_reminder"} or index >= last_user:
kept.append(original)
elif role == "assistant":
message = copy.copy(original)
message.pop("reasoning_content", None)
kept.append(message)
return kept
def _render_deepseek_v4_reference(
messages: list[dict[str, Any]],
*,
tools: list[dict[str, Any]] | None,
add_generation_prompt: bool,
enable_thinking: bool,
drop_thinking: bool,
reasoning_effort: str,
) -> str:
messages = copy.deepcopy(messages)
if tools:
target: dict[str, Any] | None = next(
(m for m in messages if m.get("role") == "developer"),
None,
)
if target is None:
target = next(
(m for m in messages if m.get("role") == "system"),
None,
)
if target is None:
target = {"role": "system", "content": ""}
messages.insert(0, target)
target["tools"] = copy.deepcopy(tools)
messages = _merge_tool_messages(messages)
effective_drop = drop_thinking and not any(m.get("tools") for m in messages)
if enable_thinking and effective_drop:
messages = _drop_historical_thinking(messages)
last_user = max(
(
index
for index, message in enumerate(messages)
if message.get("role") in {"user", "developer"}
),
default=-1,
)
prompt = _BOS
if enable_thinking:
prompt += _REASONING_EFFORT_PROMPTS[reasoning_effort]
for index, message in enumerate(messages):
role = message.get("role")
content = message.get("content")
if role == "system":
prompt += _text(content)
if message.get("tools"):
prompt += "\n\n" + _render_tools(message["tools"])
if message.get("response_format") is not None:
prompt += (
"\n\n## Response Format:\n\n"
"You MUST strictly adhere to the following schema to reply:\n"
+ _json(message["response_format"])
)
elif role == "developer":
prompt += _USER + _text(content)
if message.get("tools"):
prompt += "\n\n" + _render_tools(message["tools"])
if message.get("response_format") is not None:
prompt += (
"\n\n## Response Format:\n\n"
"You MUST strictly adhere to the following schema to reply:\n"
+ _json(message["response_format"])
)
elif role == "user":
prompt += _USER
rendered_blocks = []
for block in message.get("content_blocks") or []:
if block.get("type") == "text":
rendered_blocks.append(_text(block.get("text")))
elif block.get("type") == "tool_result":
rendered_blocks.append(
f"<tool_result>{_text(block.get('content'))}</tool_result>"
)
prompt += "\n\n".join(rendered_blocks)
elif role == "latest_reminder":
prompt += _LATEST_REMINDER + _text(content)
elif role == "assistant":
previous_has_task = (
index > 0 and messages[index - 1].get("task") is not None
)
keep_reasoning = (
enable_thinking
and not previous_has_task
and (not effective_drop or index > last_user)
)
if keep_reasoning:
prompt += str(message.get("reasoning_content") or "") + _THINK_END
prompt += _text(content)
tool_calls = message.get("tool_calls") or []
if tool_calls:
prompt += (
f"\n\n<{_DSML}tool_calls>\n"
+ "\n".join(_render_tool_call(call) for call in tool_calls)
+ f"\n</{_DSML}tool_calls>"
)
if not message.get("wo_eos", False):
prompt += _EOS
else:
raise ValueError(f"Unsupported DeepSeek V4 reference role: {role!r}")
next_role = (
messages[index + 1].get("role") if index + 1 < len(messages) else None
)
if next_role is not None and next_role not in {
"assistant",
"latest_reminder",
}:
continue
task = message.get("task")
if task is not None:
if task not in _TASK_TOKENS:
raise ValueError(f"Invalid DeepSeek V4 reference task: {task!r}")
if task != "action":
prompt += _TASK_TOKENS[task]
else:
prompt += _ASSISTANT
prompt += _THINK_START if enable_thinking else _THINK_END
prompt += _TASK_TOKENS[task]
continue
if (next_role is None and not add_generation_prompt) or role not in {
"user",
"developer",
}:
continue
prompt += _ASSISTANT
if enable_thinking and (not effective_drop or index >= last_user):
prompt += _THINK_START
else:
prompt += _THINK_END
return prompt
def _render_hugging_face(
tokenizer: Any,
messages: list[dict[str, Any]],
**kwargs: Any,
) -> list[int]:
result = tokenizer.apply_chat_template(
messages,
tokenize=True,
return_dict=False,
**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)
def _render_deepseek_v4(
tokenizer: Any,
messages: list[dict[str, Any]],
**kwargs: Any,
) -> list[int]:
kwargs = dict(kwargs)
text = _render_deepseek_v4_reference(
messages,
tools=kwargs.pop("tools", None),
add_generation_prompt=kwargs.pop("add_generation_prompt"),
enable_thinking=kwargs.pop("enable_thinking", False),
drop_thinking=kwargs.pop("drop_thinking", True),
reasoning_effort=kwargs.pop("reasoning_effort", "low"),
)
if kwargs:
raise TypeError(f"Unsupported DeepSeek V4 reference kwargs: {sorted(kwargs)}")
return list(tokenizer.encode(text, add_special_tokens=False))
def _harmony_tool_description(tool: Mapping[str, Any]):
from openai_harmony import ToolDescription
fn = tool.get("function", tool)
return ToolDescription.new(
name=fn.get("name", ""),
description=fn.get("description", ""),
parameters=fn.get("parameters") or {},
)
def _harmony_messages(
messages: list[dict[str, Any]],
*,
tools: list[dict[str, Any]] | None,
reasoning_effort: str,
conversation_start_date: str | None,
):
from openai_harmony import (
Author,
DeveloperContent,
Message,
ReasoningEffort,
Role,
SystemContent,
)
effort = {
"low": ReasoningEffort.LOW,
"medium": ReasoningEffort.MEDIUM,
"high": ReasoningEffort.HIGH,
}[reasoning_effort]
system = (
SystemContent.new()
.with_reasoning_effort(effort)
.with_conversation_start_date(
conversation_start_date or datetime.now().strftime("%Y-%m-%d")
)
)
out = [Message.from_role_and_content(Role.SYSTEM, system)]
first_system = next(
(
index
for index, message in enumerate(messages)
if message["role"] == "system"
),
None,
)
if first_system is not None or tools:
developer = DeveloperContent.new()
if first_system is not None and messages[first_system].get("content"):
developer = developer.with_instructions(messages[first_system]["content"])
if tools:
developer = developer.with_function_tools(
[_harmony_tool_description(tool) for tool in tools]
)
out.append(Message.from_role_and_content(Role.DEVELOPER, developer))
for index, message in enumerate(messages):
if index == first_system:
continue
role = message["role"]
content = message.get("content") or ""
if role == "user":
out.append(Message.from_role_and_content(Role.USER, content))
continue
if role in {"system", "developer"}:
developer = DeveloperContent.new().with_instructions(content)
out.append(Message.from_role_and_content(Role.DEVELOPER, developer))
continue
if role == "tool":
name = message.get("name") or "unknown"
if not name.startswith("functions."):
name = f"functions.{name}"
tool_message = Message.from_author_and_content(
Author.new(Role.TOOL, name), content
)
out.append(
tool_message.with_recipient("assistant").with_channel("commentary")
)
continue
if role != "assistant":
raise AssertionError(f"Harmony oracle does not support role={role!r}")
tool_calls = message.get("tool_calls") or []
later_final = any(
later.get("role") == "assistant"
and not later.get("tool_calls")
and bool(later.get("content"))
for later in messages[index + 1 :]
)
reasoning = message.get("reasoning_content")
if reasoning and tool_calls and not later_final:
out.append(
Message.from_role_and_content(Role.ASSISTANT, reasoning).with_channel(
"analysis"
)
)
if content:
out.append(
Message.from_role_and_content(Role.ASSISTANT, content).with_channel(
"final"
)
)
for tool_call in tool_calls:
fn = tool_call.get("function", tool_call)
arguments = fn.get("arguments", {})
if not isinstance(arguments, str):
arguments = json.dumps(arguments, ensure_ascii=False)
name = fn.get("name", "")
if not name.startswith("functions."):
name = f"functions.{name}"
out.append(
Message.from_role_and_content(Role.ASSISTANT, arguments)
.with_channel("commentary")
.with_recipient(name)
)
if not content and not tool_calls and not reasoning:
out.append(
Message.from_role_and_content(Role.ASSISTANT, "").with_channel("final")
)
return out
def _render_harmony(
tokenizer: Any,
messages: list[dict[str, Any]],
**kwargs: Any,
) -> list[int]:
del tokenizer
from openai_harmony import (
Conversation,
HarmonyEncodingName,
Role,
load_harmony_encoding,
)
kwargs = dict(kwargs)
add_generation_prompt = kwargs.pop("add_generation_prompt")
tools = kwargs.pop("tools", None)
reasoning_effort = kwargs.pop("reasoning_effort", "medium")
conversation_start_date = kwargs.pop("conversation_start_date", None)
if kwargs:
raise TypeError(f"Unsupported Harmony reference kwargs: {sorted(kwargs)}")
encoder = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
conversation = Conversation.from_messages(
_harmony_messages(
messages,
tools=tools,
reasoning_effort=reasoning_effort,
conversation_start_date=conversation_start_date,
)
)
if add_generation_prompt:
prompt = encoder.render_conversation_for_completion(
conversation, next_turn_role=Role.ASSISTANT
)
return prompt + encoder.encode(
"<|channel|>analysis<|message|>", allowed_special="all"
)
return encoder.render_conversation_for_training(conversation)
REFERENCE_ORACLES: Mapping[str, ReferenceOracle] = MappingProxyType(
{
"hugging-face": ReferenceOracle("hugging-face", _render_hugging_face),
"deepseek-v4": ReferenceOracle("deepseek-v4", _render_deepseek_v4),
"harmony": ReferenceOracle("harmony", _render_harmony),
}
)
"""All available reference implementations, keyed by stable oracle name."""
DEFAULT_REFERENCE_ORACLE = "hugging-face"
RENDERER_ORACLE_ROUTES: Mapping[str, str] = MappingProxyType(
{
"deepseek-v4": "deepseek-v4",
"gpt-oss": "harmony",
}
)
"""Renderer families whose canonical reference is not a Jinja template."""
def reference_oracle_for_renderer(renderer_name: str) -> str:
"""Return the oracle registered for a resolved renderer name."""
return RENDERER_ORACLE_ROUTES.get(renderer_name, DEFAULT_REFERENCE_ORACLE)
def reference_oracle_for_model(model_name: str) -> str:
"""Resolve a canonical model through the production renderer routing map."""
renderer_name = MODEL_RENDERER_MAP.get(model_name, "default")
return reference_oracle_for_renderer(renderer_name)
def render_reference(
tokenizer: Any,
messages: list[dict[str, Any]],
*,
oracle: str | None = None,
**kwargs: Any,
) -> list[int]:
"""Render ``messages`` through one resolved reference-oracle adapter."""
oracle_name = oracle or reference_oracle_for_model(
getattr(tokenizer, "name_or_path", "")
)
try:
adapter = REFERENCE_ORACLES[oracle_name]
except KeyError as error:
raise ValueError(
f"Unknown reference oracle {oracle_name!r}; "
f"registered oracles: {sorted(REFERENCE_ORACLES)}"
) from error
kwargs.setdefault("add_generation_prompt", False)
return adapter.render(tokenizer, messages, **kwargs)
__all__ = [
"DEFAULT_REFERENCE_ORACLE",
"DEEPSEEK_V4_MODEL",
"REFERENCE_ORACLES",
"RENDERER_ORACLE_ROUTES",
"ReferenceOracle",
"reference_oracle_for_model",
"reference_oracle_for_renderer",
"render_reference",
]
+48
View File
@@ -0,0 +1,48 @@
"""Replay only the inference HTTP boundary; exercise the real client stack."""
import json
import httpx
from openai import AsyncOpenAI
def replay_client(completions, requests):
"""Replay sampled IDs, logprobs, and masks without mocking renderer code."""
responses = iter(completions)
def respond(request):
assert request.url.path == "/inference/v1/generate"
body = json.loads(request.content)
requests.append(body)
ids, finish_reason = next(responses)
return httpx.Response(
200,
json={
"request_id": f"replay-{len(requests)}",
"choices": [
{
"token_ids": ids,
"finish_reason": finish_reason,
"logprobs": {
"content": [
{"token": f"token_id:{tid}", "logprob": -0.25}
for tid in ids
]
},
"sampling_mask": [[tid] for tid in ids],
}
],
},
)
return AsyncOpenAI(
api_key="replay",
base_url="http://replay/v1",
http_client=httpx.AsyncClient(transport=httpx.MockTransport(respond)),
)
def assert_evidence(result, ids):
assert result["completion_ids"] == ids
assert result["completion_logprobs"] == [-0.25] * len(ids)
assert result["sampling_mask"] == [[tid] for tid in ids]
+32 -17
View File
@@ -19,24 +19,9 @@ from __future__ import annotations
from functools import lru_cache
import pytest
from parity import models_for
# (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"),
("zai-org/GLM-5.1", "auto"),
("THUDM/GLM-4.5-Air", "auto"),
("MiniMaxAI/MiniMax-M2.5", "auto"),
("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"),
]
_BRIDGE_MODELS = [(case.model, case.renderer) for case in models_for("bridge")]
@lru_cache(maxsize=None)
@@ -109,6 +94,13 @@ def _simulate_prior_turn(renderer, assistant=None):
full_with_assistant = renderer.render_ids(
prior + assistant, add_generation_prompt=False
)
# Some templates render a content-only historical turn without the live
# prompt's reasoning prefill (Harmony also changes analysis to final).
# Slice only at an actual shared boundary; cutting by length alone silently
# removes content or a reasoning closer and manufactures a malformed turn.
if full_with_assistant[: len(prev_prompt)] != prev_prompt:
prev_prompt = renderer.render_ids(prior, add_generation_prompt=False)
assert full_with_assistant[: len(prev_prompt)] == prev_prompt
prev_completion = list(full_with_assistant[len(prev_prompt) :])
# Trim past any trailing scaffolding the template emits AFTER the
@@ -213,6 +205,24 @@ def test_bridge_extension_includes_new_message_text(
)
def test_qwen3_renders_openai_text_content_parts(br_renderer, br_tokenizer, br_model):
"""Text content lists must not become an empty user turn."""
if br_model not in {"Qwen/Qwen3-8B", "Qwen/Qwen3-4B"}:
pytest.skip(f"{br_model}: not a Qwen3 text renderer")
text = "CONTENT_LIST_SENTINEL_XYZ"
string_ids = br_renderer.render_ids(
[{"role": "user", "content": text}], add_generation_prompt=True
)
list_ids = br_renderer.render_ids(
[{"role": "user", "content": [{"type": "text", "text": text}]}],
add_generation_prompt=True,
)
assert list_ids == string_ids
assert text in br_tokenizer.decode(list_ids, skip_special_tokens=False)
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
@@ -344,3 +354,8 @@ def test_bridge_keeps_thinking_when_history_kwarg_disables_truncation():
assert bridged is not None, (
f"{model}: bridge must keep verbatim when the template keeps all thinking"
)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_load.cache_clear()
+121 -14
View File
@@ -3,8 +3,11 @@
Runs against every (model, renderer) pair.
"""
import pytest
from renderers import build_training_sample, build_trajectory_step
from renderers.base import PlaceholderRange, _build_mm_token_type_ids
from tests.reference_rendering import render_reference
def test_build_mm_token_type_ids_marks_ranges():
@@ -18,23 +21,23 @@ def test_build_mm_token_type_ids_marks_ranges():
def _expected(tokenizer, messages, **kwargs):
# Match the Renderer Protocol's default for add_generation_prompt
# (False); some tokenizers default it to True in their config
# (e.g. Kimi) which would otherwise flip the parity check on the flag
# alone. Callers wanting the gen prompt still pass it through.
kwargs.setdefault("add_generation_prompt", False)
result = tokenizer.apply_chat_template(
messages, tokenize=True, return_dict=False, **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)
return render_reference(tokenizer, messages, **kwargs)
def test_build_training_sample_ids_match(model_name, tokenizer, renderer):
"""Token IDs must match apply_chat_template."""
"""Token IDs must match the model-aware reference renderer."""
if (
model_name
in {
"google/gemma-4-26B-A4B-it",
"google/gemma-4-31B-it",
}
and not renderer.config.enable_thinking
):
pytest.skip(
"Gemma 4 26B/31B deliberately keeps the disabled-thinking prefill "
"on assistant history; stability is covered separately"
)
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
@@ -92,6 +95,110 @@ def test_build_training_sample_ensures_final_stop(model_name, tokenizer, rendere
assert sample.token_ids == baseline.token_ids
@pytest.mark.parametrize(
"selection",
[[0] * 6, [1] * 6, [0, 1, 0, 0, 1, 0], [False, False, True, True, False, True]],
)
@pytest.mark.parametrize("ensure_final_stop", [False, True])
@pytest.mark.parametrize("body_roles", [None, {"user", "tool"}])
@pytest.mark.parametrize("tool_turn", [False, True])
def test_build_training_sample_message_loss_mask(
model_name, tokenizer, renderer, selection, ensure_final_stop, body_roles, tool_turn
):
"""Select arbitrary messages without changing tokens or enabling new targets."""
messages = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Earlier answer."},
{"role": "user", "content": "Next question"},
{"role": "assistant", "content": "New answer."},
{"role": "user", "content": "One more question"},
{"role": "assistant", "content": "Final answer."},
]
if tool_turn:
messages[1]["tool_calls"] = [
{
"id": "call_1",
"type": "function",
"function": {"name": "lookup", "arguments": '{"q":"x"}'},
}
]
messages[2] = {
"role": "tool",
"content": "Lookup result",
"tool_call_id": "call_1",
"name": "lookup",
}
rendered = renderer.render(messages)
kwargs = {
"ensure_final_stop": ensure_final_stop,
"content_sft_roles": body_roles,
}
if not rendered.sampled_mask:
kwargs["role_to_mask"] = lambda m: m["role"] == "assistant"
baseline = build_training_sample(renderer, messages, **kwargs)
sample = build_training_sample(
renderer, messages, message_loss_mask=selection, **kwargs
)
assert sample.token_ids == baseline.token_ids
assert len(sample.loss_mask) == len(sample.token_ids)
for k, index in enumerate(rendered.message_indices):
if index < 0 or not selection[index]:
assert not sample.loss_mask[k]
else:
assert sample.loss_mask[k] == baseline.loss_mask[k]
# A synthesized stop is controlled by the final assistant's flag.
assert sample.loss_mask[len(rendered.token_ids) :] == [
keep and bool(selection[-1])
for keep in baseline.loss_mask[len(rendered.token_ids) :]
]
disabled = build_training_sample(
renderer,
messages,
message_loss_mask=selection,
role_to_mask=lambda _: False,
ensure_final_stop=ensure_final_stop,
)
assert not any(disabled.loss_mask)
trained = tokenizer.decode(
[t for t, keep in zip(sample.token_ids[1:], sample.loss_mask[1:]) if keep]
)
for index, text in [
(1, "Earlier answer."),
(3, "New answer."),
(5, "Final answer."),
]:
assert (text in trained) == bool(selection[index])
# Closing tokens are assistant output, including markers emitted while
# rendering the next user/tool message. Its body keeps its own owner.
for index, sampled in zip(rendered.message_indices, rendered.sampled_mask):
if sampled:
assert index >= 0 and messages[index]["role"] == "assistant"
@pytest.mark.parametrize(
"selection",
[
[],
[1],
[1] * 5,
[1, 0, 2, 1],
[1, -1, 0, 1],
[1, "0", 0, 1],
[1, 1.0, 0, 1],
[1, None, 0, 1],
],
)
def test_build_training_sample_rejects_invalid_message_loss_mask(selection):
messages = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Answer"},
{"role": "tool", "content": "Result"},
{"role": "assistant", "content": "Final"},
]
with pytest.raises(ValueError, match="message_loss_mask"):
build_training_sample(None, messages, message_loss_mask=selection)
def test_build_trajectory_step_reconstructs_full(model_name, tokenizer, renderer):
"""prompt_ids + completion_ids must equal the full rendered sequence."""
prompt = [
+375 -24
View File
@@ -5,6 +5,7 @@ import json
import httpx
import numpy as np
import pytest
from renderers import MalformedGenerateResponseError
from renderers.base import (
ParsedResponse,
ParsedToolCall,
@@ -40,7 +41,7 @@ class _FakeRenderer:
return [99]
def parse_response(
self, completion_ids: list[int], *, tools=None
self, completion_ids: list[int], *, tools=None, prompt_ids=None
) -> ParsedResponse:
assert completion_ids == [7, 8]
# Stores tools so tests can assert the client plumbed them through.
@@ -67,42 +68,71 @@ class _FakeClient:
def __init__(self):
self.calls = []
self.base_url = "http://fake-host:8000/v1"
self.usage = None
routed_experts = np.array([[[1]], [[2]]], dtype=np.uint8)
self.choice = {
"index": 0,
"token_ids": [7, 8],
"logprobs": {
"content": [
{"token": "token_id:7", "logprob": -0.1},
{"token": "token_id:8", "logprob": -0.2},
]
},
"finish_reason": "stop",
"routed_experts": {
"data": base64.b64encode(routed_experts.tobytes()).decode("ascii"),
"shape": list(routed_experts.shape),
},
}
async def post(self, path, *, cast_to=dict, body=None, options=None):
self.calls.append(
{"path": path, "cast_to": cast_to, "body": body, "options": options}
)
routed_experts = np.array([[[1]], [[2]]], dtype=np.uint8)
payload = {
"request_id": "gen-test",
"choices": [
{
"index": 0,
"token_ids": [7, 8],
"logprobs": {
"content": [
{"token": "token_id:7", "logprob": -0.1},
{"token": "token_id:8", "logprob": -0.2},
]
},
"finish_reason": "stop",
"routed_experts": {
"data": base64.b64encode(routed_experts.tobytes()).decode(
"ascii"
),
"shape": list(routed_experts.shape),
},
}
],
"choices": [self.choice],
}
if self.usage is not None:
payload["usage"] = self.usage
if body and body.get("content_parts"):
payload["prompt_token_ids"] = [1, 2, 2, 3]
payload["mm_placeholders"] = {"image": [{"offset": 1, "length": 2}]}
return httpx.Response(
200,
content=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
)
def test_generate_builds_request_body_and_parses_response():
def _run_generate(client, renderer=None):
return asyncio.run(
generate(
client=client,
renderer=renderer or _FakeRenderer(),
messages=[{"role": "user", "content": "hi"}],
model="test-model",
tools=[{"type": "function", "function": {"name": "echo"}}],
)
)
@pytest.mark.parametrize(
"usage",
[
None,
{
"prompt_tokens": 3,
"completion_tokens": 2,
"total_tokens": 5,
"prompt_tokens_details": {"cached_tokens": 2},
"completion_tokens_details": {"reasoning_tokens": 1},
},
],
)
def test_generate_builds_request_body_and_parses_response(usage):
client = _FakeClient()
client.usage = usage
renderer = _FakeRenderer()
result = asyncio.run(
@@ -154,6 +184,7 @@ def test_generate_builds_request_body_and_parses_response():
assert result["routed_experts"]["data"].tobytes() == base64.b64encode(b"\x01\x02")
assert result["multi_modal_data"] is None
assert result["request_id"] == "gen-test"
assert result["usage"] == usage
# 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.
@@ -172,11 +203,144 @@ def test_generate_builds_request_body_and_parses_response():
assert tc.status == ToolCallParseStatus.OK
def test_generate_process_multimodal_false_sends_content_parts():
class DeferredMultimodalRenderer(_FakeRenderer):
supports_process_multimodal = True
def render(
self,
messages,
*,
tools=None,
add_generation_prompt=False,
process_multimodal=True,
):
assert process_multimodal is False
return RenderedTokens(token_ids=[1, 2, 3])
client = _FakeClient()
image_url = "data:image/png;base64,aW1hZ2U="
result = asyncio.run(
generate(
client=client,
renderer=DeferredMultimodalRenderer(),
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "look"},
{"type": "image_url", "image_url": {"url": image_url}},
],
}
],
model="test-model",
process_multimodal=False,
)
)
body = client.calls[0]["body"]
assert body["content_parts"] == [{"type": "image_url", "url": image_url}]
assert body["return_token_ids"] is True
assert "features" not in body
assert result["renderer_prompt_ids"] == [1, 2, 3]
assert result["prompt_ids"] == [1, 2, 2, 3]
assert result["mm_placeholders"] == {"image": [{"offset": 1, "length": 2}]}
def test_generate_rejects_missing_completion_logprobs_before_parsing():
client = _FakeClient()
client.choice.pop("logprobs")
renderer = _FakeRenderer()
with pytest.raises(
MalformedGenerateResponseError,
match=r"choice\.logprobs must be an object",
):
_run_generate(client, renderer)
assert not hasattr(renderer, "_last_parse_tools")
@pytest.mark.parametrize(
"entry",
[
{"token": "token_id:7"},
{"token": "token_id:7", "logprob": None},
{"token": "token_id:7", "logprob": "-0.1"},
{"token": "token_id:7", "logprob": True},
],
ids=["missing", "null", "string", "boolean"],
)
def test_generate_rejects_non_numeric_completion_logprobs(entry):
client = _FakeClient()
client.choice["logprobs"]["content"][0] = entry
with pytest.raises(
MalformedGenerateResponseError,
match=r"content\[0\]\.logprob must be a number",
):
_run_generate(client)
def test_generate_rejects_completion_logprob_count_mismatch():
client = _FakeClient()
client.choice["logprobs"]["content"] = [{"token": "token_id:7", "logprob": -0.1}]
with pytest.raises(
MalformedGenerateResponseError,
match=r"completion token count \(2\) does not match logprob count \(1\)",
):
_run_generate(client)
@pytest.mark.parametrize("logprob", [float("nan"), float("inf"), float("-inf")])
def test_generate_rejects_non_finite_completion_logprobs(logprob):
client = _FakeClient()
client.choice["logprobs"]["content"][0]["logprob"] = logprob
with pytest.raises(
MalformedGenerateResponseError,
match=r"content\[0\]\.logprob must be finite",
):
_run_generate(client)
def test_generate_rejects_vllm_missing_logprob_sentinel():
client = _FakeClient()
client.choice["logprobs"]["content"][0]["logprob"] = -9999.0
with pytest.raises(
MalformedGenerateResponseError,
match=r"does not contain sampling evidence",
):
_run_generate(client)
def test_generate_rejects_logprob_token_id_mismatch():
client = _FakeClient()
client.choice["logprobs"]["content"][0]["token"] = "token_id:8"
with pytest.raises(
MalformedGenerateResponseError,
match=r"content\[0\]\.token must be 'token_id:7'",
):
_run_generate(client)
def test_generate_preserves_zero_completion_logprob():
client = _FakeClient()
client.choice["logprobs"]["content"][0]["logprob"] = 0.0
result = _run_generate(client)
assert result["completion_logprobs"] == [0.0, -0.2]
class _MalformedToolRenderer(_FakeRenderer):
"""Returns only a malformed tool-call attempt — finish_reason must stay "stop"."""
def parse_response(
self, completion_ids: list[int], *, tools=None
self, completion_ids: list[int], *, tools=None, prompt_ids=None
) -> ParsedResponse:
return ParsedResponse(
content="",
@@ -285,8 +449,10 @@ def test_generate_threads_prompt_attribution_through_prebuilt_prompt_path():
[
("Qwen/Qwen3-VL-4B-Instruct", "renderers.qwen3_vl:Qwen3VLRenderer"),
("Qwen/Qwen3.5-2B", "renderers.qwen35:Qwen35Renderer"),
("Qwen/Qwen3.8-27B", "renderers.qwen38:Qwen38Renderer"),
("Qwen/Qwen3.8-Flash-Next", "renderers.qwen38:Qwen38Renderer"),
],
ids=["qwen3_vl", "qwen35"],
ids=["qwen3_vl", "qwen35", "qwen38", "qwen38_flash_next"],
)
def test_generate_serializes_multimodal_features_for_qwen_vl_family(
model_id, renderer_class_path
@@ -371,6 +537,164 @@ def test_generate_serializes_multimodal_features_for_qwen_vl_family(
assert isinstance(item, str) and len(item) > 0
def test_generate_serializes_multimodal_features_for_gemma4():
"""Gemma 4's HF image positions are translated to vLLM's field name."""
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.gemma4 import Gemma4Renderer
renderer = Gemma4Renderer(load_tokenizer("google/gemma-4-31B-it"))
mm_data = MultiModalData(
mm_hashes={"image": ["aaa", "bbb"]},
mm_placeholders={
"image": [
PlaceholderRange(offset=5, length=2),
PlaceholderRange(offset=12, length=2),
]
},
mm_items={
"image": [
{
"pixel_values": _torch.zeros(1, 4, 8),
"image_position_ids": _torch.zeros(1, 4, 2, dtype=_torch.int64),
},
{
"pixel_values": _torch.zeros(1, 4, 8),
"image_position_ids": _torch.zeros(1, 4, 2, dtype=_torch.int64),
},
]
},
)
client = _FakeClient()
asyncio.run(
generate(
client=client,
renderer=renderer,
messages=[],
model="gemma4",
prompt_ids=list(range(20)),
multi_modal_data=mm_data,
sampling_params={"max_tokens": 4},
)
)
features = client.calls[0]["body"]["features"]
assert features["mm_hashes"] == {"image": ["aaa", "bbb"]}
assert features["mm_placeholders"] == {
"image": [
{"offset": 5, "length": 2},
{"offset": 12, "length": 2},
]
}
assert len(features["kwargs_data"]["image"]) == 2
assert all(
isinstance(item, str) and item for item in features["kwargs_data"]["image"]
)
def test_generate_serializes_nemotron_dynamic_image_features():
pytest.importorskip("torch")
pytest.importorskip("vllm", reason="vllm needed for features serialization")
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import (
decode_mm_kwargs_item,
)
from vllm.model_executor.models.nano_nemotron_vl import NemotronH_Nano_VL_V2
from vllm.multimodal.inputs import MultiModalKwargsItems
from renderers.base import MultiModalData, PlaceholderRange
from renderers.nemotron3 import Nemotron35Renderer
class _FakeNemotronRenderer(Nemotron35Renderer):
def get_stop_token_ids(self):
return [99]
def parse_response(self, completion_ids, *, tools=None, prompt_ids=None):
return ParsedResponse(content="done")
renderer = object.__new__(_FakeNemotronRenderer)
mm_data = MultiModalData(
mm_hashes={"image": ["wide", "tall"]},
mm_placeholders={
"image": [
PlaceholderRange(offset=2, length=6),
PlaceholderRange(offset=10, length=6),
]
},
mm_items={
"image": [
{
"pixel_values": np.zeros((1, 3, 32, 48), dtype=np.float32),
"imgs_sizes": np.array([[32, 48]], dtype=np.int64),
"num_tokens": [6],
"num_patches": [1],
},
{
"pixel_values": np.ones((1, 3, 48, 32), dtype=np.float32),
"imgs_sizes": np.array([[48, 32]], dtype=np.int64),
"num_tokens": [6],
"num_patches": [1],
},
]
},
)
client = _FakeClient()
asyncio.run(
generate(
client=client,
renderer=renderer,
messages=[],
model="nemotron35-super",
prompt_ids=list(range(20)),
multi_modal_data=mm_data,
sampling_params={"max_tokens": 4},
)
)
features = client.calls[0]["body"]["features"]
assert features["mm_hashes"] == {"image": ["wide", "tall"]}
assert features["mm_placeholders"] == {
"image": [{"offset": 2, "length": 6}, {"offset": 10, "length": 6}]
}
decoded_items = [
decode_mm_kwargs_item(item) for item in features["kwargs_data"]["image"]
]
decoded = [item.get_data() for item in decoded_items]
assert [tuple(item["pixel_values_flat"].shape) for item in decoded] == [
(3, 32, 48),
(3, 48, 32),
]
assert [tuple(item["imgs_sizes"]) for item in decoded] == [
(32, 48),
(48, 32),
]
assert [int(item["num_tokens_per_image"]) for item in decoded] == [6, 6]
assert all("image_num_patches" not in item for item in decoded)
kwargs = MultiModalKwargsItems({"image": decoded_items}).get_data()
model = object.__new__(NemotronH_Nano_VL_V2)
model.dynamic_resolution = True
model.patch_size = 16
image_input = model._parse_and_validate_image_input(**kwargs)
assert image_input is not None
assert tuple(image_input["pixel_values_flat"].shape) == (
1,
12,
3 * 16 * 16,
)
assert [tuple(size) for size in image_input["imgs_sizes"]] == [
(32, 48),
(48, 32),
]
assert image_input["num_tokens_per_image"] == [6, 6]
# ---------------------------------------------------------------------------
# Prompt overflow handling.
# ---------------------------------------------------------------------------
@@ -502,3 +826,30 @@ def test_generate_caches_max_prompt_len_lookup_failure():
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
@pytest.mark.parametrize(
"finish,reasoning_complete", [("stop", False), ("length", True), ("stop", None)]
)
def test_generate_forwards_reasoning_state_without_classifying_acceptance(
finish,
reasoning_complete,
):
class ContextRenderer(_FakeRenderer):
def parse_response(self, completion_ids, *, tools=None, prompt_ids=None):
assert prompt_ids == [1, 2, 3]
assert completion_ids == [7, 8]
return ParsedResponse(
content="",
reasoning_content="reasoning",
reasoning_complete=reasoning_complete,
)
client = _FakeClient()
client.choice["finish_reason"] = finish
result = _run_generate(client, ContextRenderer())
assert result["reasoning_complete"] is reasoning_complete
assert result["finish_reason"] == finish
assert result["completion_ids"] == [7, 8]
assert result["completion_logprobs"] == [-0.1, -0.2]
assert result["content"] == ""
+194
View File
@@ -0,0 +1,194 @@
"""Custom renderers loaded from local files or importable modules."""
from __future__ import annotations
import pickle
import textwrap
import pytest
from pydantic import TypeAdapter, ValidationError
from renderers import (
CustomRendererConfig,
GLM53RendererConfig,
RendererConfig,
create_renderer,
custom_renderer_config,
load_custom_renderer,
merge_chat_template_kwargs,
template_field_names,
)
TOY_SOURCE = textwrap.dedent(
"""
from typing import Literal
from renderers.configs import BaseRendererConfig
class ToyRendererConfig(BaseRendererConfig):
name: Literal["toy"] = "toy"
effort: int = 1
cache_size: int = 8
_template_fields = frozenset({"effort"})
_internal_fields = frozenset({"cache_size"})
class ToyRenderer:
config_class = ToyRendererConfig
def __init__(self, tokenizer, config):
self.tokenizer = tokenizer
self.config = config
class NoConfigRenderer:
pass
"""
)
@pytest.fixture
def toy_file(tmp_path):
path = tmp_path / "toy_renderer.py"
path.write_text(TOY_SOURCE)
return path
def import_path(path, name="ToyRenderer"):
return f"{path}:{name}"
def test_custom_fields_validate_through_the_renderer_config(toy_file):
config = CustomRendererConfig(import_path=import_path(toy_file), effort=3)
assert custom_renderer_config(config).effort == 3
assert custom_renderer_config(config).name == "toy"
with pytest.raises(ValidationError):
CustomRendererConfig(import_path=import_path(toy_file), unknown=1)
def test_shared_renderer_fields_reach_the_renderer_config(toy_file):
config = CustomRendererConfig(
import_path=import_path(toy_file), thinking_retention="all"
)
assert custom_renderer_config(config).thinking_retention == "all"
def test_discriminated_union_parses_renderer_configs(toy_file):
config = TypeAdapter(RendererConfig).validate_python(
{"name": "custom", "import_path": import_path(toy_file), "effort": 2}
)
assert isinstance(config, CustomRendererConfig)
assert custom_renderer_config(config).effort == 2
def test_create_renderer_builds_the_custom_renderer_with_its_own_config(toy_file):
tokenizer = object()
renderer = create_renderer(
tokenizer, CustomRendererConfig(import_path=import_path(toy_file), effort=4)
)
assert type(renderer).__name__ == "ToyRenderer"
assert renderer.tokenizer is tokenizer
assert type(renderer.config).__name__ == "ToyRendererConfig"
assert renderer.config.effort == 4
def test_chat_template_kwargs_use_the_custom_renderer_allowlist(toy_file):
config = CustomRendererConfig(import_path=import_path(toy_file))
renderer = create_renderer(object(), config, chat_template_kwargs={"effort": 5})
assert renderer.config.effort == 5
with pytest.raises(ValueError, match="cache_size"):
create_renderer(object(), config, chat_template_kwargs={"cache_size": 2})
def test_module_import_paths_import_by_name(toy_file, monkeypatch):
monkeypatch.syspath_prepend(str(toy_file.parent))
config = CustomRendererConfig(import_path="toy_renderer.ToyRenderer", effort=6)
assert create_renderer(object(), config).config.effort == 6
def test_file_import_paths_load_once_per_process(toy_file):
assert load_custom_renderer(import_path(toy_file)) is load_custom_renderer(
import_path(toy_file)
)
def test_invalid_import_paths_fail_clearly(toy_file, tmp_path):
with pytest.raises(ValueError, match="must look like"):
CustomRendererConfig(import_path=str(toy_file))
with pytest.raises(ValueError, match="has no attribute"):
CustomRendererConfig(import_path=import_path(toy_file, "Missing"))
with pytest.raises(TypeError, match="config_class"):
CustomRendererConfig(import_path=import_path(toy_file, "NoConfigRenderer"))
with pytest.raises(FileNotFoundError):
CustomRendererConfig(import_path=f"{tmp_path / 'missing.py'}:ToyRenderer")
def test_renderer_configs_pickle_and_key_caches(toy_file):
low = CustomRendererConfig(import_path=import_path(toy_file), effort=1)
high = CustomRendererConfig(import_path=import_path(toy_file), effort=9)
assert pickle.loads(pickle.dumps(high)) == high
cache = {low: "low", high: "high"}
assert (
cache[CustomRendererConfig(import_path=import_path(toy_file), effort=9)]
== "high"
)
assert low != high
def test_public_helpers_resolve_custom_template_fields(toy_file):
config = CustomRendererConfig(import_path=import_path(toy_file))
assert template_field_names(config) == frozenset({"effort"})
merged = merge_chat_template_kwargs(config, {"effort": 7})
assert isinstance(merged, CustomRendererConfig)
assert custom_renderer_config(merged).effort == 7
with pytest.raises(ValueError, match="cache_size"):
merge_chat_template_kwargs(config, {"cache_size": 1})
GLM53_NO_THINKING_SOURCE = textwrap.dedent(
"""
from typing import Literal
from renderers.configs import GLM53RendererConfig
from renderers.glm5 import GLM53Renderer
class NoThinkingGLM53Config(GLM53RendererConfig):
name: Literal["glm-5.3-no-thinking"] = "glm-5.3-no-thinking"
class NoThinkingGLM53Renderer(GLM53Renderer):
config_class = NoThinkingGLM53Config
def _emit_generation_prompt(self, emit_special) -> None:
emit_special(self._assistant, -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)
"""
)
def test_readme_example_prefills_the_think_block(tmp_path):
from renderers.base import load_tokenizer
path = tmp_path / "glm53_no_thinking.py"
path.write_text(GLM53_NO_THINKING_SOURCE)
tokenizer = load_tokenizer("zai-org/GLM-5.3-BF16")
messages = [{"role": "user", "content": "What is 2 + 2?"}]
custom = create_renderer(
tokenizer,
CustomRendererConfig(
import_path=import_path(path, "NoThinkingGLM53Renderer"),
clear_thinking=True,
),
)
builtin = create_renderer(tokenizer, GLM53RendererConfig(clear_thinking=True))
ids = custom.render_ids(messages, add_generation_prompt=True)
builtin_ids = builtin.render_ids(messages, add_generation_prompt=True)
assert tokenizer.decode(ids[-3:]) == "<|assistant|><think></think>"
assert tokenizer.decode(builtin_ids[-2:]) == "<|assistant|><think>"
assert ids[:-1] == builtin_ids
assert custom.config.clear_thinking is True
+9 -70
View File
@@ -1,15 +1,12 @@
"""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.
General byte parity lives in ``test_parity.py``. 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,
@@ -30,70 +27,6 @@ def _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()
@@ -150,3 +83,9 @@ def test_v3_emits_content_verbatim_ignoring_reasoning():
assert got == expected
assert "should be ignored" not in tok.decode(got)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_r1.cache_clear()
_v3.cache_clear()
+598
View File
@@ -0,0 +1,598 @@
"""DeepSeek V4 Flash 0731 reference-encoder and DSML coverage."""
from __future__ import annotations
from functools import lru_cache
import pytest
from pydantic import TypeAdapter, ValidationError
from renderers import (
DeepSeekV4Renderer,
DeepSeekV4RendererConfig,
RendererConfig,
ToolCallParseStatus,
create_renderer,
)
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
from tests.reference_rendering import render_reference
MODEL = "deepseek-ai/DeepSeek-V4-Flash-0731"
BOS = "<|begin▁of▁sentence|>"
EOS = "<|end▁of▁sentence|>"
USER = "<|User|>"
ASSISTANT = "<|Assistant|>"
TOOLS = [
{
"type": "function",
"function": {
"name": "weather",
"description": "Get weather",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"days": {"type": "integer"},
},
"required": ["city"],
},
},
}
]
@lru_cache(maxsize=1)
def _tokenizer():
return load_tokenizer(MODEL)
def _renderer(**config_kwargs):
return DeepSeekV4Renderer(
_tokenizer(),
DeepSeekV4RendererConfig(**config_kwargs),
)
def _decode(renderer, messages, **kwargs):
return _tokenizer().decode(
renderer.render_ids(messages, **kwargs),
skip_special_tokens=False,
)
def test_registration_and_native_defaults():
tokenizer = _tokenizer()
renderer = create_renderer(tokenizer)
assert tokenizer.chat_template is None
assert MODEL_RENDERER_MAP[MODEL] == "deepseek-v4"
assert isinstance(renderer, DeepSeekV4Renderer)
assert renderer.config.enable_thinking is False
assert renderer.config.drop_thinking is True
assert renderer.config.reasoning_effort == "low"
assert renderer.effective_thinking_retention == "all"
def test_config_discriminator_and_template_kwarg_contract():
parsed = TypeAdapter(RendererConfig).validate_python(
{
"name": "deepseek-v4",
"enable_thinking": True,
"drop_thinking": False,
"reasoning_effort": "max",
}
)
assert isinstance(parsed, DeepSeekV4RendererConfig)
assert parsed.reasoning_effort == "max"
with pytest.raises(ValidationError):
DeepSeekV4RendererConfig(
drop_thinking=False,
thinking_retention="tool_cycle",
)
def test_chat_mode_generation_prompt_matches_reference_encoder():
messages = [
{"role": "system", "content": "Be concise."},
{"role": "user", "content": "Hello"},
]
assert _decode(_renderer(), messages, add_generation_prompt=True) == (
f"{BOS}Be concise.{USER}Hello{ASSISTANT}</think>"
)
assert _decode(_renderer(), messages) == f"{BOS}Be concise.{USER}Hello"
def test_thinking_mode_drops_only_historical_reasoning_without_tools():
messages = [
{"role": "system", "content": "Be concise."},
{"role": "user", "content": "First"},
{
"role": "assistant",
"reasoning_content": "old secret",
"content": "First answer",
},
{"role": "user", "content": "Second"},
{
"role": "assistant",
"reasoning_content": "current thought",
"content": "Second answer",
},
]
assert _decode(_renderer(enable_thinking=True), messages) == (
f"{BOS}Be concise."
f"{USER}First{ASSISTANT}</think>First answer{EOS}"
f"{USER}Second{ASSISTANT}<think>current thought</think>Second answer{EOS}"
)
def test_tools_preserve_reasoning_and_use_dsml_wire_format():
messages = [
{"role": "system", "content": "Be helpful."},
{"role": "user", "content": "Weather?"},
{
"role": "assistant",
"reasoning_content": "I should call the tool.",
"content": "",
"tool_calls": [
{
"id": "call-1",
"type": "function",
"function": {
"name": "weather",
"arguments": {"city": "Berlin", "days": 2},
},
}
],
},
{"role": "tool", "tool_call_id": "call-1", "content": '{"sun":true}'},
]
text = _decode(
_renderer(enable_thinking=True),
messages,
tools=TOOLS,
add_generation_prompt=True,
)
assert text.startswith(f"{BOS}Be helpful.\n\n## Tools\n")
assert f"{USER}Weather?{ASSISTANT}<think>I should call the tool.</think>" in text
assert '<|DSML|invoke name="weather">' in text
assert (
'<|DSML|parameter name="city" string="true">Berlin</|DSML|parameter>'
) in text
assert (
'<|DSML|parameter name="days" string="false">2</|DSML|parameter>'
) in text
assert (
f'{EOS}{USER}<tool_result>{{"sun":true}}</tool_result>{ASSISTANT}<think>'
) in text
def test_parallel_tool_results_are_sorted_by_call_order():
messages = [
{"role": "user", "content": "Run both"},
{
"role": "assistant",
"tool_calls": [
{"id": "a", "function": {"name": "first", "arguments": {}}},
{"id": "b", "function": {"name": "second", "arguments": {}}},
],
},
{"role": "tool", "tool_call_id": "b", "content": "second result"},
{"role": "tool", "tool_call_id": "a", "content": "first result"},
]
text = _decode(_renderer(), messages)
assert text.index("first result") < text.index("second result")
@pytest.mark.parametrize("prefilled", [False, True])
@pytest.mark.parametrize("enabled", [False, True])
def test_dsml_roundtrip_preserves_string_and_json_argument_types(prefilled, enabled):
renderer = _renderer(enable_thinking=True)
messages = [
{"role": "user", "content": "Weather?"},
{
"role": "assistant",
"reasoning_content": "Use weather.",
"content": "checking",
"tool_calls": [
{
"function": {
"name": "weather",
"arguments": {
"city": "true",
"days": 2,
"flags": [True, False],
},
}
}
],
},
]
rendered = renderer.render_ids(messages)
assistant_id = _tokenizer().encode(ASSISTANT, add_special_tokens=False)[0]
completion_start = rendered.index(assistant_id) + 1 + int(prefilled)
completion = rendered[completion_start:]
parsed = _renderer(enable_thinking=enabled).parse_response(
completion, prompt_ids=rendered[:completion_start]
)
assert parsed.reasoning_content == "Use weather."
assert parsed.content == "checking\n\n"
assert len(parsed.tool_calls) == 1
call = parsed.tool_calls[0]
assert call.status == ToolCallParseStatus.OK
assert call.name == "weather"
assert call.arguments == {
"city": "true",
"days": 2,
"flags": [True, False],
}
assert call.token_span is not None
start, end = call.token_span
assert (
_tokenizer()
.decode(completion[start:end], skip_special_tokens=False)
.rstrip("\n")
== call.raw
)
@pytest.mark.parametrize(
"arguments, decoded_type",
[
("[]", "list"),
('"value"', "str"),
("1", "int"),
("null", "NoneType"),
],
)
def test_json_nonobject_tool_arguments_raise_like_reference_encoder(
arguments,
decoded_type,
):
messages = [
{"role": "user", "content": "Call it"},
{
"role": "assistant",
"tool_calls": [
{
"function": {
"name": "weather",
"arguments": arguments,
}
}
],
},
]
with pytest.raises(AttributeError) as reference_error:
render_reference(_tokenizer(), messages)
with pytest.raises(AttributeError) as renderer_error:
_renderer().render_ids(messages)
expected = f"'{decoded_type}' object has no attribute 'items'"
assert str(reference_error.value) == expected
assert str(renderer_error.value) == expected
def test_reasoning_effort_prefix_is_after_bos_and_thinking_only():
messages = [{"role": "user", "content": "Think"}]
high = _decode(
_renderer(enable_thinking=True, reasoning_effort="high"),
messages,
add_generation_prompt=True,
)
chat = _decode(
_renderer(enable_thinking=False, reasoning_effort="high"),
messages,
add_generation_prompt=True,
)
assert high.startswith(f"{BOS}Reasoning Effort: Absolute maximum")
assert chat == f"{BOS}{USER}Think{ASSISTANT}</think>"
def test_reference_encoder_drops_stale_developer_messages_without_tools():
messages = [
{"role": "developer", "content": "stale internal query"},
{"role": "assistant", "reasoning_content": "old", "content": "old answer"},
{"role": "user", "content": "current public query"},
]
text = _decode(
_renderer(enable_thinking=True),
messages,
add_generation_prompt=True,
)
assert "stale internal query" not in text
assert text == (f"{BOS}old answer{EOS}{USER}current public query{ASSISTANT}<think>")
def test_quick_task_token_renders_without_normal_generation_prompt():
messages = [{"role": "user", "content": "Search?", "task": "action"}]
renderer = _renderer()
assert renderer.render_ids(messages) == render_reference(
_tokenizer(),
messages,
)
assert _decode(renderer, messages) == (
f"{BOS}{USER}Search?{ASSISTANT}</think><|action|>"
)
def test_action_task_assistant_suppresses_thinking_like_reference_encoder():
messages = [
{"role": "user", "content": "Classify", "task": "action"},
{
"role": "assistant",
"reasoning_content": "must not render",
"content": "result",
},
]
renderer = _renderer(enable_thinking=True)
rendered = renderer.render_ids(messages)
assert rendered == render_reference(
_tokenizer(),
messages,
enable_thinking=True,
)
assert _tokenizer().decode(rendered, skip_special_tokens=False) == (
f"{BOS}{USER}Classify{ASSISTANT}<think><|action|>result{EOS}"
)
def test_historical_action_task_keeps_reference_encoders_unclosed_think():
messages = [
{"role": "user", "content": "Classify", "task": "action"},
{"role": "assistant", "content": "result"},
{"role": "user", "content": "Continue"},
]
renderer = _renderer(enable_thinking=True)
rendered = renderer.render_ids(messages, add_generation_prompt=True)
assert rendered == render_reference(
_tokenizer(),
messages,
add_generation_prompt=True,
enable_thinking=True,
)
assert _tokenizer().decode(rendered, skip_special_tokens=False) == (
f"{BOS}{USER}Classify{ASSISTANT}<think><|action|>result{EOS}"
f"{USER}Continue{ASSISTANT}<think>"
)
def test_task_before_nonassistant_does_not_emit_task_token():
messages = [
{"role": "user", "content": "First", "task": "query"},
{"role": "user", "content": "Second"},
]
renderer = _renderer(enable_thinking=True)
rendered = renderer.render_ids(messages, add_generation_prompt=True)
assert rendered == render_reference(
_tokenizer(),
messages,
add_generation_prompt=True,
enable_thinking=True,
)
assert "<|query|>" not in _tokenizer().decode(
rendered,
skip_special_tokens=False,
)
def test_tool_result_merges_into_tasked_user_like_reference_encoder():
messages = [
{"role": "user", "content": "Classify", "task": "action"},
{"role": "tool", "tool_call_id": "call-1", "content": "done"},
{
"role": "assistant",
"reasoning_content": "must not render",
"content": "result",
},
]
renderer = _renderer(enable_thinking=True)
rendered = renderer.render_ids(messages)
assert rendered == render_reference(
_tokenizer(),
messages,
enable_thinking=True,
)
assert _tokenizer().decode(rendered, skip_special_tokens=False) == (
f"{BOS}{USER}Classify\n\n<tool_result>done</tool_result>"
f"{ASSISTANT}<think><|action|>result{EOS}"
)
def test_merged_followup_task_is_dropped_like_reference_encoder():
messages = [
{"role": "tool", "tool_call_id": "call-1", "content": "done"},
{"role": "user", "content": "Classify", "task": "action"},
]
renderer = _renderer(enable_thinking=True)
rendered = renderer.render_ids(messages, add_generation_prompt=True)
assert rendered == render_reference(
_tokenizer(),
messages,
add_generation_prompt=True,
enable_thinking=True,
)
text = _tokenizer().decode(rendered, skip_special_tokens=False)
assert "<|action|>" not in text
assert text.endswith(f"{ASSISTANT}<think>")
@pytest.mark.parametrize("prefix", ["", "\n", "\n\n"])
def test_dsml_parser_accepts_vllm_tool_opener_without_template_newlines(prefix):
text = (
f"{prefix}<|DSML|tool_calls>\n"
'<|DSML|invoke name="weather">\n\n</|DSML|invoke>\n'
"</|DSML|tool_calls>"
)
parsed = _renderer().parse_response(
_tokenizer().encode(text, add_special_tokens=False)
)
assert parsed.content == ""
assert [(call.name, call.arguments, call.status) for call in parsed.tool_calls] == [
("weather", {}, ToolCallParseStatus.OK)
]
def test_rendered_masks_keep_dsml_sampled_and_tool_wrappers_scaffolded():
renderer = _renderer(enable_thinking=True)
messages = [
{"role": "user", "content": "Call it"},
{
"role": "assistant",
"reasoning_content": "calling",
"tool_calls": [
{"id": "x", "function": {"name": "weather", "arguments": {}}}
],
},
{"role": "tool", "tool_call_id": "x", "content": "sunny"},
]
rendered = renderer.render(messages, tools=TOOLS)
assert len(rendered.token_ids) == len(rendered.message_indices)
assert len(rendered.token_ids) == len(rendered.sampled_mask)
assert len(rendered.token_ids) == len(rendered.is_content)
assert rendered.tokens_by_role(sampled_only=True)["assistant"] > 0
assert rendered.tokens_by_role(sampled_only=True)["tool"] == 0
tool_content = rendered.content_mask_for_roles({"tool"})
assert (
_tokenizer().decode(
[token for token, keep in zip(rendered.token_ids, tool_content) if keep],
skip_special_tokens=False,
)
== "sunny"
)
def test_bridge_extends_a_single_tool_result_exactly():
renderer = _renderer(enable_thinking=True)
first_messages = [
{"role": "user", "content": "Call it"},
{
"role": "assistant",
"reasoning_content": "calling",
"tool_calls": [
{
"id": "x",
"function": {"name": "weather", "arguments": {"city": "Rome"}},
}
],
},
]
full_messages = first_messages + [
{"role": "tool", "tool_call_id": "x", "content": "sunny"}
]
prompt = renderer.render_ids(
first_messages[:1],
tools=TOOLS,
add_generation_prompt=True,
)
full_first = renderer.render_ids(first_messages, tools=TOOLS)
completion = full_first[len(prompt) :]
bridged = renderer.bridge_to_next_turn(
prompt,
completion,
full_messages[-1:],
tools=TOOLS,
)
assert bridged is not None
assert bridged.token_ids == renderer.render_ids(
full_messages,
tools=TOOLS,
add_generation_prompt=True,
)
def test_bridge_declines_at_developer_query_boundary_when_dropping_thinking():
renderer = _renderer(enable_thinking=True)
prior_messages = [{"role": "user", "content": "Q1"}]
answer = {
"role": "assistant",
"reasoning_content": "old reasoning",
"content": "A1",
}
new_messages = [{"role": "developer", "content": "Q2"}]
prompt = renderer.render_ids(prior_messages, add_generation_prompt=True)
completed = renderer.render_ids([*prior_messages, answer])
completion = completed[len(prompt) :]
assert renderer.bridge_to_next_turn(prompt, completion, new_messages) is None
full_messages = [*prior_messages, answer, *new_messages]
assert renderer.render_ids(
full_messages,
add_generation_prompt=True,
) == render_reference(
_tokenizer(),
full_messages,
enable_thinking=True,
add_generation_prompt=True,
)
def test_bridge_extends_developer_query_when_preserving_all_thinking():
renderer = _renderer(enable_thinking=True, drop_thinking=False)
prior_messages = [{"role": "user", "content": "Q1"}]
answer = {
"role": "assistant",
"reasoning_content": "retained reasoning",
"content": "A1",
}
new_messages = [{"role": "developer", "content": "Q2"}]
prompt = renderer.render_ids(prior_messages, add_generation_prompt=True)
completed = renderer.render_ids([*prior_messages, answer])
completion = completed[len(prompt) :]
bridged = renderer.bridge_to_next_turn(prompt, completion, new_messages)
assert bridged is not None
assert bridged.token_ids == renderer.render_ids(
[*prior_messages, answer, *new_messages],
add_generation_prompt=True,
)
def test_dsml_reasoning_markers_in_arguments_remain_argument_text():
text = (
'\n\n<|DSML|tool_calls>\n<|DSML|invoke name="weather">\n'
'<|DSML|parameter name="city" string="true"><think>example</think></|DSML|parameter>\n'
"</|DSML|invoke>\n</|DSML|tool_calls>"
)
parsed = _renderer().parse_response(
_tokenizer().encode(text, add_special_tokens=False), prompt_ids=[]
)
assert parsed.reasoning_content is None
assert parsed.content == ""
assert parsed.reasoning_complete is True
assert len(parsed.tool_calls) == 1
assert parsed.tool_calls[0].status == ToolCallParseStatus.OK
assert parsed.tool_calls[0].arguments == {"city": "<think>example</think>"}
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_tokenizer.cache_clear()
+232
View File
@@ -0,0 +1,232 @@
"""Sampled-token stability with thinking disabled.
For the affected Qwen and Gemma 4 variants, the generation prompt prefills an
empty thinking wrapper, so that wrapper is part of every sampled turn's token
stream. In an agentic rollout the conversation keeps growing (tool responses,
budget / prune-reminder user messages, ...) and may be re-rendered from
messages. The upstream Jinja templates strip the wrapper from assistant
history, so a re-render would diverge token-for-token from the stream the model
actually sampled — forking any token-identity comparison on byte-identical
messages.
These tests pin the renderer-side guarantee that fixes this: with thinking
disabled, historical assistant turns without ``reasoning_content`` re-emit
the exact gen-prompt wrapper, so the tokens a turn was sampled with are a
prefix of every later re-render of the grown conversation, and the bridge
and a full re-render agree.
This is a deliberate, documented deviation from ``apply_chat_template`` —
see the carve-out in ``test_parity.py`` and the module
docstrings of the affected renderers.
"""
from __future__ import annotations
from functools import lru_cache
from parity import models_for
from renderers import create_renderer
from renderers.base import load_tokenizer
from renderers.configs import _config_class_for
# One representative model per affected renderer family, each with
# thinking explicitly disabled.
_MODELS = [
(
case.model,
_config_class_for(case.resolved_renderer)(enable_thinking=False),
)
for case in models_for("disabled-thinking")
]
_EMPTY_WRAPPERS = {
"google/gemma-4-26B-A4B-it": "<|channel>thought\n<channel|>",
}
@lru_cache(maxsize=None)
def _load(model_name: str):
return load_tokenizer(model_name)
def pytest_generate_tests(metafunc):
if "dt_model" in metafunc.fixturenames:
metafunc.parametrize("dt_model,dt_config", _MODELS, ids=[m for m, _ in _MODELS])
def test_sampled_stream_is_prefix_of_rerender(dt_model, dt_config):
"""The rollout invariant: every generation prompt (which ends with the
prefilled empty wrapper) stays a byte prefix of all later re-renders of
the grown conversation — even after new real user queries arrive."""
tok = _load(dt_model)
renderer = create_renderer(tok, dt_config)
convo: list[dict] = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "What is the capital of France?"},
]
prev = renderer.render_ids(convo, add_generation_prompt=True)
steps = [
(
{"role": "assistant", "content": "Paris."},
{"role": "user", "content": "You are running low on budget."},
),
(
{"role": "assistant", "content": "Understood."},
{"role": "user", "content": "Submit your final answer now."},
),
]
for assistant, user in steps:
convo += [assistant, user]
cur = renderer.render_ids(convo, add_generation_prompt=True)
assert cur[: len(prev)] == prev, (
f"{dt_model}: re-render after appending {assistant['content']!r} "
"diverged from the earlier generation prompt — historical turn "
"lost its prefilled empty think wrapper"
)
prev = cur
def test_wrapper_reemitted_on_historical_turn(dt_model, dt_config):
"""A historical assistant turn (before the last real user query, no
reasoning_content) renders with the exact empty wrapper bytes the
generation prompt prefilled."""
tok = _load(dt_model)
renderer = create_renderer(tok, dt_config)
rendered = renderer.render(
[
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
{"role": "user", "content": "Now 3+3?"},
]
)
turn = [t for t, i in zip(rendered.token_ids, rendered.message_indices) if i == 1]
text = tok.decode(turn)
expected_wrapper = _EMPTY_WRAPPERS.get(dt_model, "<think>\n\n</think>\n\n")
assert expected_wrapper in text, (
f"{dt_model}: historical assistant turn rendered without the "
f"prefilled empty think wrapper: {text!r}"
)
def test_bridge_and_rerender_agree(dt_model, dt_config):
"""Extending a sampled turn via the bridge and re-rendering the same
conversation from messages must produce identical tokens — the property
whose violation shows up as token-level forks on byte-identical
trajectories."""
tok = _load(dt_model)
renderer = create_renderer(tok, dt_config)
msgs = [{"role": "user", "content": "What is the capital of France?"}]
prompt_ids = renderer.render_ids(msgs, add_generation_prompt=True)
# Simulate the sampled completion: content tokens then the stop token.
completion_ids = tok.encode("Paris.", add_special_tokens=False) + [
renderer.get_stop_token_ids()[0]
]
reminder = {"role": "user", "content": "You are running low on budget."}
bridged = renderer.bridge_to_next_turn(prompt_ids, completion_ids, [reminder])
assert bridged is not None, (
f"{dt_model}: bridge refused with thinking disabled (implied "
"thinking_retention='all' should allow it)"
)
rerender = renderer.render_ids(
msgs + [{"role": "assistant", "content": "Paris."}, reminder],
add_generation_prompt=True,
)
assert bridged.token_ids == rerender, (
f"{dt_model}: bridge-extended tokens and full re-render disagree:\n"
f"bridge: {tok.decode(bridged.token_ids)!r}\n"
f"rerender: {tok.decode(rerender)!r}"
)
def test_tool_cycle_rerender_stays_prefix_stable(dt_model, dt_config):
"""Tool-call turns (empty content, no reasoning) keep the prefilled
wrapper too. On qwen3 the template window additionally requires
``is_last or reasoning_content``, so without the deviation a mid-cycle
re-render would strip the wrapper from the tool-call turn even though
it sits after the last real user query."""
tok = _load(dt_model)
renderer = create_renderer(tok, dt_config)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
msgs: list[dict] = [{"role": "user", "content": "Weather in Paris?"}]
prev = renderer.render_ids(msgs, tools=tools, add_generation_prompt=True)
msgs += [
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
{"role": "tool", "content": '{"temp": 20}'},
]
cur = renderer.render_ids(msgs, tools=tools, add_generation_prompt=True)
assert cur[: len(prev)] == prev, (
f"{dt_model}: tool-call turn lost its prefilled empty think wrapper "
"on re-render"
)
msgs += [
{"role": "assistant", "content": "It is 20 degrees."},
{"role": "user", "content": "You are running low on budget."},
]
cur2 = renderer.render_ids(msgs, tools=tools, add_generation_prompt=True)
assert cur2[: len(cur)] == cur
def test_historical_reasoning_stays_template_faithful(dt_model, dt_config):
"""Scope guard: turns that carry ``reasoning_content`` were not sampled
under ``enable_thinking=False``, so they keep exact template parity —
the deviation fires only for the empty wrapper."""
tok = _load(dt_model)
renderer = create_renderer(tok, dt_config)
msgs = [
{"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",
},
]
ours = renderer.render_ids(msgs)
theirs = list(
tok.apply_chat_template(
msgs,
tokenize=True,
return_dict=False,
add_generation_prompt=False,
enable_thinking=False,
)
)
assert ours == theirs
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_load.cache_clear()
+474
View File
@@ -0,0 +1,474 @@
"""Focused coverage for Gemma 4's template variants and tool grammar."""
from functools import lru_cache
import pytest
from parity import models_for
from renderers import Gemma4Renderer, create_renderer
from renderers.base import MODEL_RENDERER_MAP, MULTIMODAL_MODELS, load_tokenizer
from renderers.configs import Gemma4RendererConfig
_MODELS = tuple(case.model for case in models_for("gemma-checkpoints"))
@lru_cache
def _gemma4():
tokenizer = load_tokenizer("google/gemma-4-31B-it")
return tokenizer, create_renderer(tokenizer)
def test_all_instruction_checkpoints_are_registered_as_image_renderers():
for model in _MODELS:
assert MODEL_RENDERER_MAP[model] == "gemma4"
assert MULTIMODAL_MODELS[model] == {"image"}
def test_disabled_thinking_prefill_tracks_template_revision(monkeypatch):
tokenizer, current_renderer = _gemma4()
messages = [{"role": "user", "content": "Hello"}]
current_text = tokenizer.decode(
current_renderer.render_ids(messages, add_generation_prompt=True),
skip_special_tokens=False,
)
assert current_text.endswith("<|channel>thought\n<channel|>")
# E2B/E4B use the otherwise-identical earlier template revision, which
# stops at the model role opener when thinking is disabled.
monkeypatch.setattr(tokenizer, "name_or_path", "google/gemma-4-E4B-it")
monkeypatch.setattr(tokenizer, "chat_template", "")
earlier_renderer = Gemma4Renderer(tokenizer)
earlier_text = tokenizer.decode(
earlier_renderer.render_ids(messages, add_generation_prompt=True),
skip_special_tokens=False,
)
assert earlier_text.endswith("<|turn>model\n")
def test_preserve_thinking_controls_derived_retention_and_rejects_conflicts():
tokenizer, _ = _gemma4()
preserved = Gemma4Renderer(
tokenizer,
Gemma4RendererConfig(enable_thinking=True, preserve_thinking=True),
)
assert preserved.effective_thinking_retention == "all"
with pytest.raises(ValueError, match="preserve_thinking=True implies"):
Gemma4RendererConfig(
preserve_thinking=True,
thinking_retention="tool_cycle",
)
@pytest.mark.parametrize(
"messages",
[
[{"role": "tool", "content": "orphan"}],
[
{"role": "assistant", "content": "No call."},
{"role": "tool", "content": "orphan"},
],
[
{
"role": "assistant",
"content": "",
"tool_responses": [{"name": "legacy", "response": "done"}],
},
{"role": "tool", "content": "still orphaned"},
],
],
)
def test_unconsumed_tool_messages_raise(messages):
tokenizer, renderer = _gemma4()
with pytest.raises(ValueError, match="Unconsumed tool message"):
renderer.render_ids(messages)
@pytest.mark.parametrize("enable_thinking", [False, True])
def test_tool_cycle_matches_canonical_template(enable_thinking):
tokenizer, _ = _gemma4()
renderer = Gemma4Renderer(
tokenizer, Gemma4RendererConfig(enable_thinking=enable_thinking)
)
tools = [
{
"type": "function",
"function": {
"name": "weather",
"description": "Look up the weather.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"],
},
},
}
]
messages = [
{"role": "user", "content": "Weather in Berlin?"},
{
"role": "assistant",
"reasoning_content": "I should call the weather tool."
if not enable_thinking
else None,
"content": "",
"tool_calls": [
{
"id": "call-1",
"type": "function",
"function": {
"name": "weather",
"arguments": {"city": "Berlin"},
},
}
],
},
{
"role": "tool",
"tool_call_id": "call-1",
"content": '{"temperature": 24, "unit": "C"}',
},
{
"role": "assistant",
"reasoning_content": "I can now answer." if not enable_thinking else None,
"content": "It is 24 C.",
},
]
expected = tokenizer.apply_chat_template(
messages,
tools=tools,
tokenize=True,
add_generation_prompt=False,
enable_thinking=enable_thinking,
return_dict=False,
)
assert renderer.render_ids(messages, tools=tools) == list(expected)
def test_disabled_thinking_post_tool_completion_matches_sampled_stream():
"""A post-tool assistant message continues the existing model turn.
The 26B/31B generation prompt prefills an empty thought channel before the
initial completion, but the disabled-thinking post-tool prompt does not
insert another one. A later full rerender must preserve that exact stream.
"""
tokenizer, _ = _gemma4()
renderer = Gemma4Renderer(tokenizer, Gemma4RendererConfig(enable_thinking=False))
tools = [
{
"type": "function",
"function": {
"name": "weather",
"description": "Look up the weather.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
user = {"role": "user", "content": "Weather in Berlin?"}
tool_call = {
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call-1",
"type": "function",
"function": {
"name": "weather",
"arguments": {"city": "Berlin"},
},
}
],
}
tool_response = {
"role": "tool",
"tool_call_id": "call-1",
"content": '{"temperature": 24}',
}
final = {"role": "assistant", "content": "It is 24 C."}
initial_prompt = renderer.render_ids(
[user], tools=tools, add_generation_prompt=True
)
tool_call_prompt = renderer.render_ids(
[user, tool_call], tools=tools, add_generation_prompt=True
)
assert tool_call_prompt[: len(initial_prompt)] == initial_prompt
tool_call_completion = tool_call_prompt[len(initial_prompt) :]
post_tool_prompt = renderer.bridge_to_next_turn(
initial_prompt,
tool_call_completion,
[tool_response],
tools=tools,
)
assert post_tool_prompt is not None
final_completion = tokenizer.encode(final["content"], add_special_tokens=False) + [
renderer.get_stop_token_ids()[0]
]
reminder = {"role": "user", "content": "Please summarize."}
extended_stream = renderer.bridge_to_next_turn(
post_tool_prompt.token_ids,
final_completion,
[reminder],
tools=tools,
)
assert extended_stream is not None
rerendered = renderer.render_ids(
[user, tool_call, tool_response, final, reminder],
tools=tools,
add_generation_prompt=True,
)
assert rerendered == extended_stream.token_ids
def test_parser_extracts_reasoning_and_multiple_typed_tool_calls():
tokenizer, renderer = _gemma4()
text = (
"<|channel>thought\nI need two lookups.\n<channel|>"
'<|tool_call>call:weather{city:<|"|>Berlin<|"|>,days:2}'
"<tool_call|>"
"<|tool_call>call:flags{enabled:true,values:[1,null]}<tool_call|>"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert parsed.reasoning_content == "I need two lookups."
assert parsed.content == ""
assert [(call.name, call.arguments) for call in parsed.tool_calls] == [
("weather", {"city": "Berlin", "days": 2}),
("flags", {"enabled": True, "values": [1, None]}),
]
def test_parser_recovers_prompt_opened_post_tool_reasoning():
tokenizer, _ = _gemma4()
renderer = Gemma4Renderer(tokenizer, Gemma4RendererConfig(enable_thinking=True))
tool_call = {
"id": "call-1",
"type": "function",
"function": {"name": "weather", "arguments": {"city": "Berlin"}},
}
messages = [
{"role": "user", "content": "Weather?"},
{"role": "assistant", "content": "", "tool_calls": [tool_call]},
{"role": "tool", "tool_call_id": "call-1", "content": "sunny"},
]
expected_prompt = tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
enable_thinking=True,
return_dict=False,
)
prompt = renderer.render_ids(messages, add_generation_prompt=True)
assert prompt == list(expected_prompt)
assert tokenizer.decode(prompt, skip_special_tokens=False).endswith(
"<|channel>thought\n"
)
completion = tokenizer.encode(
"Need synthesize.\n<channel|>It is sunny.<turn|>",
add_special_tokens=False,
)
parsed = renderer.parse_response(completion, prompt_ids=prompt)
assert parsed.reasoning_content == "Need synthesize."
assert parsed.content == "It is sunny."
assert parsed.tool_calls == []
# Initial-turn content without a channel closer remains ordinary content.
direct = renderer.parse_response(
tokenizer.encode("Direct answer.<turn|>", add_special_tokens=False)
)
assert direct.reasoning_content is None
assert direct.content == "Direct answer."
def _image_renderer():
"""A Gemma 4 renderer with a live ``Gemma4Processor``, or a skip."""
tokenizer, _ = _gemma4()
renderer = Gemma4Renderer(tokenizer)
try:
renderer._get_processor()
except (RuntimeError, OSError) as exc: # pragma: no cover - env dependent
pytest.skip(f"Gemma4Processor unavailable: {exc}")
return tokenizer, renderer
def _tiny_image():
from PIL import Image
return Image.new("RGB", (224, 224), color=(128, 192, 255))
@pytest.mark.parametrize("size", [(224, 224), (448, 224), (224, 448)])
def test_real_processor_keeps_one_batched_row_per_image(size):
"""Guard the ``MultiModalFieldConfig.batched('image')`` contract with
live Gemma4Processor output rather than synthetic tensor shapes."""
from PIL import Image
_, renderer = _image_renderer()
image = Image.new("RGB", size, color=(128, 192, 255))
rendered = renderer.render(
[{"role": "user", "content": [{"type": "image", "image": image}]}]
)
item = rendered.multi_modal_data.mm_items["image"][0]
placeholder = rendered.multi_modal_data.mm_placeholders["image"][0]
assert item["pixel_values"].shape[0] == 1
assert item["image_position_ids"].shape[0] == 1
assert item["pixel_values"].shape[1] == item["image_position_ids"].shape[1]
assert placeholder.length > 0
def test_schema_unified_image_parts_still_expand_image_tokens():
"""``Dataset.from_list`` unifies the Arrow schema across a content list,
so an image part round-tripped through a dataset carries ``text: None``
(and text parts carry ``image: None``). Dispatching on ``"text" in part``
before classifying media would route the image into the text branch,
emit nothing, and silently skip soft-token expansion."""
tokenizer, renderer = _image_renderer()
image = _tiny_image()
plain = [
{
"role": "user",
"content": [
{"type": "image", "image": image},
{"type": "text", "text": "What is this?"},
],
}
]
schema_unified = [
{
"role": "user",
"content": [
{"type": "image", "image": image, "text": None},
{"type": "text", "text": "What is this?", "image": None},
],
}
]
baseline = renderer.render(plain)
roundtripped = renderer.render(schema_unified)
image_id = tokenizer.convert_tokens_to_ids("<|image|>")
assert baseline.token_ids.count(image_id) > 0
assert roundtripped.token_ids == baseline.token_ids
assert (
roundtripped.multi_modal_data.mm_hashes == baseline.multi_modal_data.mm_hashes
)
assert (
roundtripped.multi_modal_data.mm_placeholders
== baseline.multi_modal_data.mm_placeholders
)
def test_schema_unified_tool_response_image_parts_survive():
"""Same hazard on the tool-response path, which also has to keep
accepting untyped text parts."""
tokenizer, renderer = _image_renderer()
image = _tiny_image()
messages = [
{"role": "user", "content": "Look it up."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call-1",
"type": "function",
"function": {"name": "screenshot", "arguments": {}},
}
],
},
{
"role": "tool",
"tool_call_id": "call-1",
"content": [
{"type": "image", "image": image, "text": None},
{"type": "text", "text": "captured", "image": None},
],
},
]
rendered = renderer.render(messages)
image_id = tokenizer.convert_tokens_to_ids("<|image|>")
assert rendered.token_ids.count(image_id) > 0
assert rendered.multi_modal_data.mm_hashes["image"]
assert "captured" in tokenizer.decode(rendered.token_ids, skip_special_tokens=False)
def test_untyped_text_parts_render_in_tool_responses():
tokenizer, _ = _gemma4()
renderer = Gemma4Renderer(tokenizer)
messages = [
{"role": "user", "content": "Check."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call-1",
"type": "function",
"function": {"name": "check", "arguments": {}},
}
],
},
{
"role": "tool",
"tool_call_id": "call-1",
"content": [{"text": "all good"}],
},
]
text = tokenizer.decode(renderer.render_ids(messages), skip_special_tokens=False)
assert "all good" in text
def test_system_content_lists_reject_media_parts():
"""The text-only guard must not be fooled by a schema-unified image
part's ``text: None`` key, which would drop the image silently."""
tokenizer, _ = _gemma4()
renderer = Gemma4Renderer(tokenizer)
messages = [
{
"role": "system",
"content": [{"type": "image", "image": object(), "text": None}],
},
{"role": "user", "content": "Hi"},
]
with pytest.raises(ValueError, match="text parts only"):
renderer.render_ids(messages)
def test_legacy_assistant_tool_responses_preserve_mask_contract():
tokenizer, _ = _gemma4()
renderer = Gemma4Renderer(tokenizer)
messages = [
{"role": "user", "content": "Check."},
{
"role": "assistant",
"content": "Done.",
"tool_responses": [{"name": "check", "response": {"ok": True}}],
},
]
rendered = renderer.render(messages)
for index, message_index in enumerate(rendered.message_indices):
if message_index == 1:
assert rendered.is_content[index] == rendered.sampled_mask[index]
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_gemma4.cache_clear()
+186
View File
@@ -0,0 +1,186 @@
"""GLM tool-name validation against the provided tools list.
vLLM 0.24 re-aliased ``glm45`` from the lenient ``Glm4MoeModelToolParser``
to ``Glm47MoeModelToolParser``, whose engine config sets
``validate_tool_names=True`` (``vllm/parser/glm47_moe.py``): a completed
``<tool_call>`` block whose name isn't in the request's tool list is
silently dropped — no tool call is emitted and the response reads as a
voluntary stop. Before this, unknown-name calls were surfaced to the
harness, which answered with a recoverable "unknown tool" error.
``parse_glm`` mirrors the ≥ 0.24 behavior when ``tools`` is passed:
unknown names get ``status=UNKNOWN_TOOL`` — never ``OK`` — so the
client-side stop→tool_calls finish-reason promotion
(``renderers/client.py``) agrees with what an OpenAI chat-completions
client sees from the engine, while the attempt itself stays visible for
verifier / RL-loss code. Without ``tools`` there is no validation, also
matching vLLM (``ParserEngine._is_valid_tool_name`` returns ``True``
when the request has no tools).
Cross-validated end-to-end against the real vLLM v0.23.0 and v0.24.0
parsers (vendored from the release tags) on identical completions.
"""
from __future__ import annotations
from functools import lru_cache
from parity import models_for
from renderers.base import ToolCallParseStatus
# Both GLM renderers share ``parse_glm`` and are served by the same
# strict vLLM parser (the ``glm45`` and ``glm47`` aliases both resolve
# to ``Glm47MoeModelToolParser`` in vLLM ≥ 0.24).
_MODELS = [(case.model, case.renderer) for case in models_for("glm-tool-names")]
_TOOLS = [
{
"name": "bash",
"description": "Run a shell command.",
"parameters": {
"type": "object",
"properties": {
"command": {"type": "string"},
"timeout": {"type": "integer"},
},
"required": ["command"],
},
},
# A declared tool with no parameters must still count as a known
# name (name lookup is independent of the param-type index).
{"name": "submit", "description": "Finish the episode."},
]
@lru_cache(maxsize=None)
def _load(model: str, renderer_name: str):
from renderers import config_from_name, create_renderer
from renderers.base import load_tokenizer
tok = load_tokenizer(model)
return tok, create_renderer(tok, config_from_name(renderer_name))
def pytest_generate_tests(metafunc):
if "model" in metafunc.fixturenames:
metafunc.parametrize(
"model,renderer_name",
_MODELS,
ids=[m for m, _ in _MODELS],
)
def _parse(model: str, renderer_name: str, text: str, tools):
tok, renderer = _load(model, renderer_name)
ids = tok.encode(text, add_special_tokens=False)
return renderer.parse_response(ids, tools=tools, prompt_ids=[])
def _statuses(parsed):
return [tc.status for tc in parsed.tool_calls]
def test_known_name_is_ok(model, renderer_name):
parsed = _parse(
model,
renderer_name,
"<tool_call>bash\n"
"<arg_key>command</arg_key>\n<arg_value>pwd</arg_value>\n"
"</tool_call>",
_TOOLS,
)
assert _statuses(parsed) == [ToolCallParseStatus.OK]
assert parsed.tool_calls[0].name == "bash"
assert parsed.tool_calls[0].arguments == {"command": "pwd"}
def test_known_name_without_parameters_is_ok(model, renderer_name):
parsed = _parse(model, renderer_name, "<tool_call>submit\n</tool_call>", _TOOLS)
assert _statuses(parsed) == [ToolCallParseStatus.OK]
assert parsed.tool_calls[0].name == "submit"
def test_unknown_name_is_flagged(model, renderer_name):
parsed = _parse(
model,
renderer_name,
"<tool_call>read\n"
"<arg_key>lines</arg_key>\n<arg_value>10</arg_value>\n"
"</tool_call>",
_TOOLS,
)
assert _statuses(parsed) == [ToolCallParseStatus.UNKNOWN_TOOL]
# The attempt stays visible (unlike vLLM's silent drop): name and
# parsed arguments are preserved for verifier / RL-loss consumers.
assert parsed.tool_calls[0].name == "read"
assert parsed.tool_calls[0].arguments == {"lines": 10}
def test_unknown_name_without_args_is_flagged(model, renderer_name):
parsed = _parse(model, renderer_name, "<tool_call>finish\n</tool_call>", _TOOLS)
assert _statuses(parsed) == [ToolCallParseStatus.UNKNOWN_TOOL]
def test_missing_arg_key_block_is_flagged(model, renderer_name):
# No <arg_key> token ⇒ the whole block resolves as the name — both
# here and in vLLM's engine (unmatched terminals in TOOL_NAME state
# accumulate into the name) — and then fails validation.
parsed = _parse(
model,
renderer_name,
"<tool_call>bash\n<arg_value>pwd</arg_value>\n</tool_call>",
_TOOLS,
)
assert _statuses(parsed) == [ToolCallParseStatus.UNKNOWN_TOOL]
assert "bash" in (parsed.tool_calls[0].name or "")
def test_mixed_calls_flag_only_unknown(model, renderer_name):
parsed = _parse(
model,
renderer_name,
"<tool_call>bash\n"
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value>\n"
"</tool_call>"
"<tool_call>read\n"
"<arg_key>path</arg_key>\n<arg_value>x</arg_value>\n"
"</tool_call>",
_TOOLS,
)
assert _statuses(parsed) == [
ToolCallParseStatus.OK,
ToolCallParseStatus.UNKNOWN_TOOL,
]
def test_no_tools_means_no_validation(model, renderer_name):
# vLLM skips name validation when the request carries no tools; so
# do we — this also keeps tools-less parse_response calls (the
# common test / SFT path) byte-for-byte backward compatible.
parsed = _parse(
model,
renderer_name,
"<tool_call>read\n"
"<arg_key>lines</arg_key>\n<arg_value>10</arg_value>\n"
"</tool_call>",
None,
)
assert _statuses(parsed) == [ToolCallParseStatus.OK]
def test_openai_envelope_tools_are_recognized(model, renderer_name):
wrapped = [{"type": "function", "function": t} for t in _TOOLS]
parsed = _parse(
model,
renderer_name,
"<tool_call>bash\n"
"<arg_key>command</arg_key>\n<arg_value>pwd</arg_value>\n"
"</tool_call>",
wrapped,
)
assert _statuses(parsed) == [ToolCallParseStatus.OK]
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_load.cache_clear()
-271
View File
@@ -1,271 +0,0 @@
"""GptOssRenderer parity vs ``openai-harmony``'s reference encoder.
Why this file exists
--------------------
HF's ``apply_chat_template`` for gpt-oss diverges from the model's
canonical wire format in small ways (trailing ``\\n\\n`` after developer
instructions; different layout for function-tool declarations). The
canonical format is what ``openai-harmony`` produces — vLLM uses that
encoder directly when serving gpt-oss, and it's what the model was
trained on.
So our ``GptOssRenderer`` matches harmony, not HF Jinja, and this file
checks that. ``test_render_ids`` skips gpt-oss for the same reason.
Each test mirrors the corresponding case in ``test_render_ids`` but
uses ``HarmonyEncoding.render_conversation_for_training`` as the
oracle.
"""
from __future__ import annotations
from datetime import datetime
import pytest
from openai_harmony import (
Conversation,
DeveloperContent,
HarmonyEncodingName,
Message as HarmonyMessage,
ReasoningEffort,
Role,
SystemContent,
ToolDescription,
load_harmony_encoding,
)
from renderers.configs import GptOssRendererConfig
from renderers.gpt_oss import GptOssRenderer
from transformers import AutoTokenizer
GPT_OSS_MODEL = "openai/gpt-oss-20b"
DATE_FOR_PARITY = datetime.now().strftime("%Y-%m-%d")
@pytest.fixture(scope="module")
def tokenizer():
return AutoTokenizer.from_pretrained(GPT_OSS_MODEL)
@pytest.fixture(scope="module")
def renderer(tokenizer):
# Pin the date so the rendered preamble matches the harmony oracle
# built with the same fixed date.
return GptOssRenderer(
tokenizer, GptOssRendererConfig(conversation_start_date=DATE_FOR_PARITY)
)
@pytest.fixture(scope="module")
def encoder():
return load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
def _system_content() -> SystemContent:
return (
SystemContent.new()
.with_reasoning_effort(ReasoningEffort.MEDIUM)
.with_conversation_start_date(DATE_FOR_PARITY)
)
def _tool_description() -> ToolDescription:
return ToolDescription.new(
name="get_weather",
description="Get the current weather for a city",
parameters={
"type": "object",
"properties": {
"city": {"type": "string", "description": "The city name"},
},
"required": ["city"],
},
)
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"],
},
},
}
]
def test_no_system_message(renderer, encoder):
"""A user-only conversation: only the auto-injected system preamble + user."""
msgs = [{"role": "user", "content": "Hello!"}]
got = renderer.render_ids(msgs, add_generation_prompt=False)
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.USER, "Hello!"),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_system_and_user(renderer, encoder):
"""The caller's first system message becomes the developer Instructions block."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hello!"},
]
got = renderer.render_ids(msgs, add_generation_prompt=False)
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(
Role.DEVELOPER,
DeveloperContent.new().with_instructions("You are helpful."),
),
HarmonyMessage.from_role_and_content(Role.USER, "Hello!"),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_terminal_assistant_uses_return(renderer, encoder):
"""Terminal assistant turn (no follow-up) closes with ``<|return|>``."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
got = renderer.render_ids(msgs, add_generation_prompt=False)
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.USER, "Hi"),
HarmonyMessage.from_role_and_content(Role.ASSISTANT, "Hello!").with_channel(
"final"
),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_tools_with_system(renderer, encoder):
"""Tools attach to the developer message alongside the instructions."""
msgs = [
{"role": "system", "content": "You are a weather assistant."},
{"role": "user", "content": "Weather?"},
]
got = renderer.render_ids(msgs, tools=TOOLS, add_generation_prompt=False)
dev = (
DeveloperContent.new()
.with_instructions("You are a weather assistant.")
.with_function_tools([_tool_description()])
)
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev),
HarmonyMessage.from_role_and_content(Role.USER, "Weather?"),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_tool_call_and_response(renderer, encoder):
"""Tool call → tool result → final assistant: each in its own harmony message."""
msgs = [
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c1",
"function": {
"name": "get_weather",
"arguments": '{"city": "Paris"}',
},
}
],
},
{
"role": "tool",
"content": '{"temp": 20}',
"tool_call_id": "c1",
"name": "get_weather",
},
{"role": "assistant", "content": "It's 20 degrees in Paris."},
]
got = renderer.render_ids(msgs, tools=TOOLS, add_generation_prompt=False)
dev = DeveloperContent.new().with_function_tools([_tool_description()])
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev),
HarmonyMessage.from_role_and_content(Role.USER, "Weather in Paris?"),
HarmonyMessage.from_role_and_content(Role.ASSISTANT, '{"city": "Paris"}')
.with_channel("commentary")
.with_recipient("functions.get_weather"),
HarmonyMessage.from_author_and_content(
{"role": "tool", "name": "functions.get_weather"}, '{"temp": 20}'
)
.with_recipient("assistant")
.with_channel("commentary"),
HarmonyMessage.from_role_and_content(
Role.ASSISTANT, "It's 20 degrees in Paris."
).with_channel("final"),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_assistant_with_reasoning_content_strips_analysis(renderer, encoder):
"""Historical reasoning_content is stripped — harmony drops
analysis-channel messages from rendered history. The renderer matches
that behaviour, emitting only the final-channel text."""
msgs = [
{"role": "user", "content": "2+2?"},
{
"role": "assistant",
"content": "Four.",
"reasoning_content": "Two plus two is four.",
},
]
got = renderer.render_ids(msgs, add_generation_prompt=False)
# Oracle has no analysis message — it would be stripped anyway.
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.USER, "2+2?"),
HarmonyMessage.from_role_and_content(Role.ASSISTANT, "Four.").with_channel(
"final"
),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_generation_prompt(renderer):
"""``add_generation_prompt=True`` appends the analysis-channel start."""
msgs = [{"role": "user", "content": "Hi"}]
got = renderer.render_ids(msgs, add_generation_prompt=True)
no_genprompt = renderer.render_ids(msgs, add_generation_prompt=False)
# The trailing tokens should be: <|start|>assistant<|channel|>analysis<|message|>
suffix = got[len(no_genprompt) :]
decoded = renderer._tokenizer.decode(suffix) # noqa: SLF001
assert decoded == "<|start|>assistant<|channel|>analysis<|message|>", decoded
-136
View File
@@ -1,136 +0,0 @@
"""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")
+9 -1
View File
@@ -110,7 +110,10 @@ def test_parse_low_mode_inference_stream():
"Let me work it out." + _THINK_END + "It is 4." + _EOS,
add_special_tokens=False,
)
parsed = r.parse_response(comp)
prompt = r.render_ids(
[{"role": "user", "content": "What is 2+2?"}], add_generation_prompt=True
)
parsed = r.parse_response(comp, prompt_ids=prompt)
assert parsed.reasoning_content == "Let me work it out."
assert parsed.content == "It is 4."
assert not parsed.tool_calls
@@ -484,3 +487,8 @@ def test_bridge_declines_on_empty_completion():
rf.bridge_to_next_turn(prompt, [], [{"role": "tool", "content": "more"}])
is None
)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_tok.cache_clear()
+1 -1
View File
@@ -1,7 +1,7 @@
"""Unit tests for ``trim_to_turn_close`` and the bridge contract invariants
that every renderer's ``bridge_to_next_turn`` must uphold.
Cross-renderer parity is validated in test_render_ids.py and test_roundtrip.py;
Cross-renderer parity is validated in test_parity.py and test_roundtrip.py;
this file exercises the shared primitive + protocol-level guarantees with a
fake renderer so we get fast, deterministic coverage of the tricky corners
(truncation opt-in, assistant-in-extension rejection, empty inputs).
+528
View File
@@ -0,0 +1,528 @@
"""Focused tests for Inkling and Inkling-Small.
The shared matrices (conftest render-parity, config-parity, multimodal) already
assert byte parity on the common shapes and image/audio parity against the
processor. This file pins the behaviours specific to Inkling's token-delimited
template that those matrices don't generate:
- the ``Thinking effort level: {N}`` line (labels + raw floats, ``0`` special case),
- effort emitted once before the first non-system message (or at the end),
- the token-delimited assistant structure and its sampled/is_content masks,
- tool-name resolution via ``tool_call_id``,
- parse round-trips (reasoning / content / native-JSON tool calls),
- bridge extensions matching a fresh render byte-for-byte,
- config validation of ``reasoning_effort``.
"""
from __future__ import annotations
from functools import lru_cache
import numpy as np
import pytest
from renderers import create_renderer
from renderers.base import ToolCallParseStatus, load_tokenizer
from renderers.configs import InklingRendererConfig
from renderers.inkling import InklingRenderer
_MODEL = "thinkingmachines/Inkling"
_SMALL_MODEL = "thinkingmachines/Inkling-Small"
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) -> InklingRenderer:
renderer = create_renderer(_tok(), InklingRendererConfig(**config_kwargs))
assert isinstance(renderer, InklingRenderer)
return renderer
def _expected(msgs, *, tools=None, add_generation_prompt=False, **template_kwargs):
result = _tok().apply_chat_template(
msgs,
tools=tools,
add_generation_prompt=add_generation_prompt,
tokenize=True,
return_dict=False,
**template_kwargs,
)
if isinstance(result, dict):
return list(result["input_ids"])
if isinstance(result, str):
return list(_tok().encode(result, add_special_tokens=False))
return list(result)
def _decode(ids):
return _tok().decode(ids, skip_special_tokens=False)
@pytest.mark.parametrize("checkpoint", [_MODEL, _SMALL_MODEL])
def test_auto_resolves_both_checkpoints_to_shared_renderer(checkpoint):
renderer = create_renderer(load_tokenizer(checkpoint))
assert isinstance(renderer, InklingRenderer)
assert renderer.config.name == "inkling"
# ── Reasoning-effort line ─────────────────────────────────────────────
@pytest.mark.parametrize(
"effort,shown",
[
("none", "0"),
("minimal", "0.1"),
("low", "0.2"),
("medium", "0.7"),
("high", "0.9"),
("max", "0.99"),
(0.0, "0"),
(0.5, "0.5"),
(0.33, "0.33"),
(0.99, "0.99"),
],
)
def test_effort_line_format_and_parity(effort, shown):
msgs = [{"role": "user", "content": "Hi"}]
r = _renderer(reasoning_effort=effort)
ours = r.render_ids(msgs, add_generation_prompt=True)
assert ours == _expected(msgs, add_generation_prompt=True, reasoning_effort=effort)
assert f"Thinking effort level: {shown}<|end_message|>" in _decode(ours)
def test_default_effort_is_high():
"""No ``reasoning_effort`` set mirrors the template default (0.9)."""
msgs = [{"role": "user", "content": "Hi"}]
ours = _renderer().render_ids(msgs, add_generation_prompt=True)
assert ours == _expected(msgs, add_generation_prompt=True)
assert "Thinking effort level: 0.9<|end_message|>" in _decode(ours)
def test_effort_emitted_once_before_first_non_system():
msgs = [
{"role": "system", "content": "SYS"},
{"role": "user", "content": "Hi"},
]
ours = _renderer().render_ids(msgs, add_generation_prompt=True)
assert ours == _expected(msgs, add_generation_prompt=True)
text = _decode(ours)
# System body precedes the effort line, which precedes the user turn.
assert (
text.index("SYS")
< text.index("Thinking effort level")
< text.index("<|message_user|>")
)
assert text.count("Thinking effort level") == 1
def test_effort_emitted_at_end_when_all_system():
msgs = [{"role": "system", "content": "only sys"}]
ours = _renderer().render_ids(msgs)
assert ours == _expected(msgs)
text = _decode(ours)
assert text.index("only sys") < text.index("Thinking effort level")
# ── Tool declaration precedes everything ──────────────────────────────
def test_tool_declaration_comes_first():
msgs = [
{"role": "system", "content": "SYS"},
{"role": "user", "content": "Weather?"},
]
ours = _renderer().render_ids(msgs, tools=TOOLS, add_generation_prompt=True)
assert ours == _expected(msgs, tools=TOOLS, add_generation_prompt=True)
text = _decode(ours)
assert text.startswith("<|message_system|>tool_declare<|content_xml|>")
# The tools block precedes the system body and the effort line.
assert (
text.index("tool_declare")
< text.index("SYS")
< text.index("Thinking effort level")
)
# ── Assistant structure + masks ───────────────────────────────────────
def test_assistant_structure_and_masks():
msgs = [
{"role": "user", "content": "2+2?"},
{
"role": "assistant",
"reasoning_content": "add them",
"content": "4",
},
]
r = _renderer()
rendered = r.render(msgs)
assert rendered.token_ids == _expected(msgs)
pos = [k for k, i in enumerate(rendered.message_indices) if i == 1]
sampled = [rendered.sampled_mask[k] for k in pos]
# Only the leading <|message_model|> (gen-prompt-equivalent) is scaffold.
assert sampled[0] is False
assert all(sampled[1:])
# On assistant tokens is_content == sampled_mask by construction.
assert [rendered.is_content[k] for k in pos] == sampled
# The turn ends on the sampled <|content_model_end_sampling|>.
assert rendered.token_ids[pos[-1]] == r._content_model_end_sampling
assert rendered.sampled_mask[pos[-1]] is True
def test_tool_call_invoke_json_shape():
msgs = [
{"role": "user", "content": "hi"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris", "days": 3},
}
}
],
},
]
ours = _renderer().render_ids(msgs, tools=TOOLS)
assert ours == _expected(msgs, tools=TOOLS)
assert (
"<|message_model|>get_weather<|content_invoke_tool_json|>"
'{"name":"get_weather","args":{"city":"Paris","days":3}}<|end_message|>'
) in _decode(ours)
@pytest.mark.parametrize("arguments", ["not-json", "[]", ["not", "an", "object"]])
def test_tool_call_rejects_non_object_arguments(arguments):
msgs = [
{"role": "user", "content": "hi"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": arguments}}
],
},
]
with pytest.raises(TypeError, match="arguments must be a JSON object"):
_renderer().render_ids(msgs, tools=TOOLS)
def test_unknown_content_part_type_raises():
with pytest.raises(ValueError, match="Unsupported Inkling content part type"):
_renderer().render_ids(
[
{
"role": "user",
"content": [{"type": "file", "file": "notes.txt"}],
}
]
)
def test_input_image_field_loads_during_render_and_bridge(monkeypatch):
from PIL import Image
renderer = _renderer()
image = Image.new("RGB", (2, 2), color="navy")
processed_images = []
def process_image(pil, _image_hash):
processed_images.append(pil)
return {"pixel_values": np.zeros((1, 1), dtype=np.float32)}, 1
monkeypatch.setattr(renderer, "_process_image", process_image)
part = {"type": "input_image", "input_image": image}
rendered = renderer.render([{"role": "user", "content": [part]}])
assert rendered.multi_modal_data is not None
assert len(rendered.multi_modal_data.mm_items["image"]) == 1
bridged, fresh = _bridge_case(
renderer,
[{"role": "user", "content": "Describe this later."}],
{"role": "assistant", "content": "Okay."},
[{"role": "user", "content": [part]}],
)
assert bridged is not None
assert bridged.token_ids == fresh
assert bridged.multi_modal_data is not None
assert len(bridged.multi_modal_data.mm_items["image"]) == 1
assert processed_images and all(pil is image for pil in processed_images)
# ── Tool-name resolution ──────────────────────────────────────────────
def test_tool_name_resolved_via_tool_call_id():
msgs = [
{"role": "user", "content": "hi"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c1",
"function": {"name": "get_weather", "arguments": {"city": "Paris"}},
}
],
},
{"role": "tool", "tool_call_id": "c1", "content": "sunny"},
]
ours = _renderer().render_ids(msgs, tools=TOOLS)
assert ours == _expected(msgs, tools=TOOLS)
assert "<|message_tool|>get_weather<|content_text|>sunny<|end_message|>" in _decode(
ours
)
# ── Parse ─────────────────────────────────────────────────────────────
def _completion(prompt, asst, *, tools=None):
r = _renderer()
pp = r.render_ids(prompt, tools=tools, add_generation_prompt=True)
full = r.render_ids([*prompt, asst], tools=tools)
return r, full[len(pp) :]
def test_parse_reasoning_and_content():
r, comp = _completion(
[{"role": "user", "content": "2+2?"}],
{
"role": "assistant",
"reasoning_content": "Let me think.",
"content": "The answer is 4.",
},
)
parsed = r.parse_response(comp)
assert parsed.reasoning_content == "Let me think."
assert parsed.content == "The answer is 4."
assert not parsed.tool_calls
def test_parse_tool_call_preserves_types():
r, comp = _completion(
[{"role": "user", "content": "weather?"}],
{
"role": "assistant",
"content": "checking",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris", "days": 3},
}
}
],
},
tools=TOOLS,
)
parsed = r.parse_response(comp, tools=TOOLS)
assert parsed.content == "checking"
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.name == "get_weather"
assert tc.arguments == {"city": "Paris", "days": 3} # int preserved
assert tc.status == ToolCallParseStatus.OK
assert tc.token_span is not None
def test_parse_multiple_tool_calls():
r, comp = _completion(
[{"role": "user", "content": "hi"}],
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "f", "arguments": {"a": 1}}},
{"function": {"name": "g", "arguments": {}}},
],
},
)
parsed = r.parse_response(comp)
assert [tc.name for tc in parsed.tool_calls] == ["f", "g"]
assert parsed.tool_calls[0].arguments == {"a": 1}
assert parsed.tool_calls[1].arguments == {}
# ── Bridge ────────────────────────────────────────────────────────────
def _bridge_case(r, prev, asst, ext, *, tools=None):
pp = r.render_ids(prev, tools=tools, add_generation_prompt=True)
full = r.render_ids([*prev, asst], tools=tools)
completion = full[len(pp) :]
assert completion[-1] == r._content_model_end_sampling
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_fresh_render():
r = _renderer()
bridged, fresh = _bridge_case(
r,
[{"role": "user", "content": "Hi"}],
{"role": "assistant", "content": "Hello!"},
[{"role": "user", "content": "Bye"}],
)
assert bridged is not None
assert bridged.token_ids == fresh
def test_bridge_tool_extension_matches_fresh_render():
r = _renderer()
bridged, fresh = _bridge_case(
r,
[{"role": "user", "content": "Weather in Tokyo?"}],
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Tokyo"}}}
],
},
# Tool message carries an explicit name (bridge can't resolve a
# prior-turn tool_call_id since the assistant is outside new_messages).
[
{"role": "tool", "name": "get_weather", "content": "Sunny"},
{"role": "user", "content": "And Paris?"},
],
tools=TOOLS,
)
assert bridged is not None
assert bridged.token_ids == fresh
def test_bridge_synthesizes_close_on_truncation():
r = _renderer()
prev = [{"role": "user", "content": "Hi"}]
asst = {"role": "assistant", "content": "Hello!"}
ext = [{"role": "user", "content": "Bye"}]
pp = r.render_ids(prev, add_generation_prompt=True)
full = r.render_ids([*prev, asst])
# Truncated: drop the terminating <|content_model_end_sampling|>.
completion = full[len(pp) : -1]
assert r._content_model_end_sampling not in completion
bridged = r.bridge_to_next_turn(pp, completion, ext)
assert bridged is not None
fresh = r.render_ids([*prev, asst, *ext], add_generation_prompt=True)
assert bridged.token_ids == fresh
def test_bridge_rejects_assistant_extension():
r = _renderer()
pp = r.render_ids([{"role": "user", "content": "Hi"}], add_generation_prompt=True)
assert (
r.bridge_to_next_turn(
pp, [r._content_model_end_sampling], [{"role": "assistant", "content": "x"}]
)
is None
)
def test_bridge_refuses_tool_needing_prior_name_resolution():
"""A tool message with only ``tool_call_id`` (no explicit name) can't be
resolved from ``new_messages`` alone, so the bridge refuses (the caller
re-renders)."""
r = _renderer()
pp = r.render_ids([{"role": "user", "content": "Hi"}], add_generation_prompt=True)
bridged = r.bridge_to_next_turn(
pp,
[r._content_model_end_sampling],
[{"role": "tool", "tool_call_id": "c1", "content": "sunny"}],
)
assert bridged is None
# ── Config validation ─────────────────────────────────────────────────
def test_config_accepts_labels_and_floats():
for eff in ("none", "minimal", "low", "medium", "high", "max", 0.0, 0.5, 0.99):
InklingRendererConfig(reasoning_effort=eff)
def test_audio_cache_has_an_independent_bound_and_uses_public_processor_api():
class FakeProcessor:
def __init__(self):
self.calls = []
def __call__(self, **kwargs):
self.calls.append(kwargs)
return {
"audio_input_ids": np.zeros((1, 1, 80), dtype=np.int32),
"audio_input_ids_mask": np.ones((1, 1), dtype=bool),
}
processor = FakeProcessor()
renderer = InklingRenderer(
_tok(),
InklingRendererConfig(image_cache_max=1, audio_cache_max=2),
processor=processor,
)
renderer._process_audio(np.zeros(8, dtype=np.float32), 16_000)
renderer._process_audio(np.ones(8, dtype=np.float32), 16_000)
assert len(renderer._audio_cache) == 2
assert all(call["return_tensors"] == "pt" for call in processor.calls)
assert all(call["sampling_rate"] == 16_000 for call in processor.calls)
def test_processor_unavailable_fails_lazily_with_upgrade_message(monkeypatch):
def unavailable(*args, **kwargs):
raise ValueError("unknown processor")
monkeypatch.setattr("transformers.AutoProcessor.from_pretrained", unavailable)
renderer = _renderer()
with pytest.raises(RuntimeError, match="Transformers >=5.14"):
renderer._get_processor()
@pytest.mark.parametrize("bad", ["no_think", "bogus", 1.5, -0.1])
def test_config_rejects_bad_effort(bad):
with pytest.raises(Exception):
InklingRendererConfig(reasoning_effort=bad)
# ── Stop tokens ───────────────────────────────────────────────────────
def test_stop_tokens():
r = _renderer()
stop = r.get_stop_token_ids()
assert r._content_model_end_sampling in stop
# eos is <|content_model_end_sampling|> (config.json eos_token_id = 200006).
assert stop[0] == r._content_model_end_sampling
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_tok.cache_clear()
+159
View File
@@ -0,0 +1,159 @@
"""Exact chat-template parity for the official Laguna M.1 checkpoint."""
from __future__ import annotations
from functools import lru_cache
from pydantic import TypeAdapter
from renderers import (
LagunaM1Renderer,
LagunaM1RendererConfig,
RendererConfig,
create_renderer,
)
from renderers.base import load_tokenizer
_MODEL = "poolside/Laguna-M.1"
TOOLS = [
{
"type": "function",
"function": {
"name": "shell",
"description": "Run a shell command",
"parameters": {
"type": "object",
"properties": {
"cmd": {"type": "string"},
"timeout": {"type": "integer"},
},
"required": ["cmd"],
},
},
}
]
@lru_cache(maxsize=None)
def _tok():
return load_tokenizer(_MODEL)
def _renderer(**kwargs) -> LagunaM1Renderer:
renderer = create_renderer(_tok(), LagunaM1RendererConfig(**kwargs))
assert isinstance(renderer, LagunaM1Renderer)
return renderer
def _expected(messages, *, tools=None, add_generation_prompt=False, **kwargs):
return list(
_tok().apply_chat_template(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
tokenize=True,
return_dict=False,
**kwargs,
)
)
def test_auto_selection_and_typed_config():
renderer = create_renderer(_tok())
assert isinstance(renderer, LagunaM1Renderer)
assert isinstance(renderer.config, LagunaM1RendererConfig)
parsed = TypeAdapter(RendererConfig).validate_python(
{"name": "laguna-m.1", "enable_thinking": True}
)
assert isinstance(parsed, LagunaM1RendererConfig)
assert parsed.enable_thinking is True
def test_reasoning_field_precedence_and_inline_think_extraction():
precedence = [
{"role": "user", "content": "Compute."},
{
"role": "assistant",
"reasoning": "preferred",
"reasoning_content": "ignored",
"content": "answer",
},
]
got = _renderer(enable_thinking=True).render_ids(precedence)
assert got == _expected(precedence, enable_thinking=True)
text = _tok().decode(got)
assert "preferred" in text
assert "ignored" not in text
empty_reasoning_wins = [
{"role": "user", "content": "Compute."},
{
"role": "assistant",
"reasoning": "",
"reasoning_content": "also ignored",
"content": "answer",
},
]
got = _renderer(enable_thinking=True).render_ids(empty_reasoning_wins)
assert got == _expected(empty_reasoning_wins, enable_thinking=True)
assert "also ignored" not in _tok().decode(got)
inline = [
{"role": "user", "content": "Compute."},
{
"role": "assistant",
"content": "<think>\ninline reason\n</think>\nvisible answer",
},
]
assert _renderer().render_ids(inline) == _expected(inline)
def test_reasoning_content_and_tool_call_round_trip():
renderer = _renderer(enable_thinking=True)
prompt = [{"role": "user", "content": "Inspect the machine."}]
assistant = {
"role": "assistant",
"reasoning": "Need a command.",
"content": "Running it.",
"tool_calls": [
{
"function": {
"name": "shell",
"arguments": {"cmd": "uname -a", "timeout": 5},
}
}
],
}
prompt_ids = renderer.render_ids(prompt, add_generation_prompt=True)
full_ids = renderer.render_ids([*prompt, assistant])
completion_ids = full_ids[len(prompt_ids) :]
parsed = renderer.parse_response(completion_ids, tools=TOOLS, prompt_ids=prompt_ids)
assert parsed.reasoning_content == "Need a command."
assert parsed.content == "Running it."
assert len(parsed.tool_calls) == 1
assert parsed.tool_calls[0].name == "shell"
assert parsed.tool_calls[0].arguments == {"cmd": "uname -a", "timeout": 5}
def test_raw_assistant_round_trip_parity():
messages = [
{"role": "user", "content": "Continue."},
{
"role": "assistant",
"content": "<think>raw reason</think>raw body</assistant>",
},
]
renderer = _renderer(enable_thinking=True, render_assistant_messages_raw=True)
assert renderer.render_ids(messages) == _expected(
messages,
enable_thinking=True,
render_assistant_messages_raw=True,
)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_tok.cache_clear()
+41 -4
View File
@@ -19,9 +19,11 @@ from __future__ import annotations
from functools import lru_cache
import pytest
from renderers import create_renderer
from renderers.base import load_tokenizer
from renderers.configs import LagunaXS21RendererConfig
from renderers.configs import LagunaXS21RendererConfig, config_from_name
from renderers.laguna_xs2 import LagunaXS21Renderer
_MODEL = "poolside/Laguna-XS-2.1"
@@ -250,15 +252,45 @@ def test_parse_no_think_completion():
completion is pure content up to ``</assistant>``."""
parsed = _renderer().parse_response(_completion_ids("Four.</assistant>"))
assert parsed.content == "Four."
assert parsed.reasoning_complete is True
assert parsed.reasoning_content is None
assert not parsed.tool_calls
@pytest.mark.parametrize(
"renderer_name", ["laguna-xs.2", "laguna-m.1", "laguna-xs-2.1", "laguna-s-2.1"]
)
@pytest.mark.parametrize("stop", ["", "</assistant>"])
def test_parse_unclosed_prefilled_thinking(renderer_name, stop):
config = config_from_name(renderer_name).model_copy(
update={"enable_thinking": True}
)
renderer = create_renderer(_tok(), config)
prompt = renderer.render_ids(
[{"role": "user", "content": "Research a fact."}], add_generation_prompt=True
)
assert _tok().decode(prompt).endswith("<think>")
text = "Still investigating.<tool_call>get_weather<arg_key>city</arg_key><arg_value>Tokyo</arg_value></tool_call>"
completion = text + stop
parsed = renderer.parse_response(
_completion_ids(completion), tools=TOOLS, prompt_ids=prompt
)
assert parsed.reasoning_content == text
assert parsed.content == ""
assert parsed.tool_calls == []
assert parsed.reasoning_complete is False
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>")
renderer = _renderer(enable_thinking=True)
prompt = renderer.render_ids(
[{"role": "user", "content": "Answer."}], add_generation_prompt=True
)
parsed = renderer.parse_response(
_completion_ids("Chain of thought</think>\nThe answer.\n</assistant>"),
prompt_ids=prompt,
)
assert parsed.reasoning_content == "Chain of thought"
assert parsed.content == "\nThe answer.\n"
@@ -294,7 +326,7 @@ def test_roundtrip_reasoning_with_thinking():
pp = r.render_ids(prompt, add_generation_prompt=True)
full = r.render_ids([*prompt, msg])
completion = full[len(pp) :]
parsed = r.parse_response(completion)
parsed = r.parse_response(completion, prompt_ids=pp)
assert parsed.reasoning_content == "Two plus two equals four."
assert parsed.content == "The answer is four."
@@ -374,3 +406,8 @@ def test_bridge_rejects_assistant_extension():
)
is None
)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_tok.cache_clear()
+4 -147
View File
@@ -10,11 +10,13 @@ with Meta license access.
from __future__ import annotations
import pytest
from parity import models_for
from renderers import Llama3Renderer, Llama3RendererConfig, create_renderer
from renderers.base import (
MODEL_RENDERER_MAP,
ParsedResponse,
TOKENIZER_SOURCE_OVERRIDES,
ToolCallParseStatus,
load_tokenizer,
)
@@ -24,10 +26,8 @@ from renderers.base import (
_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"),
(case.model, TOKENIZER_SOURCE_OVERRIDES[case.model])
for case in models_for("llama-checkpoints")
]
@@ -115,149 +115,6 @@ def _expected(tok, messages, **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."""
+16 -11
View File
@@ -12,8 +12,6 @@ import re
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from renderers import base
from renderers.base import TOKENIZER_SOURCE_OVERRIDES, TRUSTED_REVISIONS, load_tokenizer
@@ -122,22 +120,29 @@ def test_tokenizer_source_overrides_are_exact_llama_mirrors():
}
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."""
def test_offsetless_byo_preserves_ids_without_content_attribution():
"""Offsetless BYO tokenizers keep the joined BPE pass but omit attribution."""
class _NoOffsets:
name_or_path = "anywhere/anything"
def encode(self, text, *, add_special_tokens=False):
assert add_special_tokens is False
return [len(text)]
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())
tokenizer = _NoOffsets()
assert base._get_offset_tokenizer(tokenizer) is None
attributed = base.attribute_text_segments(
tokenizer,
[("user\n", False), ("hello", True)],
)
assert attributed == [(10, False)]
assert attributed.has_content_attribution is False
# ---------------------------------------------------------------------------
+64 -1
View File
@@ -2,7 +2,7 @@
Why this file exists
--------------------
The test barrage in ``test_render_ids`` checks token-id parity against
The matrix in ``test_parity`` checks token-id parity against
``apply_chat_template`` — useful, but only for token *bytes*. The
per-token attribution (``RenderedTokens.message_indices``) was never
covered, even though it directly drives the loss mask in
@@ -40,6 +40,69 @@ Tests in this file:
from __future__ import annotations
import pytest
from renderers import build_training_sample
from renderers.glm45 import GLM45Renderer
from renderers.glm5 import GLM5Renderer
from tests.reference_rendering import render_reference
def test_glm_tool_stop_ownership(model_name, tokenizer, renderer):
"""The first emitted observation closes the assistant, even after reordering."""
if not isinstance(renderer, (GLM5Renderer, GLM45Renderer)):
pytest.skip("GLM turn-closing role markers")
messages = [
{"role": "user", "content": "Look up both"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": f"c{i}",
"type": "function",
"function": {"name": f"f{i}", "arguments": {}},
}
for i in (1, 2)
],
},
{
"role": "tool",
"content": "Second result",
"tool_call_id": "c2",
"name": "f2",
},
{"role": "tool", "content": "First result", "tool_call_id": "c1", "name": "f1"},
{"role": "assistant", "content": "Done"},
]
rendered = renderer.render(messages)
assert rendered.token_ids == render_reference(tokenizer, messages)
observation = tokenizer.encode("<|observation|>", add_special_tokens=False)[0]
positions = [
k for k, token in enumerate(rendered.token_ids) if token == observation
]
first, *rest = positions
assert rendered.message_indices[first] == 1
assert rendered.sampled_mask[first] and rendered.is_content[first]
assert not any(rendered.sampled_mask[k] for k in rest)
assert not rendered.content_mask_for_roles({"tool"})[first]
span = rendered.message_token_spans()[1]
assert span is not None
assert all(index == 1 for index in rendered.message_indices[span[0] : span[1]])
for selected in (False, True):
sample = build_training_sample(
renderer,
messages,
message_loss_mask=[0, selected, not selected, not selected, 0],
content_sft_roles={"tool"},
ensure_final_stop=True,
)
assert sample.loss_mask[first] == selected
for k, is_tool_body in enumerate(rendered.content_mask_for_roles({"tool"})):
if is_tool_body:
assert sample.loss_mask[k] == (not selected)
assert not sample.loss_mask[-1]
def test_message_indices_in_range(model_name, renderer):
"""Every emitted token's ``message_indices`` must be in
+255 -15
View File
@@ -52,6 +52,7 @@ def _config_with_add_vision_id(model_name: str, add_vision_id: bool):
pytest.importorskip("PIL", reason="Pillow required for multimodal tests")
pytest.importorskip("torch", reason="torch required for multimodal tests")
import numpy as np # noqa: E402
from PIL import Image # noqa: E402
@@ -104,8 +105,8 @@ _loaded: dict[str, tuple] = {}
# Models whose processors need ``trust_remote_code=True`` (custom Python
# in the repo) AND a pinned revision for security. Mirrors the
# ``TRUSTED_REVISIONS`` policy in ``renderers.base`` for tokenizers.
# in the repo) and still use a pinned revision. Nemotron 3.5 is handled
# separately below so its selected model revision is not overridden.
_PROCESSOR_TRUSTED_REVISIONS: dict[str, str] = {
"moonshotai/Kimi-K2.5": "4d01dfe0332d63057c186e0b262165819efb6611",
"moonshotai/Kimi-K2.6": "2755962d07cb42aa2d988a35bcb65cd4a9c2de82",
@@ -118,9 +119,16 @@ def _load_processor_and_renderer(model_name: str):
tokenizer = load_tokenizer(model_name)
revision = _PROCESSOR_TRUSTED_REVISIONS.get(model_name)
if revision is not None:
if model_name.startswith("nvidia/NVIDIA-Nemotron-3.5"):
processor = AutoProcessor.from_pretrained(
model_name, trust_remote_code=True, revision=revision
model_name,
trust_remote_code=True,
)
elif revision is not None:
processor = AutoProcessor.from_pretrained(
model_name,
trust_remote_code=True,
revision=revision,
)
else:
processor = AutoProcessor.from_pretrained(model_name)
@@ -167,11 +175,24 @@ def _detect_family(model_name: str) -> str:
- ``kimi_k25``: ``processor(messages=..., return_tensors=...)`` (does
template + image preprocessing in one call), content parts shaped
``{"type": "image_url", "image_url": <PIL>}``.
- ``gemma4``: canonical Gemma turn grammar plus dynamic
``<|image>`` + N x ``<|image|>`` + ``<image|>`` expansion.
"""
if model_name.startswith("nvidia/NVIDIA-Nemotron-3.5"):
return "nemotron35"
if model_name.startswith("moonshotai/Kimi-K2.5") or model_name.startswith(
"moonshotai/Kimi-K2.6"
):
return "kimi_k25"
if model_name.startswith("google/gemma-4-"):
return "gemma4"
if model_name in {
"thinkingmachines/Inkling",
"thinkingmachines/Inkling-Small",
}:
# Two-step processor call like Qwen-VL — processor(images=/audio=, text=)
# — but different placeholder tokens and a distinct audio modality.
return "inkling"
return "qwen_vl"
@@ -204,6 +225,45 @@ def _qwen_vl_processor_input_ids(processor, messages, add_gp):
].tolist()
def _audio_content_part(audio):
return {"type": "audio", "audio": audio}
def _inkling_audio_processor_input_ids(processor, messages, add_gp):
"""Run Inkling's processor on audio-bearing ``messages``.
Two-step like the Qwen-VL image path, but collects audio waveforms and
passes them via ``audio=``. The template puts one ``<|unused_200053|>``
per audio placeholder; the processor expands it to one per mel frame.
"""
text = processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=add_gp
)
audios = []
for msg in messages:
content = msg.get("content")
if not isinstance(content, list):
continue
for item in content:
if not (
isinstance(item, dict)
and item.get("type")
in (
"audio",
"input_audio",
"audio_url",
)
):
continue
for key in ("audio", "input_audio", "audio_url"):
if key in item:
audios.append(item[key])
break
return processor(audio=audios, text=text, return_tensors="pt")["input_ids"][
0
].tolist()
def _kimi_processor_input_ids(processor, messages, add_gp):
"""Run Kimi K2.5's processor on ``messages`` (one-shot template+vision).
@@ -218,6 +278,43 @@ def _kimi_processor_input_ids(processor, messages, add_gp):
return out["input_ids"][0].tolist()
def _gemma4_processor_input_ids(processor, messages, add_gp):
"""Run Gemma 4's template followed by its dynamic image expansion."""
text = processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=add_gp
)
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:
raw = item.get("image")
if raw is not None:
images.append(raw)
out = processor(images=[images], text=[text], return_tensors="pt")
return out["input_ids"][0].tolist()
def _audio_sample():
"""A 1-second 440 Hz mono tone at 16 kHz (Inkling's expected rate)."""
sr = 16000
t = np.arange(sr, dtype=np.float32) / sr
return (0.1 * np.sin(2 * np.pi * 440 * t)).astype(np.float32)
def _sample_for(modality: str, tiny_image):
"""The per-modality media item cases are built from."""
if modality == "image":
return tiny_image
if modality == "audio":
return _audio_sample()
raise NotImplementedError(f"No sample for modality {modality!r}.")
def _modality_kit(modality: str, model_name: str):
family = _detect_family(model_name)
if modality == "image":
@@ -227,12 +324,43 @@ def _modality_kit(modality: str, model_name: str):
"placeholder_token": "<|media_pad|>",
"processor_input_ids": _kimi_processor_input_ids,
}
if family == "gemma4":
return {
"make_part": _image_content_part,
"placeholder_token": "<|image|>",
"processor_input_ids": _gemma4_processor_input_ids,
}
if family == "inkling":
# Inkling expands the single image placeholder to ``num_patches``
# ``<|unused_200054|>`` tokens; the processor call matches the
# Qwen-VL two-step (images=, text=).
return {
"make_part": _image_content_part,
"placeholder_token": "<|unused_200054|>",
"processor_input_ids": _qwen_vl_processor_input_ids,
}
if family == "nemotron35":
return {
"make_part": _image_content_part,
"placeholder_token": "<image>",
"processor_input_ids": _qwen_vl_processor_input_ids,
}
# Default: Qwen-VL family (Qwen3-VL, Qwen3.5, Qwen3.6).
return {
"make_part": _image_content_part,
"placeholder_token": "<|image_pad|>",
"processor_input_ids": _qwen_vl_processor_input_ids,
}
if modality == "audio":
if family == "inkling":
return {
"make_part": _audio_content_part,
"placeholder_token": "<|unused_200053|>",
"processor_input_ids": _inkling_audio_processor_input_ids,
}
raise NotImplementedError(
f"Audio test kit not implemented for family {family!r}."
)
raise NotImplementedError(
f"Test kit for modality {modality!r} not implemented yet."
)
@@ -437,15 +565,55 @@ def _build_tool_image_cases(make_part, image):
# ---------------------------------------------------------------------------
def _skip_for_disabled_thinking_deviation(renderer, case_id) -> bool:
"""Skip processor parity where a disabled-thinking renderer deliberately
preserves a generation-prefilled empty thought wrapper on assistant history.
The Qwen family deviates only once the assistant is before a later user
query. Gemma 4's 26B/31B revision never re-emits its generation prefill in
the upstream template, so every media case containing an assistant turn is
affected. Sampled-token stability is covered separately.
"""
from renderers.gemma4 import Gemma4Renderer
from renderers.qwen35 import Qwen35Renderer
qwen_deviation = (
isinstance(renderer, Qwen35Renderer)
and getattr(renderer.config, "enable_thinking", True) is False
and case_id
in (
"multi_turn_two_images",
"multi_turn_tool_response_images",
)
)
gemma4_deviation = (
isinstance(renderer, Gemma4Renderer)
and getattr(renderer.config, "enable_thinking", True) is False
and case_id
in (
"multi_turn_two_images",
"tool_response_with_image",
"multi_turn_tool_response_images",
"consecutive_tools_mixed_media",
)
)
return qwen_deviation or gemma4_deviation
def _supports_tool_message_images(renderer) -> bool:
"""True iff this renderer emits image placeholders inside tool-response
content. Renderers without the feature silently drop image parts in tool
content; as they grow the feature they get added here and the test starts
asserting against them."""
from renderers.gemma4 import Gemma4Renderer
from renderers.kimi_k25 import KimiK25Renderer
from renderers.nemotron3 import Nemotron35Renderer
from renderers.qwen35 import Qwen35Renderer
return isinstance(renderer, (Qwen35Renderer, KimiK25Renderer))
return isinstance(
renderer,
(Qwen35Renderer, KimiK25Renderer, Gemma4Renderer, Nemotron35Renderer),
)
@pytest.mark.parametrize(
@@ -463,9 +631,12 @@ def test_multimodal_byte_parity_vs_processor(mm_model_name, modality, tiny_image
kit = _modality_kit(modality, mm_model_name)
tokenizer, processor, renderer = _load_processor_and_renderer(mm_model_name)
sample = _sample_for(modality, tiny_image)
for case in _build_cases(kit["make_part"], tiny_image):
for case in _build_cases(kit["make_part"], sample):
messages, add_gp = case.values
if _skip_for_disabled_thinking_deviation(renderer, case.id):
continue
# Ours.
ours = renderer.render_ids(messages, add_generation_prompt=add_gp)
@@ -494,8 +665,9 @@ def test_multimodal_placeholders_match_pad_runs(mm_model_name, modality, tiny_im
kit = _modality_kit(modality, mm_model_name)
tokenizer, _, renderer = _load_processor_and_renderer(mm_model_name)
pad_id = tokenizer.convert_tokens_to_ids(kit["placeholder_token"])
sample = _sample_for(modality, tiny_image)
for case in _build_cases(kit["make_part"], tiny_image):
for case in _build_cases(kit["make_part"], sample):
messages, add_gp = case.values
rendered = renderer.render(messages, add_generation_prompt=add_gp)
@@ -560,14 +732,17 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
tokenizer,
_config_for_model(mm_model_name, thinking_retention="all"),
)
if not getattr(renderer, "supports_multimodal_bridge", True):
pytest.skip(f"{type(renderer).__name__} uses full multimodal re-rendering")
if hasattr(renderer, "_processor") and renderer._processor is None:
renderer._processor = processor
sample = _sample_for(modality, tiny_image)
initial = [
{
"role": "user",
"content": [
kit["make_part"](tiny_image),
kit["make_part"](sample),
{"type": "text", "text": "Turn one."},
],
}
@@ -576,7 +751,7 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
{
"role": "user",
"content": [
kit["make_part"](tiny_image),
kit["make_part"](sample),
{"type": "text", "text": "Turn two."},
],
}
@@ -589,11 +764,15 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
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|>``.
im_end_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
completion_ids = tokenizer.encode("Saw it.", add_special_tokens=False) + [im_end_id]
# ``previous_completion_ids`` mirrors what a sampler would emit starting
# AFTER the prompt's assistant opener — response text then the renderer's
# own turn-close token.
close_id = renderer.get_stop_token_ids()[0]
# A thinking-prefilled prompt requires a sampled reasoning close before
# final content. Otherwise this fixture would be EOS inside reasoning.
prefix = tokenizer.decode(initial_rendered.token_ids, skip_special_tokens=False)
response = "</think>Saw it." if prefix.rstrip().endswith("<think>") else "Saw it."
completion_ids = tokenizer.encode(response, add_special_tokens=False) + [close_id]
bridged_raw = renderer.bridge_to_next_turn(
previous_prompt_ids=initial_rendered.token_ids,
@@ -665,6 +844,56 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
)
def test_inkling_bridge_does_not_mutate_prior_mm_data(tiny_image):
"""Bridging must not mutate the caller's ``previous_multi_modal_data`` —
the merge copies the per-modality lists, not just the outer dict, so a
carried-forward image doesn't grow the prior turn's list in place."""
model = "thinkingmachines/Inkling"
if not _hf_snapshot_cached(model):
pytest.skip(f"{model}: HF snapshot not cached locally")
_, processor, renderer = _load_processor_and_renderer(model)
initial = [
{
"role": "user",
"content": [
_image_content_part(tiny_image),
{"type": "text", "text": "Turn one."},
],
}
]
rendered = renderer.render(initial, add_generation_prompt=True)
prior = rendered.multi_modal_data
assert prior is not None and len(prior.mm_placeholders["image"]) == 1
close_id = renderer.get_stop_token_ids()[0]
completion_ids = processor.tokenizer.encode("Saw it.", add_special_tokens=False) + [
close_id
]
new = [
{
"role": "user",
"content": [
_image_content_part(tiny_image),
{"type": "text", "text": "Turn two."},
],
}
]
bridged = renderer.bridge_to_next_turn(
rendered.token_ids,
completion_ids,
new,
previous_multi_modal_data=prior,
)
assert bridged is not None
# The prior sidecar is unchanged; the bridged one carries both images.
assert len(prior.mm_placeholders["image"]) == 1
assert len(prior.mm_hashes["image"]) == 1
assert len(prior.mm_items["image"]) == 1
assert len(bridged.multi_modal_data.mm_placeholders["image"]) == 2
def test_modality_registry_models_route_to_renderer():
"""Every model in ``MULTIMODAL_MODELS`` resolves to a concrete renderer
via ``create_renderer(renderer='auto')``. Guards against drift between
@@ -709,6 +938,8 @@ def test_tool_response_image_byte_parity(mm_model_name, modality, tiny_image):
for case in _build_tool_image_cases(kit["make_part"], tiny_image):
messages, add_gp = case.values
if _skip_for_disabled_thinking_deviation(renderer, case.id):
continue
ours = renderer.render_ids(messages, add_generation_prompt=add_gp)
theirs = kit["processor_input_ids"](processor, messages, add_gp)
assert ours == theirs, (
@@ -796,6 +1027,8 @@ def test_add_vision_id_parity_vs_processor(
for case in _build_cases(kit["make_part"], tiny_image):
messages, add_gp = case.values
if _skip_for_disabled_thinking_deviation(renderer, case.id):
continue
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
@@ -868,7 +1101,9 @@ def test_bridge_refuses_when_add_vision_id_loses_prior_count(
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]
prefix = tokenizer.decode(initial_rendered.token_ids, skip_special_tokens=False)
response = "</think>Saw it." if prefix.rstrip().endswith("<think>") else "Saw it."
completion_ids = tokenizer.encode(response, 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
@@ -945,3 +1180,8 @@ def test_is_image_part_treats_type_field_as_authoritative():
assert not _is_image_part({"image_url": None})
assert not _is_image_part({"image": None})
assert not _is_video_part({"video_url": None})
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_loaded.clear()
+322
View File
@@ -0,0 +1,322 @@
"""Focused multimodal tests for the private Nemotron 3.5 Super checkpoint."""
from __future__ import annotations
import os
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from renderers.base import MODEL_RENDERER_MAP, MULTIMODAL_MODELS, PlaceholderRange
from renderers.nemotron3 import Nemotron35Renderer
MODEL = "nvidia/NVIDIA-Nemotron-3.5-Super-EA-09112026"
class _Tokenizer:
name_or_path = MODEL
unk_token_id = -1
eos_token_id = 2
_specials = {
"<|im_start|>": 1,
"<|im_end|>": 2,
"<|endoftext|>": 3,
"<think>": 4,
"</think>": 5,
"<tool_call>": 6,
"</tool_call>": 7,
"<tool_response>": 8,
"</tool_response>": 9,
"<img>": 10,
"</img>": 11,
"<image>": 18,
}
def convert_tokens_to_ids(self, token: str) -> int:
return self._specials.get(token, self.unk_token_id)
def encode(self, text: str, *, add_special_tokens: bool = False) -> list[int]:
assert not add_special_tokens
token_ids: list[int] = []
index = 0
specials = sorted(self._specials, key=len, reverse=True)
while index < len(text):
special = next(
(value for value in specials if text.startswith(value, index)), None
)
if special is not None:
token_ids.append(self._specials[special])
index += len(special)
else:
token_ids.append(1000 + ord(text[index]))
index += 1
return token_ids
def decode(self, token_ids: list[int], **_: Any) -> str:
reverse_specials = {value: key for key, value in self._specials.items()}
return "".join(
reverse_specials[token_id]
if token_id in reverse_specials
else chr(token_id - 1000)
for token_id in token_ids
)
class _ImageProcessor:
def __init__(self) -> None:
self.calls = 0
def __call__(self, *, images: list[Any], return_tensors: str):
assert len(images) == 1
assert return_tensors == "np"
self.calls += 1
return {
"pixel_values": [[[[0.0]]]],
"num_tokens": [3],
"num_patches": [1],
"imgs_sizes": [(1, 1)],
}
def test_private_super_is_registered_as_image_model():
assert MODEL_RENDERER_MAP[MODEL] == "nemotron-3.5"
assert MULTIMODAL_MODELS[MODEL] == {"image"}
def test_image_content_expands_and_attaches_only_model_inputs():
Image = pytest.importorskip("PIL.Image")
image = Image.new("RGB", (4, 3), color=(10, 20, 30))
image_processor = _ImageProcessor()
processor = SimpleNamespace(image_processor=image_processor)
renderer = Nemotron35Renderer(_Tokenizer(), processor=processor)
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What is shown? "},
{"type": "image", "image": image},
{"type": "text", "text": " Be concise."},
],
}
]
rendered = renderer.render(messages, add_generation_prompt=True)
assert messages[0]["content"][1]["image"] is image
assert image_processor.calls == 1
assert renderer.mm_token_type_id_map == {18: 1}
assert rendered.multi_modal_data is not None
assert rendered.multi_modal_data.mm_hashes.keys() == {"image"}
assert len(rendered.multi_modal_data.mm_hashes["image"]) == 1
placeholder = rendered.multi_modal_data.mm_placeholders["image"]
assert placeholder == [PlaceholderRange(offset=placeholder[0].offset, length=3)]
assert rendered.token_ids[placeholder[0].offset : placeholder[0].offset + 3] == [
18,
18,
18,
]
assert rendered.multi_modal_data.mm_items == {
"image": [
{
"pixel_values": [[[[0.0]]]],
"num_tokens": [3],
"num_patches": [1],
"imgs_sizes": [(1, 1)],
}
]
}
def test_deferred_multimodal_processing_keeps_one_logical_image_token():
Image = pytest.importorskip("PIL.Image")
image = Image.new("RGB", (2, 2))
renderer = Nemotron35Renderer(
_Tokenizer(), processor=SimpleNamespace(image_processor=_ImageProcessor())
)
rendered = renderer.render(
[{"role": "user", "content": [{"type": "image", "image": image}]}],
process_multimodal=False,
)
assert rendered.token_ids.count(18) == 1
assert rendered.multi_modal_data is None
def test_two_images_produce_two_distinct_placeholder_ranges():
Image = pytest.importorskip("PIL.Image")
renderer = Nemotron35Renderer(
_Tokenizer(), processor=SimpleNamespace(image_processor=_ImageProcessor())
)
rendered = renderer.render(
[
{
"role": "user",
"content": [
{"type": "image", "image": Image.new("RGB", (2, 2))},
{"type": "text", "text": "compare"},
{"type": "image", "image": Image.new("RGB", (3, 2))},
],
}
]
)
assert rendered.multi_modal_data is not None
placeholders = rendered.multi_modal_data.mm_placeholders["image"]
assert [placeholder.length for placeholder in placeholders] == [3, 3]
assert placeholders[0].offset + placeholders[0].length < placeholders[1].offset
assert len(rendered.multi_modal_data.mm_items["image"]) == 2
def test_multimodal_bridge_uses_full_rerender_fallback():
renderer = Nemotron35Renderer(_Tokenizer())
assert not renderer.supports_multimodal_bridge
assert (
renderer.bridge_to_next_turn(
[1],
[2],
[{"role": "user", "content": [{"type": "image", "image": object()}]}],
)
is None
)
def test_text_only_nemotron35_tokenizer_does_not_need_image_token():
class _TextTokenizer(_Tokenizer):
_specials = {
key: value
for key, value in _Tokenizer._specials.items()
if key != "<image>"
}
renderer = Nemotron35Renderer(_TextTokenizer())
assert renderer.mm_token_type_id_map == {}
assert renderer.render_ids([{"role": "user", "content": "Hello"}])
@pytest.mark.parametrize(
"source",
[
"https://example.test/image.png",
"file:///tmp/image.png",
"/tmp/image.png",
],
)
def test_nemotron35_rejects_network_and_filesystem_image_sources(source):
renderer = Nemotron35Renderer(
_Tokenizer(), processor=SimpleNamespace(image_processor=_ImageProcessor())
)
with pytest.raises(ValueError, match="in-memory images or data:image"):
renderer.render(
[
{
"role": "user",
"content": [{"type": "image_url", "image_url": {"url": source}}],
}
]
)
def test_nemotron35_rejects_unpinned_remote_processor(monkeypatch):
class _RemoteTokenizer(_Tokenizer):
name_or_path = "example/unreviewed-model"
monkeypatch.setattr(
"renderers.nemotron3._require_transformers",
lambda _: pytest.fail(
"unknown remote model must fail before transformers load"
),
)
renderer = Nemotron35Renderer(_RemoteTokenizer())
with pytest.raises(RuntimeError, match="not approved for remote-code loading"):
renderer._get_processor()
def test_nemotron35_rejects_unapproved_local_processor(tmp_path, monkeypatch):
class _LocalTokenizer(_Tokenizer):
name_or_path = str(tmp_path)
monkeypatch.setattr(
"renderers.nemotron3._require_transformers",
lambda _: pytest.fail("unapproved local model must fail before load"),
)
with pytest.raises(RuntimeError, match="explicitly injected reviewed processor"):
Nemotron35Renderer(_LocalTokenizer())._get_processor()
def test_nemotron35_loads_approved_remote_processor_without_revision(monkeypatch):
calls = []
expected = object()
transformers = SimpleNamespace(
AutoProcessor=SimpleNamespace(
from_pretrained=lambda name, **kwargs: (
calls.append((name, kwargs)) or expected
)
)
)
monkeypatch.setattr(
"renderers.nemotron3._require_transformers", lambda _: transformers
)
assert Nemotron35Renderer(_Tokenizer())._get_processor() is expected
assert calls == [
(
MODEL,
{"trust_remote_code": True},
)
]
def test_real_processor_token_parity_when_metadata_is_available():
metadata = os.environ.get("NEMOTRON35_VLM_METADATA")
if metadata is None:
pytest.skip("set NEMOTRON35_VLM_METADATA to the downloaded model metadata")
metadata_path = Path(metadata)
if not metadata_path.is_dir():
pytest.skip(f"Nemotron metadata directory does not exist: {metadata_path}")
Image = pytest.importorskip("PIL.Image")
transformers = pytest.importorskip("transformers")
tokenizer = transformers.AutoTokenizer.from_pretrained(metadata_path)
processor = transformers.AutoProcessor.from_pretrained(
metadata_path, trust_remote_code=True
)
renderer = Nemotron35Renderer(tokenizer, processor=processor)
images = [
Image.new("RGB", (2048, 256), color=(10, 20, 30)),
Image.new("RGB", (256, 2048), color=(30, 20, 10)),
]
for selected_images in (images[:1], images):
content = [{"type": "text", "text": "Describe: "}]
content.extend({"type": "image", "image": image} for image in selected_images)
messages = [{"role": "user", "content": content}]
rendered = renderer.render(messages, add_generation_prompt=True)
prompt = processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
expected = processor(
images=selected_images,
text=prompt,
return_tensors=None,
)["input_ids"][0]
assert rendered.token_ids == expected
assert rendered.multi_modal_data is not None
assert len(rendered.multi_modal_data.mm_items["image"]) == len(selected_images)
if len(selected_images) == 2:
shapes = [
tuple(item["pixel_values"].shape)
for item in rendered.multi_modal_data.mm_items["image"]
]
assert shapes[0] != shapes[1]
-676
View File
@@ -1,676 +0,0 @@
"""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
+32 -7
View File
@@ -1,4 +1,4 @@
"""Offline wiring tests for the Nemotron-3 variant split.
"""Offline wiring tests for the Nemotron 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
@@ -6,15 +6,16 @@ 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:
The three 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``.
* ``nemotron-3.5`` — Lightning, Ultra's glue but no effort kwarg at all.
Both route to the one ``Nemotron3Renderer`` class, which selects the variant
from ``config.name``.
All route to the one ``Nemotron3Renderer`` implementation via per-variant
subclasses.
"""
from types import SimpleNamespace
@@ -23,9 +24,15 @@ from renderers.base import MODEL_RENDERER_MAP, RENDERER_REGISTRY, _populate_regi
from renderers.configs import (
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
Nemotron35RendererConfig,
_config_class_for,
)
from renderers.nemotron3 import Nemotron3Renderer, Nemotron3UltraRenderer, _is_super
from renderers.nemotron3 import (
Nemotron3Renderer,
Nemotron3UltraRenderer,
Nemotron35Renderer,
_is_super,
)
_ULTRA_REPOS = [
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
@@ -35,6 +42,9 @@ _NANO_SUPER_REPOS = [
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
]
_LIGHTNING_REPOS = [
"nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16",
]
def _fake_tok(name):
@@ -46,18 +56,23 @@ def test_models_map_to_their_variant():
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
for repo in _LIGHTNING_REPOS:
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3.5", 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).
assert _config_class_for("nemotron-3.5") is Nemotron35RendererConfig
# Registry → renderer class (Ultra / 3.5 are sibling subclasses, matching
# the GLM-5/5.1 and Qwen3.5/3.6 house style — not one class under N names).
_populate_registry()
assert RENDERER_REGISTRY["nemotron-3"] is Nemotron3Renderer
assert RENDERER_REGISTRY["nemotron-3-ultra"] is Nemotron3UltraRenderer
assert RENDERER_REGISTRY["nemotron-3.5"] is Nemotron35Renderer
assert issubclass(Nemotron3UltraRenderer, Nemotron3Renderer)
assert issubclass(Nemotron35Renderer, Nemotron3Renderer)
def test_variant_is_encoded_by_the_class():
@@ -66,8 +81,10 @@ def test_variant_is_encoded_by_the_class():
# config.name → class). Default config also follows the class.
assert Nemotron3Renderer._ultra is False
assert Nemotron3UltraRenderer._ultra is True
assert Nemotron35Renderer._ultra is True
assert Nemotron3Renderer._config_cls is Nemotron3RendererConfig
assert Nemotron3UltraRenderer._config_cls is Nemotron3UltraRendererConfig
assert Nemotron35Renderer._config_cls is Nemotron35RendererConfig
def test_template_fields_per_variant():
@@ -80,6 +97,10 @@ def test_template_fields_per_variant():
assert Nemotron3UltraRendererConfig.template_field_names() == frozenset(
{"enable_thinking", "truncate_history_thinking", "medium_effort"}
)
# Lightning's template defines no effort variable at all.
assert Nemotron35RendererConfig.template_field_names() == frozenset(
{"enable_thinking", "truncate_history_thinking"}
)
def test_configs_reject_the_other_variants_effort_kwarg():
@@ -91,6 +112,10 @@ def test_configs_reject_the_other_variants_effort_kwarg():
Nemotron3RendererConfig(medium_effort=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
Nemotron3UltraRendererConfig(low_effort=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
Nemotron35RendererConfig(low_effort=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
Nemotron35RendererConfig(medium_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]
+223
View File
@@ -0,0 +1,223 @@
"""Renderer-wide contract tests for BYO tokenizers without character offsets."""
from __future__ import annotations
from typing import Any
import pytest
from renderers import create_renderer
from renderers.base import load_tokenizer
class OffsetlessTokenizer:
"""Delegate the basic tokenizer protocol without exposing ``__call__``."""
def __init__(self, tokenizer: Any):
self._tokenizer = tokenizer
def __getattr__(self, name: str) -> Any:
if name == "__call__":
raise AttributeError(name)
return getattr(self._tokenizer, name)
def encode(self, *args: Any, **kwargs: Any) -> list[int]:
return self._tokenizer.encode(*args, **kwargs)
def decode(self, *args: Any, **kwargs: Any) -> str:
return self._tokenizer.decode(*args, **kwargs)
def convert_tokens_to_ids(self, *args: Any, **kwargs: Any) -> Any:
return self._tokenizer.convert_tokens_to_ids(*args, **kwargs)
def apply_chat_template(self, *args: Any, **kwargs: Any) -> Any:
return self._tokenizer.apply_chat_template(*args, **kwargs)
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
CASES = [
pytest.param(
[
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "Hello!"},
],
None,
True,
id="system-generation-prompt",
),
pytest.param(
[
{"role": "system", "content": "You are a weather assistant."},
{"role": "user", "content": "Weather?"},
],
TOOLS,
False,
id="system-and-tools",
),
pytest.param(
[
{"role": "user", "content": "What is 2+2?"},
{
"role": "assistant",
"reasoning_content": "Simple arithmetic",
"content": "4",
},
{"role": "user", "content": "And 3+3?"},
],
None,
True,
id="reasoning-history",
),
pytest.param(
[
{"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}'},
{"role": "assistant", "content": "It is 20 degrees."},
],
TOOLS,
False,
id="full-tool-cycle",
),
]
def _offsetless_renderer(renderer: Any) -> Any:
return type(renderer)(OffsetlessTokenizer(renderer._tokenizer), renderer.config)
def _assert_offsetless_contract(expected: Any, actual: Any, renderer: Any) -> None:
assert actual.token_ids == expected.token_ids
assert actual.message_indices == expected.message_indices
if type(renderer).__name__ == "PrimeQwen3Renderer":
assert actual.sampled_mask == []
else:
assert actual.sampled_mask == expected.sampled_mask
assert actual.is_content == []
assert actual.message_roles == expected.message_roles
assert actual.message_tool_names == expected.message_tool_names
assert actual.multi_modal_data == expected.multi_modal_data
@pytest.mark.parametrize("messages,tools,add_generation_prompt", CASES)
def test_offsetless_contract_across_renderer_matrix(
model_name: str,
renderer: Any,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None,
add_generation_prompt: bool,
) -> None:
"""Every configured renderer preserves tokens and non-content metadata."""
expected = renderer.render(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
)
offsetless = _offsetless_renderer(renderer)
actual = offsetless.render(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
)
_assert_offsetless_contract(expected, actual, renderer)
def test_offsetless_contract_across_renderer_bridges(
model_name: str,
renderer: Any,
) -> None:
"""Bridge paths preserve their tokens and metadata without offsets."""
prior_messages = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi!"},
]
new_messages = [{"role": "user", "content": "Tell me more."}]
prior = renderer.render(prior_messages)
offsetless = _offsetless_renderer(renderer)
expected = renderer.bridge_to_next_turn(
prior.token_ids,
[],
new_messages,
)
actual = offsetless.bridge_to_next_turn(
prior.token_ids,
[],
new_messages,
)
assert (actual is None) == (expected is None)
if expected is not None and actual is not None:
_assert_offsetless_contract(expected, actual, renderer)
def test_hy3_offsetless_preserves_multiple_system_message_indices() -> None:
"""Hy3's joined system header must not erase either caller message."""
tokenizer = load_tokenizer("tencent/Hy3")
renderer = create_renderer(tokenizer)
messages = [
{"role": "system", "content": "First instruction."},
{"role": "system", "content": "Second instruction."},
{"role": "user", "content": "Hello"},
]
expected = renderer.render(messages, tools=TOOLS)
actual = _offsetless_renderer(renderer).render(messages, tools=TOOLS)
_assert_offsetless_contract(expected, actual, renderer)
assert {0, 1}.issubset(actual.message_indices)
@pytest.mark.parametrize(
"deepseek_model",
["deepseek-ai/DeepSeek-V3", "deepseek-ai/DeepSeek-R1"],
)
def test_deepseek_offsetless_contract(deepseek_model: str) -> None:
"""DeepSeek variants live outside the shared parity matrix."""
tokenizer = load_tokenizer(deepseek_model)
renderer = create_renderer(tokenizer)
messages = [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
]
expected = renderer.render(messages, add_generation_prompt=True)
actual = _offsetless_renderer(renderer).render(
messages,
add_generation_prompt=True,
)
_assert_offsetless_contract(expected, actual, renderer)
+230
View File
@@ -0,0 +1,230 @@
"""Unified renderer parity matrix.
Every valid cell is the product of one model, one shared conversation
scenario, and all explicit reference-controlled values accepted by that
model's typed config. Unsupported cells are excluded declaratively in the
model catalog rather than discovered at runtime through skips or xfails. The
reference is model-aware: most models use Hugging Face Jinja, DeepSeek V4 uses
its shipped Python encoder, and GPT-OSS uses Harmony.
"""
from __future__ import annotations
from enum import Enum
from functools import lru_cache
from types import UnionType
from typing import Annotated, Any, Literal, Mapping, Union, cast, get_args, get_origin
import pytest
from parity import (
KWARG_VALUES,
MODEL_CATALOG,
SCENARIOS,
ModelCase,
Scenario,
kwarg_combinations,
scenario_is_valid,
)
from renderers import create_renderer
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
from renderers.configs import RendererConfig, _config_class_for
from tests.reference_rendering import (
DEFAULT_REFERENCE_ORACLE,
REFERENCE_ORACLES,
RENDERER_ORACLE_ROUTES,
reference_oracle_for_model,
reference_oracle_for_renderer,
render_reference,
)
def _id(case: ModelCase, scenario: Scenario, kwargs: Mapping[str, Any]) -> str:
values = ",".join(f"{key}={value!r}" for key, value in kwargs.items())
suffix = values or "defaults"
return f"{case.model}-{scenario.id}-{suffix}"
def _matrix():
for case in MODEL_CATALOG:
for kwargs in kwarg_combinations(case):
for scenario in SCENARIOS:
if scenario_is_valid(case, scenario, kwargs):
yield pytest.param(
case,
scenario,
kwargs,
id=_id(case, scenario, kwargs),
)
# The matrix groups all scenarios/settings for each checkpoint together.
# Retain only the current checkpoint and configuration, not the whole catalog.
@lru_cache(maxsize=1)
def _tokenizer(model: str):
return load_tokenizer(model)
@lru_cache(maxsize=1)
def _renderer(model: str, renderer_name: str, items: tuple[tuple[str, Any], ...]):
tokenizer = _tokenizer(model)
resolved = (
MODEL_RENDERER_MAP.get(model, "default")
if renderer_name == "auto"
else renderer_name
)
config = cast(RendererConfig, _config_class_for(resolved)())
kwargs = dict(items)
return create_renderer(tokenizer, config, chat_template_kwargs=kwargs or None)
def _required_annotation_values(annotation: Any) -> tuple[Any, ...]:
"""Return every finite value explicitly declared by a field annotation.
Open domains such as ``str`` and ``float`` intentionally contribute no
values; ``KWARG_VALUES`` still supplies representative samples for them.
Finite branches (``Literal``, ``Enum``, ``bool``, and ``None``) are
exhaustive, even when nested inside ``Annotated`` or a union with an open
domain.
"""
origin = get_origin(annotation)
if origin is Annotated:
return _required_annotation_values(get_args(annotation)[0])
if origin is Literal:
return get_args(annotation)
if annotation is bool:
return (True, False)
if annotation is type(None):
return (None,)
if isinstance(annotation, type) and issubclass(annotation, Enum):
return tuple(member.value for member in annotation)
if origin in {Union, UnionType}:
return tuple(
value
for member in get_args(annotation)
for value in _required_annotation_values(member)
)
return ()
def test_catalog_covers_every_declared_kwarg():
declared = {
field
for case in MODEL_CATALOG
for field in _config_class_for(case.resolved_renderer).template_field_names()
}
assert declared <= KWARG_VALUES.keys()
def test_catalog_covers_every_finite_declared_kwarg_value():
missing = []
config_classes = {
_config_class_for(case.resolved_renderer) for case in MODEL_CATALOG
}
for config_cls in sorted(config_classes, key=lambda cls: cls.__name__):
for field in sorted(config_cls.template_field_names()):
annotation = config_cls.model_fields[field].annotation
absent = tuple(
value
for value in _required_annotation_values(annotation)
if value not in KWARG_VALUES[field]
)
if absent:
missing.append(f"{config_cls.__name__}.{field}: {absent!r}")
assert not missing, "KWARG_VALUES omits declared finite values:\n" + "\n".join(
missing
)
def test_oracle_routes_resolve_to_registered_adapters():
assert DEFAULT_REFERENCE_ORACLE in REFERENCE_ORACLES
assert set(RENDERER_ORACLE_ROUTES.values()) <= REFERENCE_ORACLES.keys()
assert all(name == oracle.name for name, oracle in REFERENCE_ORACLES.items())
for renderer_name in RENDERER_ORACLE_ROUTES:
_config_class_for(renderer_name)
for case in MODEL_CATALOG:
assert case.oracle == reference_oracle_for_renderer(case.resolved_renderer)
@pytest.mark.parametrize(
("model", "oracle"),
(
("deepseek-ai/DeepSeek-V4-Flash-0731", "deepseek-v4"),
("openai/gpt-oss-20b", "harmony"),
("openai/gpt-oss-120b", "harmony"),
("unmapped/example", DEFAULT_REFERENCE_ORACLE),
),
)
def test_model_oracle_routing(model: str, oracle: str):
assert reference_oracle_for_model(model) == oracle
def test_catalog_routes_every_auto_model_to_its_declared_renderer():
for case in MODEL_CATALOG:
if case.renderer == "auto":
assert case.model in MODEL_RENDERER_MAP
@pytest.mark.parametrize(
"model",
(
"Qwen/Qwen3.6-35B-A3B",
"Qwen/Qwen3.8-27B",
"Qwen/Qwen3.8-Flash-Next",
),
)
def test_preserved_disabled_thinking_history_remains_in_parity_matrix(model: str):
case = next(case for case in MODEL_CATALOG if case.model == model)
scenario = next(scenario for scenario in SCENARIOS if scenario.id == "multi-turn")
assert scenario_is_valid(
case,
scenario,
{"enable_thinking": False, "preserve_thinking": True},
)
assert not scenario_is_valid(
case,
scenario,
{"enable_thinking": False, "preserve_thinking": False},
)
@pytest.mark.parametrize("case,scenario,kwargs", tuple(_matrix()))
def test_renderer_matches_reference(
case: ModelCase,
scenario: Scenario,
kwargs: Mapping[str, Any],
):
tokenizer = _tokenizer(case.model)
renderer = _renderer(case.model, case.renderer, tuple(kwargs.items()))
for key, value in kwargs.items():
if value is not None:
assert getattr(renderer.config, key) == value
oracle_kwargs = dict(case.oracle_defaults)
oracle_kwargs.update(kwargs)
# Config ``None`` values mean "defer to the oracle default"; omission
# expresses the same state for every registered adapter.
oracle_kwargs = {
key: value for key, value in oracle_kwargs.items() if value is not None
}
expected = render_reference(
tokenizer,
[dict(message) for message in scenario.messages],
oracle=case.oracle,
**oracle_kwargs,
**scenario.render_kwargs,
)
got = renderer.render_ids(list(scenario.messages), **scenario.render_kwargs)
assert got == expected, (
f"{case.model} / {scenario.id} / {dict(kwargs)!r}: renderer diverged "
f"from {case.oracle} oracle (got {len(got)} tokens, expected "
f"{len(expected)})"
)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_tokenizer.cache_clear()
_renderer.cache_clear()
+97 -13
View File
@@ -6,6 +6,7 @@ Runs against every (model, renderer) pair.
from functools import lru_cache
import pytest
from renderers import create_renderer
from renderers.base import ToolCallParseStatus, load_tokenizer
@@ -18,18 +19,18 @@ def _qwen3_vl():
def test_parse_simple_content(model_name, tokenizer, renderer):
"""Plain content, no thinking."""
"""Bare text survives in the format's initial channel."""
text = "Hello there!"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert "Hello" in parsed.content
parsed = renderer.parse_response(ids, prompt_ids=[])
assert "Hello" in parsed.content + (parsed.reasoning_content or "")
def test_parse_thinking_and_content(model_name, tokenizer, renderer):
"""Content with <think>reasoning</think> block."""
text = "Let me think about this.\n</think>\n\nThe answer is 42."
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
# Should extract reasoning or at least not crash
assert (
"42" in parsed.content
@@ -40,14 +41,14 @@ def test_parse_thinking_and_content(model_name, tokenizer, renderer):
def test_parse_empty_completion(model_name, tokenizer, renderer):
"""Empty completion should not crash."""
parsed = renderer.parse_response([])
parsed = renderer.parse_response([], prompt_ids=[])
assert parsed.content is not None
def test_parse_response_returns_parsed_response(model_name, tokenizer, renderer):
"""Return type must have content, reasoning_content, tool_calls."""
ids = tokenizer.encode("Hello!", add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert hasattr(parsed, "content")
assert hasattr(parsed, "reasoning_content")
assert hasattr(parsed, "tool_calls")
@@ -59,7 +60,9 @@ def test_qwen3_vl_parse_json_tool_call():
'Need a tool.\n<tool_call>\n{"name": "get_weather", '
'"arguments": {"city": "Paris"}}\n</tool_call>'
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
parsed = renderer.parse_response(
tokenizer.encode(text, add_special_tokens=False), prompt_ids=[]
)
assert parsed.content == "Need a tool."
assert len(parsed.tool_calls) == 1
@@ -89,7 +92,9 @@ def test_qwen3_vl_malformed_tool_call_surfaces_as_invalid_json():
'<tool_call>\n{"name": "get_weather", '
'"arguments": {"city": "Paris",}}\n</tool_call>'
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
parsed = renderer.parse_response(
tokenizer.encode(text, add_special_tokens=False), prompt_ids=[]
)
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
@@ -105,6 +110,68 @@ def _qwen3():
return tokenizer, renderer
@lru_cache
def _prime_qwen3(model: str):
tokenizer = load_tokenizer(model)
return tokenizer, create_renderer(tokenizer)
@pytest.mark.parametrize(
"model",
["PrimeIntellect/Qwen3-0.6B", "PrimeIntellect/Qwen3-1.7B"],
)
def test_prime_qwen3_empty_think_roundtrips_through_bridge(model):
"""Present-but-empty reasoning must survive parse → bridge → rerender.
Collapsing an emitted ``<think></think>`` block to ``None`` drops the
block from stored messages and makes every later rerender diverge from
the sampled token stream.
"""
tokenizer, renderer = _prime_qwen3(model)
stop = renderer.get_stop_token_ids()[0]
prompt = [{"role": "user", "content": "Reverse abc"}]
prompt_ids = renderer.render_ids(prompt, add_generation_prompt=True)
full = tokenizer.encode(
tokenizer.decode(prompt_ids) + "<think></think>\ncba",
add_special_tokens=False,
)
assert full[: len(prompt_ids)] == prompt_ids
completion_ids = full[len(prompt_ids) :] + [stop]
parsed = renderer.parse_response(completion_ids, prompt_ids=[])
assert parsed.reasoning_content == ""
assert parsed.content == "cba"
assistant = {
"role": "assistant",
"content": parsed.content,
"reasoning_content": parsed.reasoning_content,
}
reminder = {"role": "user", "content": "Now reverse def"}
bridged = renderer.bridge_to_next_turn(prompt_ids, completion_ids, [reminder])
assert bridged is not None
assert bridged.token_ids == renderer.render_ids(
[*prompt, assistant, reminder], add_generation_prompt=True
)
@pytest.mark.parametrize(
"model",
["PrimeIntellect/Qwen3-0.6B", "PrimeIntellect/Qwen3-1.7B"],
)
def test_prime_qwen3_absent_think_stays_none(model):
"""A completion without a think block must not invent empty reasoning."""
tokenizer, renderer = _prime_qwen3(model)
stop = renderer.get_stop_token_ids()[0]
completion_ids = tokenizer.encode("cba", add_special_tokens=False) + [stop]
parsed = renderer.parse_response(completion_ids, prompt_ids=[])
assert parsed.reasoning_content is None
assert parsed.content == "cba"
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.
@@ -125,7 +192,9 @@ def test_qwen3_in_think_tool_call_is_not_a_real_call():
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
"</tool_call>"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
parsed = renderer.parse_response(
tokenizer.encode(text, add_special_tokens=False), prompt_ids=[]
)
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
@@ -151,7 +220,9 @@ def test_qwen3_distinct_parallel_calls_after_think_are_preserved():
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(2)"}}\n'
"</tool_call>"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
parsed = renderer.parse_response(
tokenizer.encode(text, add_special_tokens=False), prompt_ids=[]
)
assert len(parsed.tool_calls) == 2
assert [tc.arguments for tc in parsed.tool_calls] == [
@@ -186,7 +257,7 @@ def test_kimi_k25_tool_call_carries_token_span():
"<|tool_calls_section_end|>"
)
token_ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(token_ids)
parsed = renderer.parse_response(token_ids, prompt_ids=[])
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
@@ -217,7 +288,9 @@ def test_kimi_k25_in_think_section_is_not_a_real_call():
"<|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))
parsed = renderer.parse_response(
tokenizer.encode(text, add_special_tokens=False), prompt_ids=[]
)
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
@@ -258,7 +331,9 @@ def test_deepseek_v3_in_think_section_is_not_a_real_call():
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))
parsed = renderer.parse_response(
tokenizer.encode(text, add_special_tokens=False), prompt_ids=[]
)
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
@@ -274,3 +349,12 @@ def test_deepseek_v3_in_think_section_is_not_a_real_call():
assert parsed.reasoning_content is not None
assert "draft_tool" in parsed.reasoning_content
assert parsed.content == "Go."
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_qwen3_vl.cache_clear()
_qwen3.cache_clear()
_prime_qwen3.cache_clear()
_kimi_k25.cache_clear()
_deepseek_v3.cache_clear()
+18 -19
View File
@@ -6,7 +6,6 @@ even with adversarial or truncated model output.
from renderers.base import ParsedResponse, ParsedToolCall
# ── Truncation ───────────────────────────────────────────────────────
@@ -14,7 +13,7 @@ def test_truncated_mid_thinking(model_name, tokenizer, renderer):
"""Model was cut off mid-thinking (no </think> found)."""
text = "Let me think about this carefully. The problem requires"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert isinstance(parsed, ParsedResponse)
# Content or reasoning should contain the text
assert parsed.content or parsed.reasoning_content
@@ -24,7 +23,7 @@ def test_truncated_after_think_tag(model_name, tokenizer, renderer):
"""Model emitted <think> but was cut off before </think>."""
text = "<think>Let me reason about"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert isinstance(parsed, ParsedResponse)
@@ -32,7 +31,7 @@ def test_truncated_mid_tool_call(model_name, tokenizer, renderer):
"""Model started a tool call but was cut off."""
text = 'Checking the weather.\n<tool_call>\n{"name": "get'
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert isinstance(parsed, ParsedResponse)
# Should recover content before the tool call
assert "Checking" in parsed.content or parsed.content == ""
@@ -40,7 +39,7 @@ def test_truncated_mid_tool_call(model_name, tokenizer, renderer):
def test_empty_completion(model_name, tokenizer, renderer):
"""Empty token list."""
parsed = renderer.parse_response([])
parsed = renderer.parse_response([], prompt_ids=[])
assert isinstance(parsed, ParsedResponse)
assert parsed.content is not None
@@ -49,7 +48,7 @@ def test_single_eos_token(model_name, tokenizer, renderer):
"""Just an EOS token."""
stop_ids = renderer.get_stop_token_ids()
if stop_ids:
parsed = renderer.parse_response(stop_ids[:1])
parsed = renderer.parse_response(stop_ids[:1], prompt_ids=[])
assert isinstance(parsed, ParsedResponse)
@@ -60,7 +59,7 @@ def test_empty_thinking_block(model_name, tokenizer, renderer):
"""<think></think> with no content (common pattern)."""
text = "<think></think>Hello!"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert "Hello" in parsed.content
@@ -68,16 +67,16 @@ def test_thinking_with_newlines(model_name, tokenizer, renderer):
"""Thinking block with various newline patterns."""
text = "Step 1: Calculate\nStep 2: Verify\n</think>\n\nThe answer is 42."
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert "42" in parsed.content
def test_content_only_no_thinking(model_name, tokenizer, renderer):
"""Plain content with no thinking markers."""
"""Bare text follows the parser's initial state without losing text."""
text = "Hello! How can I help you today?"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert "Hello" in parsed.content
parsed = renderer.parse_response(ids, prompt_ids=[])
assert "Hello" in parsed.content + (parsed.reasoning_content or "")
assert parsed.tool_calls == []
@@ -89,7 +88,7 @@ def test_tool_call_with_complex_json(model_name, tokenizer, renderer):
# This is a generic test — the exact format varies per model
text = "Here are the results."
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert isinstance(parsed, ParsedResponse)
@@ -97,16 +96,16 @@ def test_content_with_special_chars(model_name, tokenizer, renderer):
"""Content containing angle brackets, quotes, etc."""
text = 'The formula is x < y and a > b. Use "quotes" freely.'
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert parsed.content # Should not crash on angle brackets
parsed = renderer.parse_response(ids, prompt_ids=[])
assert parsed.content or parsed.reasoning_content
def test_very_long_content(model_name, tokenizer, renderer):
"""Long content string."""
text = "word " * 500
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert len(parsed.content) > 100
parsed = renderer.parse_response(ids, prompt_ids=[])
assert len(parsed.content + (parsed.reasoning_content or "")) > 100
# ── Return type guarantees ───────────────────────────────────────────
@@ -116,7 +115,7 @@ def test_content_is_always_string(model_name, tokenizer, renderer):
"""content must always be a string, never None."""
for text in ["Hello", "", "<think></think>", "<think>x</think>"]:
ids = tokenizer.encode(text, add_special_tokens=False) if text else []
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert isinstance(parsed.content, str)
@@ -124,7 +123,7 @@ def test_reasoning_is_string_or_none(model_name, tokenizer, renderer):
"""reasoning_content must be str or None."""
text = "Some text"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert parsed.reasoning_content is None or isinstance(parsed.reasoning_content, str)
@@ -137,7 +136,7 @@ def test_tool_calls_is_list_of_parsed_tool_call(model_name, tokenizer, renderer)
"""
text = "Hello!"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
parsed = renderer.parse_response(ids, prompt_ids=[])
assert isinstance(parsed.tool_calls, list)
for tc in parsed.tool_calls:
assert isinstance(tc, ParsedToolCall)
+24
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
import json
import pytest
from renderers.base import ToolCallParseStatus, load_tokenizer
@@ -146,3 +148,25 @@ def test_default_renderer_without_parsers_is_backward_compatible():
assert parsed.reasoning_content == "r"
assert parsed.content == "a"
assert parsed.tool_calls == []
@pytest.mark.parametrize(
"text",
[
"Before<think>reason</think>After",
"Before<think>unfinished",
"\n<think>reason</think>After",
"Before</think>After",
],
)
def test_think_parser_requires_initial_opener(text):
parser = get_reasoning_parser("think", None)
assert parser.extract(text) == (None, text)
def test_parse_status_uses_wire_value_as_string():
for status in ToolCallParseStatus:
assert str(status) == status.value
assert f"{status}" == status.value
assert json.loads(json.dumps({"status": status})) == {"status": status.value}
assert ToolCallParseStatus(status.value) is status
-196
View File
@@ -1,196 +0,0 @@
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)
)
+4 -91
View File
@@ -8,28 +8,21 @@ flipped variant (default ``enable_thinking=false`` → empty
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
conversations including the ``add_generation_prompt=True`` boundary
where the polarity divergence shows up.
These tests lock in the map and polarity metadata. Byte parity for every size
lives in the unified matrix in ``test_parity.py``.
"""
from __future__ import annotations
import pytest
from parity import MODEL_CATALOG
from renderers import Qwen35Renderer, Qwen35RendererConfig, create_renderer
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
_QWEN35_IN_MAP = {
"Qwen/Qwen3.5-0.8B",
"Qwen/Qwen3.5-2B",
"Qwen/Qwen3.5-4B",
"Qwen/Qwen3.5-9B",
"Qwen/Qwen3.5-35B-A3B",
"Qwen/Qwen3.5-122B-A10B",
"Qwen/Qwen3.5-397B-A17B",
case.model for case in MODEL_CATALOG if case.resolved_renderer == "qwen3.5"
}
@@ -107,83 +100,3 @@ def test_construction_does_not_call_apply_chat_template():
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.
# ---------------------------------------------------------------------------
_PARITY_CASES = [
pytest.param(
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
],
False,
id="system_user",
),
pytest.param(
[
{"role": "system", "content": "You are a math tutor."},
{"role": "user", "content": "2+2?"},
{"role": "assistant", "content": "4"},
],
False,
id="single_turn",
),
pytest.param(
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
],
True,
id="with_gen_prompt",
),
pytest.param(
[
{"role": "user", "content": "Solve."},
{
"role": "assistant",
"content": "42",
"reasoning_content": "Think hard.",
},
{"role": "user", "content": "Why?"},
{
"role": "assistant",
"content": "Because.",
"reasoning_content": "More thinking.",
},
],
False,
id="with_reasoning",
),
]
@pytest.mark.parametrize("qwen35_model", sorted(_QWEN35_IN_MAP))
@pytest.mark.parametrize("messages,add_gen_prompt", _PARITY_CASES)
def test_qwen35_size_parity_with_apply_chat_template(
qwen35_model, messages, add_gen_prompt
):
"""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 per-model default."""
tok = load_tokenizer(qwen35_model)
renderer = create_renderer(tok, Qwen35RendererConfig())
assert isinstance(renderer, Qwen35Renderer)
ours = renderer.render_ids(messages, add_generation_prompt=add_gen_prompt)
theirs = list(
tok.apply_chat_template(
messages,
tokenize=True,
return_dict=False,
add_generation_prompt=add_gen_prompt,
)
)
assert ours == theirs, (
f"{qwen35_model}: Qwen35Renderer diverges from apply_chat_template "
f"(add_generation_prompt={add_gen_prompt})"
)
+257
View File
@@ -0,0 +1,257 @@
"""Focused Qwen3.8 registration and upstream-template parity coverage."""
from __future__ import annotations
from functools import lru_cache
from copy import deepcopy
import pytest
from pydantic import TypeAdapter
from renderers import (
Qwen38Renderer,
Qwen38RendererConfig,
RendererConfig,
create_renderer,
)
from renderers.base import MODEL_RENDERER_MAP, MULTIMODAL_MODELS, load_tokenizer
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
QWEN38_MODELS = ["Qwen/Qwen3.8-27B", "Qwen/Qwen3.8-Flash-Next"]
@lru_cache(maxsize=None)
def _qwen38(model_name):
tokenizer = load_tokenizer(model_name)
return tokenizer, create_renderer(tokenizer)
def _expected(tokenizer, messages, **kwargs):
result = tokenizer.apply_chat_template(
messages,
tokenize=True,
return_dict=False,
**kwargs,
)
return list(result)
@pytest.mark.parametrize("qwen38_model", QWEN38_MODELS)
def test_qwen38_is_registered_with_native_defaults(qwen38_model):
tokenizer, renderer = _qwen38(qwen38_model)
assert tokenizer.name_or_path == qwen38_model
assert MODEL_RENDERER_MAP[tokenizer.name_or_path] == "qwen3.8"
assert MULTIMODAL_MODELS[tokenizer.name_or_path] == {"image"}
assert isinstance(renderer, Qwen38Renderer)
assert renderer.config.enable_thinking is True
assert renderer.config.reasoning_effort == "xhigh"
assert renderer.config.preserve_thinking is True
assert renderer.effective_thinking_retention == "all"
def test_qwen38_config_discriminator():
parsed = TypeAdapter(RendererConfig).validate_python(
{
"name": "qwen3.8",
"reasoning_effort": "low",
"preserve_thinking": False,
}
)
assert isinstance(parsed, Qwen38RendererConfig)
assert parsed.reasoning_effort == "low"
assert parsed.preserve_thinking is False
@pytest.mark.parametrize(
"config_kwargs",
[
pytest.param({}, id="defaults"),
pytest.param({"reasoning_effort": "xhigh"}, id="xhigh"),
pytest.param({"reasoning_effort": "medium"}, id="medium"),
pytest.param({"reasoning_effort": "low"}, id="low"),
pytest.param({"enable_thinking": False}, id="thinking-disabled"),
pytest.param({"preserve_thinking": False}, id="drop-history-thinking"),
],
)
@pytest.mark.parametrize("qwen38_model", QWEN38_MODELS)
def test_qwen38_text_and_tool_parity(config_kwargs, qwen38_model):
tokenizer, _ = _qwen38(qwen38_model)
renderer = Qwen38Renderer(tokenizer, Qwen38RendererConfig(**config_kwargs))
cases = [
(
[
{"role": "system", "content": "Be concise."},
{"role": "user", "content": "Hello."},
],
{"add_generation_prompt": True},
),
(
[
{"role": "system", "content": ""},
{"role": "user", "content": "Hello."},
],
{"add_generation_prompt": True},
),
(
[
{"role": "user", "content": "First question."},
{
"role": "assistant",
"reasoning_content": "First thought.",
"content": "First answer.",
},
{"role": "user", "content": "Second question."},
{
"role": "assistant",
"reasoning_content": "Second thought.",
"content": "Second answer.",
},
],
{},
),
(
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris", "fresh": True},
}
}
],
},
{"role": "tool", "content": '{"temperature": 20}'},
],
{"tools": TOOLS, "add_generation_prompt": True},
),
]
for messages, render_kwargs in cases:
expected = _expected(
tokenizer,
messages,
**config_kwargs,
**render_kwargs,
)
assert renderer.render_ids(messages, **render_kwargs) == expected
@pytest.mark.parametrize("qwen38_model", QWEN38_MODELS)
def test_qwen38_keeps_inline_think_markup_in_visible_content(qwen38_model):
tokenizer, renderer = _qwen38(qwen38_model)
messages = [
{"role": "user", "content": "Echo this."},
{
"role": "assistant",
"content": "<think>literal markup</think>visible content",
},
]
assert renderer.render_ids(messages) == _expected(tokenizer, messages)
@pytest.mark.parametrize("qwen38_model", QWEN38_MODELS)
def test_qwen38_requires_a_real_user_query(qwen38_model):
_, renderer = _qwen38(qwen38_model)
with pytest.raises(ValueError, match="No user query found"):
renderer.render_ids([{"role": "system", "content": "System only."}])
@pytest.mark.parametrize(
"role,with_image",
[
("system", False),
("user", False),
("assistant", False),
("tool", False),
("user", True),
("tool", True),
],
)
def test_qwen38_structured_content_render_and_bridge(role, with_image):
_, renderer = _qwen38(QWEN38_MODELS[0])
parts = ["Hello", {"type": "text", "text": " world"}]
if with_image:
parts.append({"type": "image", "image": "unused", "text": 123})
parts.append({"type": "text", "text": "After image"})
noisy_parts = [
{"type": "unsupported"},
*parts,
{"type": "text", "text": None},
{"type": "text", "text": 123},
None,
]
prior = [
{"role": "user", "content": "First question"},
{"role": "assistant", "content": "First answer"},
]
clean = {"role": role, "content": parts}
noisy = {"role": role, "content": noisy_parts}
original = deepcopy(noisy)
messages = [noisy, *prior] if role == "system" else [*prior, noisy]
expected_messages = [clean, *prior] if role == "system" else [*prior, clean]
assert renderer.render(messages, process_multimodal=False) == renderer.render(
expected_messages, process_multimodal=False
)
if role in {"user", "tool"}:
previous = renderer.render_ids(prior)
actual = renderer.bridge_to_next_turn(
previous, [], [noisy], process_multimodal=False
)
assert actual is not None
assert actual == renderer.bridge_to_next_turn(
previous, [], [clean], process_multimodal=False
)
assert noisy == original
def test_qwen38_structured_tool_response_keeps_current_reasoning():
tokenizer, _ = _qwen38(QWEN38_MODELS[0])
renderer = Qwen38Renderer(tokenizer, Qwen38RendererConfig(preserve_thinking=False))
prior = [
{"role": "user", "content": "First question"},
{"role": "assistant", "reasoning_content": "Keep me", "content": ""},
]
content = [
{"type": "text", "text": " <tool_response>"},
{"type": "unsupported"},
{"type": "text", "text": None},
"result",
{"type": "text", "text": "</tool_response> "},
]
messages = [*prior, {"role": "user", "content": content}]
expected = [
*prior,
{"role": "user", "content": "<tool_response>result</tool_response>"},
]
assert renderer.render(messages) == renderer.render(expected)
assert "Keep me" in tokenizer.decode(renderer.render_ids(messages))
with pytest.raises(ValueError, match="No user query found"):
renderer.render([messages[-1]])
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_qwen38.cache_clear()
+630
View File
@@ -0,0 +1,630 @@
"""Reasoning state follows the generation prefix, independently of termination."""
from functools import lru_cache
import pytest
from parity import MODEL_CATALOG
from renderers import create_renderer
from renderers.base import ToolCallParseStatus, load_tokenizer
from renderers.configs import config_from_name
# Exercise every registered renderer, including inherited family variants.
_CASES = {}
for _case in MODEL_CATALOG:
_CASES.setdefault(_case.resolved_renderer, _case.model)
_GLM = {"glm-4.5", "glm-5", "glm-5.1", "glm-5.3"}
_REOPENING_TAGS = _GLM | {"deepseek-v4"}
@lru_cache(None)
def _renderer(name):
config = config_from_name(name)
updates = {"thinking_retention": "all"}
if "enable_thinking" in type(config).model_fields:
updates["enable_thinking"] = True
if "thinking" in type(config).model_fields:
updates["thinking"] = True
if name == "hy3":
updates["reasoning_effort"] = "high"
tok = load_tokenizer(_CASES[name])
return tok, create_renderer(tok, config.model_copy(update=updates))
def _encode(tok, text):
return list(tok.encode(text, add_special_tokens=False))
def _thinking_stream(name, tok, renderer):
prompt = renderer.render_ids(
[{"role": "user", "content": "Calculate carefully."}],
add_generation_prompt=True,
)
if name == "gpt-oss":
return (
prompt,
_encode(tok, "unfinished reasoning"),
_encode(tok, "<|end|><|start|>assistant<|channel|>final<|message|>Answer"),
)
if name == "gemma4":
return (
prompt,
_encode(tok, "<|channel>thought\nunfinished reasoning"),
_encode(tok, "<channel|>Answer"),
)
if name in {"inkling", "inkling-small"}:
return (
prompt,
_encode(tok, "<|content_thinking|>unfinished reasoning"),
_encode(tok, "<|end_message|><|message_model|><|content_text|>Answer"),
)
if name == "hy3":
return (
prompt,
_encode(tok, "unfinished reasoning"),
[renderer._think_end, *_encode(tok, "Answer")],
)
prefix = tok.decode(prompt, skip_special_tokens=False).rstrip()
opener = "" if prefix.endswith("<think>") else "<think>"
return (
prompt,
_encode(tok, opener + "unfinished reasoning"),
_encode(tok, "</think>Answer"),
)
@pytest.mark.parametrize("name", sorted(set(_CASES) - {"llama-3", "default"}))
@pytest.mark.parametrize("stop", [False, True])
def test_every_reasoning_renderer_preserves_unfinished_reasoning(name, stop):
tok, renderer = _renderer(name)
prompt, incomplete, closed = _thinking_stream(name, tok, renderer)
sampled = incomplete + (renderer.get_stop_token_ids()[:1] if stop else [])
original = list(sampled)
result = renderer.parse_response(sampled, prompt_ids=prompt)
assert result.content == ""
assert "unfinished reasoning" in result.reasoning_content
assert not result.tool_calls
assert result.reasoning_complete is False
assert sampled == original
completed = renderer.parse_response(incomplete + closed, prompt_ids=prompt)
assert completed.reasoning_complete is True
assert completed.content == "Answer"
@pytest.mark.parametrize("name", sorted(set(_CASES) - {"llama-3", "default"}))
def test_every_reasoning_bridge_preserves_prefix_or_refuses_sampled_stop(name):
tok, renderer = _renderer(name)
prompt, incomplete, _ = _thinking_stream(name, tok, renderer)
new_messages = [{"role": "user", "content": "Next question."}]
bridge = renderer.bridge_to_next_turn(prompt, incomplete, new_messages)
assert bridge is not None
prefix_len = len(prompt) + len(incomplete)
assert bridge.token_ids[:prefix_len] == prompt + incomplete
assert not any(bridge.sampled_mask[prefix_len:])
close_ids = {
"gpt-oss": lambda: [renderer._end],
"gemma4": lambda: [renderer._channel_end],
"inkling": lambda: [renderer._end_message],
"hy3": lambda: [renderer._think_end],
}.get(name, lambda: _encode(tok, "</think>"))()
assert bridge.token_ids[prefix_len : prefix_len + len(close_ids)] == close_ids
assert not any(bridge.is_content[prefix_len : prefix_len + len(close_ids)])
for stop in renderer.get_stop_token_ids():
stopped_bridge = renderer.bridge_to_next_turn(
prompt, incomplete + [stop], new_messages
)
# Harmony's handoff token closes analysis; its return token does not.
if name == "gpt-oss" and [stop] == _encode(tok, "<|call|>"):
assert stopped_bridge is not None
assert stopped_bridge.token_ids[: prefix_len + 1] == prompt + incomplete + [
stop
]
else:
assert stopped_bridge is None
def test_qwen35_prompt_context_overrides_renderer_mode():
tok, renderer = _renderer("qwen3.5")
plain_prompt = _encode(tok, "<|im_start|>assistant\n<think></think>\n")
answer = _encode(tok, "Answer")
assert renderer.parse_response(answer, prompt_ids=plain_prompt).content == "Answer"
thinking_prompt = _encode(tok, "<|im_start|>assistant\n<think>already thinking ")
parsed = renderer.parse_response(answer, prompt_ids=thinking_prompt)
assert parsed.content == ""
assert parsed.reasoning_content == "Answer"
assert parsed.reasoning_complete is False
def test_gemma_post_tool_prompt_supplies_reasoning_state():
tok, renderer = _renderer("gemma4")
messages = [
{"role": "user", "content": "Calculate."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"id": "call-1", "function": {"name": "calculate", "arguments": {}}},
],
},
{"role": "tool", "tool_call_id": "call-1", "content": "4"},
]
prompt = renderer.render_ids(messages, add_generation_prompt=True)
assert tok.decode(prompt, skip_special_tokens=False).endswith("<|channel>thought\n")
result = renderer.parse_response(
_encode(tok, "Still considering"), prompt_ids=prompt
)
assert result.content == ""
assert result.reasoning_content == "Still considering"
assert result.reasoning_complete is False
# Formats whose vLLM 0.26 parser ends unclosed reasoning at a tool-call opener,
# with a well-formed call to ``danger``. The rest keep reasoning open.
_QWEN_XML_CALL = "<tool_call>\n<function=danger>\n</function>\n</tool_call>"
_GLM_CALL = "<tool_call>danger</tool_call>"
_KIMI_CALL = "<|tool_calls_section_begin|><|tool_call_begin|>functions.danger:0<|tool_call_argument_begin|>{}<|tool_call_end|><|tool_calls_section_end|>"
_TOOL_CALLS = {
"qwen3": '<tool_call>\n{"name": "danger", "arguments": {}}\n</tool_call>',
"qwen3-vl": '<tool_call>\n{"name": "danger", "arguments": {}}\n</tool_call>',
"qwen3.5": _QWEN_XML_CALL,
"qwen3.6": _QWEN_XML_CALL,
"qwen3.8": _QWEN_XML_CALL,
"prime-qwen3": _QWEN_XML_CALL,
"nemotron-3": _QWEN_XML_CALL,
"nemotron-3-ultra": _QWEN_XML_CALL,
"nemotron-3.5": _QWEN_XML_CALL,
"glm-4.5": _GLM_CALL,
"glm-5": _GLM_CALL,
"glm-5.1": _GLM_CALL,
"glm-5.3": _GLM_CALL,
"minimax-m2": '<minimax:tool_call>\n<invoke name="danger">\n</invoke>\n</minimax:tool_call>',
"deepseek-v4": '\n\n<|DSML|tool_calls>\n<|DSML|invoke name="danger">\n</|DSML|invoke>\n</|DSML|tool_calls>',
"kimi-k2": _KIMI_CALL,
"kimi-k2.5": _KIMI_CALL,
"gemma4": "<|tool_call>call:danger{}<tool_call|>",
"inkling": '<|content_invoke_tool_json|>{"name": "danger", "args": {}}<|end_message|>',
}
_STRICT_TOOL_OPENERS = {
"deepseek-r1",
"deepseek-v3",
"gpt-oss",
"hy3",
"laguna-m.1",
"laguna-s-2.1",
"laguna-xs-2.1",
"laguna-xs.2",
}
def test_every_reasoning_renderer_classifies_tool_openers():
reasoning_renderers = set(_CASES) - {"llama-3", "default"}
assert reasoning_renderers == set(_TOOL_CALLS) | _STRICT_TOOL_OPENERS
assert not set(_TOOL_CALLS) & _STRICT_TOOL_OPENERS
@pytest.mark.parametrize("name", ["deepseek-r1", "laguna-xs-2.1"])
def test_tool_drafts_in_unfinished_reasoning_are_not_executable(name):
tok, renderer = _renderer(name)
prompt, incomplete, _ = _thinking_stream(name, tok, renderer)
draft = '<tool_call>{"name":"danger","arguments":{}}</tool_call>'
if name == "deepseek-r1":
draft = "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>danger\n```json\n{}\n```<|tool▁call▁end|><|tool▁calls▁end|>"
result = renderer.parse_response(
incomplete + _encode(tok, draft), prompt_ids=prompt
)
assert result.content == ""
assert "danger" in result.reasoning_content
assert result.tool_calls == []
assert result.reasoning_complete is False
@pytest.mark.parametrize("name", sorted(_TOOL_CALLS))
@pytest.mark.parametrize("stop", [False, True])
def test_tool_opener_ends_unclosed_reasoning(name, stop):
tok, renderer = _renderer(name)
prompt, incomplete, _ = _thinking_stream(name, tok, renderer)
call = _encode(tok, _TOOL_CALLS[name])
sampled = incomplete + call + (renderer.get_stop_token_ids()[:1] if stop else [])
result = renderer.parse_response(sampled, prompt_ids=prompt)
assert result.content == ""
assert result.reasoning_content == "unfinished reasoning"
assert result.reasoning_complete is True
assert [(c.name, c.arguments, c.status) for c in result.tool_calls] == [
("danger", {}, ToolCallParseStatus.OK)
]
start, end = result.tool_calls[0].token_span
assert len(incomplete) <= start < end <= len(incomplete) + len(call)
assert "danger" in tok.decode(sampled[start:end], skip_special_tokens=False)
@pytest.mark.parametrize(
"name", sorted(set(_TOOL_CALLS) - {"inkling"} - _REOPENING_TAGS)
)
def test_explicit_reasoning_close_outranks_earlier_tool_opener(name):
# Inkling closes thinking and tool segments with the same <|end_message|>.
tok, renderer = _renderer(name)
prompt, incomplete, closed = _thinking_stream(name, tok, renderer)
draft = _encode(tok, _TOOL_CALLS[name])
result = renderer.parse_response(incomplete + draft + closed, prompt_ids=prompt)
assert result.content == "Answer"
assert "danger" in result.reasoning_content
assert result.tool_calls == []
assert result.reasoning_complete is True
def test_inkling_prose_after_tool_opener_is_not_executable():
tok, renderer = _renderer("inkling")
prompt, incomplete, _ = _thinking_stream("inkling", tok, renderer)
draft = _encode(
tok, '<|content_invoke_tool_json|>{"name": "danger"} maybe not<|end_message|>'
)
result = renderer.parse_response(incomplete + draft, prompt_ids=prompt)
assert result.reasoning_content == "unfinished reasoning"
assert [c.status for c in result.tool_calls] == [ToolCallParseStatus.INVALID_JSON]
@pytest.mark.parametrize("name", sorted(_TOOL_CALLS))
@pytest.mark.parametrize("truncated", [False, True])
def test_bridge_extends_tool_call_that_ended_reasoning(name, truncated):
tok, renderer = _renderer(name)
prompt, incomplete, _ = _thinking_stream(name, tok, renderer)
call = _encode(tok, _TOOL_CALLS[name])
sampled = incomplete + (
call[: len(call) // 2]
if truncated
else call + renderer.get_stop_token_ids()[:1]
)
bridge = renderer.bridge_to_next_turn(
prompt, sampled, [{"role": "user", "content": "Next question."}]
)
assert bridge is not None
prefix_len = len(prompt) + len(sampled)
assert bridge.token_ids[:prefix_len] == prompt + sampled
assert not any(bridge.sampled_mask[prefix_len:])
close_ids = {
"gemma4": lambda: [renderer._channel_end],
"inkling": lambda: [renderer._end_message],
}.get(name, lambda: _encode(tok, "</think>"))()
assert bridge.token_ids[prefix_len : prefix_len + len(close_ids)] != close_ids
@pytest.mark.parametrize(
"name", ["qwen3", "qwen3.5", "deepseek-r1", "kimi-k2.5", "laguna-xs-2.1", "gemma4"]
)
def test_later_reasoning_markers_follow_the_format_grammar(name):
tok, renderer = _renderer(name)
prompt, incomplete, closed = _thinking_stream(name, tok, renderer)
opening = "<|channel>thought\n" if name == "gemma4" else "<think>"
result = renderer.parse_response(
incomplete + closed + _encode(tok, opening + "more reasoning"),
prompt_ids=prompt,
)
if name == "gemma4":
assert result.content == ""
assert "more reasoning" in result.reasoning_content
assert result.reasoning_complete is False
else:
assert result.content == "Answer<think>more reasoning"
assert result.reasoning_complete is True
assert result.reasoning_content.startswith("unfinished reasoning")
def test_default_renderer_uses_prompt_before_extracting_tool_drafts():
from renderers.configs import DefaultRendererConfig
tok, _ = _renderer("qwen3")
renderer = create_renderer(
tok, DefaultRendererConfig(tool_parser="qwen3", reasoning_parser="think")
)
prompt = _encode(tok, "<|im_start|>assistant\n<think>")
draft = _encode(
tok, 'Considering <tool_call>{"name":"example","arguments":{}}</tool_call>'
)
result = renderer.parse_response(draft, prompt_ids=prompt)
assert result.content == ""
assert "example" in result.reasoning_content
assert not result.tool_calls
assert result.reasoning_complete is False
def test_empty_final_channel_is_not_unfinished_reasoning():
tok, renderer = _renderer("qwen3.5")
prompt = _encode(tok, "<|im_start|>assistant\n<think>")
result = renderer.parse_response(_encode(tok, "</think>"), prompt_ids=prompt)
assert result.content == ""
assert result.reasoning_complete is True
def test_no_reasoning_format_keeps_literal_think_text():
tok, renderer = _renderer("llama-3")
result = renderer.parse_response(_encode(tok, "Literal <think> text"))
assert result.content == "Literal <think> text"
assert result.reasoning_content is None
assert result.reasoning_complete is True
def test_catalog_covers_every_registered_renderer():
from renderers.base import MODEL_RENDERER_MAP
assert set(MODEL_RENDERER_MAP.values()) <= set(_CASES)
@pytest.mark.parametrize("name", ["qwen3", "qwen3.5", "deepseek-r1", "kimi-k2.5"])
def test_literal_text_lookalike_is_not_a_reasoning_token(name):
tok, renderer = _renderer(name)
# Tokenize separately so the decoded bytes spell the marker without its
# structural token ID. The reasoning scanner must match the grammar IDs.
ids = _encode(tok, "<thi") + _encode(tok, "nk>") + _encode(tok, "example")
result = renderer.parse_response(ids, prompt_ids=[])
assert result.reasoning_complete is True
assert result.content == "<think>example"
def test_inkling_partial_reasoning_prefix_is_not_returned_as_content():
tok, renderer = _renderer("inkling")
prompt = _encode(tok, "<|message_model|><|content_thinking|>already considered ")
sampled = _encode(tok, "the next step")
parsed = renderer.parse_response(sampled, prompt_ids=prompt)
assert parsed.content == ""
assert parsed.reasoning_content == "the next step"
assert parsed.reasoning_complete is False
closed = renderer.parse_response(
sampled
+ _encode(tok, "<|end_message|><|message_model|><|content_text|>Answer"),
prompt_ids=prompt,
)
assert closed.reasoning_content == "the next step"
assert closed.content == "Answer"
assert closed.reasoning_complete is True
@pytest.mark.parametrize(
"name", sorted((set(_CASES) - {"llama-3"} - _GLM) | {"default-think"})
)
@pytest.mark.parametrize("enabled", [False, True])
@pytest.mark.parametrize("origin", ["prompt", "completion", "closed_prompt", "both"])
@pytest.mark.parametrize("ending_kind", ["truncated", "stopped", "closed"])
def test_reasoning_markers_override_generation_mode(name, enabled, origin, ending_kind):
"""Generation settings must not hide reasoning actually present in the stream."""
if name in {"default", "default-think"}:
from renderers.configs import DefaultRendererConfig
tok, _ = _renderer("qwen3")
renderer = create_renderer(
tok,
DefaultRendererConfig(
reasoning_parser="think" if name == "default-think" else None
),
)
else:
tok, original = _renderer(name)
updates = {}
for key in ("enable_thinking", "thinking"):
if key in type(original.config).model_fields:
updates[key] = enabled
if name == "hy3":
updates["reasoning_effort"] = "high" if enabled else "no_think"
renderer = create_renderer(tok, original.config.model_copy(update=updates))
opening, ending = {
"gpt-oss": (
"<|start|>assistant<|channel|>analysis<|message|>",
"<|end|><|start|>assistant<|channel|>final<|message|>",
),
"gemma4": ("<|channel>thought\n", "<channel|>"),
"inkling": (
"<|message_model|><|content_thinking|>",
"<|end_message|><|message_model|><|content_text|>",
),
"hy3": ("<think:opensource>", "</think:opensource>"),
}.get(name, ("<think>", "</think>"))
prompt_text = {
"prompt": opening + "Earlier reasoning ",
"completion": "",
"closed_prompt": opening + "Earlier reasoning" + ending,
"both": opening,
}[origin]
prompt = _encode(tok, prompt_text)
text = (opening if origin != "prompt" else "") + "Reasoning"
closed = ending_kind == "closed"
if closed:
text += ending + "Answer"
sampled = _encode(tok, text)
if ending_kind == "stopped":
sampled += renderer.get_stop_token_ids()[:1]
original = list(sampled)
parsed = renderer.parse_response(sampled, prompt_ids=prompt)
assert parsed.reasoning_content == "Reasoning"
assert parsed.content == ("Answer" if closed else "")
assert parsed.reasoning_complete is closed
if origin == "completion":
assert renderer.parse_response(sampled) == parsed
assert renderer.parse_response(sampled, prompt_ids=None) == parsed
assert not parsed.tool_calls
assert sampled == original
@pytest.mark.parametrize(
"name",
sorted(
set(_CASES)
- {"llama-3", "gpt-oss", "gemma4", "inkling", "default"}
- _REOPENING_TAGS
),
)
@pytest.mark.parametrize("closed", [False, True])
def test_late_think_markers_stay_content(name, closed):
tok, renderer = _renderer(name)
opening, ending = (
("<think:opensource>", "</think:opensource>")
if name == "hy3"
else ("<think>", "</think>")
)
literal = "Before" + opening + "literal" + (ending + "After" if closed else "")
parsed = renderer.parse_response(_encode(tok, literal), prompt_ids=[])
assert parsed.content == literal
assert parsed.reasoning_content is None
assert parsed.reasoning_complete is True
continued = renderer.parse_response(
_encode(tok, "continued"), prompt_ids=_encode(tok, literal)
)
assert continued.content == "continued"
assert continued.reasoning_content is None
assert continued.reasoning_complete is True
# After a valid initial reasoning block closes, later markers stay content.
prompt, reasoning, suffix = _thinking_stream(name, tok, renderer)
completion = reasoning + suffix + _encode(tok, literal)
parsed = renderer.parse_response(completion, prompt_ids=prompt)
assert parsed.content == "Answer" + literal
assert parsed.reasoning_complete is True
assert parsed.reasoning_content == "unfinished reasoning"
bridged = renderer.bridge_to_next_turn(
prompt, completion, [{"role": "user", "content": "Next"}]
)
assert bridged is not None
prefix = prompt + completion
assert bridged.token_ids[: len(prefix)] == prefix
close_ids = _encode(tok, ending)
assert bridged.token_ids[len(prefix) : len(prefix) + len(close_ids)] != close_ids
# The same content may already be part of the assistant prompt prefix.
parsed = renderer.parse_response(_encode(tok, "continued"), prompt_ids=prefix)
assert parsed.content == "continued"
assert parsed.reasoning_content is None
assert parsed.reasoning_complete is True
@pytest.mark.parametrize("reasoning_parser", [None, "think"])
@pytest.mark.parametrize(
"literal",
[
"Before<think>literal",
"Before<think>literal</think>After",
"Before</think>After",
],
)
def test_default_renderer_preserves_late_think_markers(reasoning_parser, literal):
from renderers.configs import DefaultRendererConfig
tok, _ = _renderer("qwen3")
renderer = create_renderer(
tok, DefaultRendererConfig(reasoning_parser=reasoning_parser)
)
parsed = renderer.parse_response(_encode(tok, literal), prompt_ids=[])
assert parsed.content == literal
assert parsed.reasoning_content is None
assert parsed.reasoning_complete is not False
@pytest.mark.parametrize("name", sorted(_CASES))
def test_missing_and_empty_prompt_are_self_contained(name):
if name == "default":
from renderers.configs import DefaultRendererConfig
tok, _ = _renderer("qwen3")
renderer = create_renderer(tok, DefaultRendererConfig())
else:
tok, renderer = _renderer(name)
bare = _encode(tok, "Answer")
expected = renderer.parse_response(bare, prompt_ids=[])
if name in _REOPENING_TAGS:
assert expected.content == ""
assert expected.reasoning_content == "Answer"
assert expected.reasoning_complete is False
else:
assert expected.content == "Answer"
assert expected.reasoning_content is None
assert expected.reasoning_complete is not False
assert renderer.parse_response(bare) == expected
assert renderer.parse_response(bare, prompt_ids=None) == expected
if name not in {"llama-3", "default"}:
prompt, incomplete, closed = _thinking_stream(name, tok, renderer)
# Missing context is equivalent for both closed and truncated streams.
for sampled in (incomplete, incomplete + closed):
expected = renderer.parse_response(sampled, prompt_ids=[])
assert renderer.parse_response(sampled) == expected
assert renderer.parse_response(sampled, prompt_ids=None) == expected
with_prompt = renderer.parse_response(incomplete, prompt_ids=prompt)
assert with_prompt.reasoning_complete is False
assert with_prompt.content == ""
@pytest.mark.parametrize("prefilled", [False, True])
@pytest.mark.parametrize("channel", ["final", "commentary", "tool"])
@pytest.mark.parametrize("terminated", [False, True])
def test_harmony_later_channels_end_unterminated_analysis(
prefilled, channel, terminated
):
tok, renderer = _renderer("gpt-oss")
prompt, _, _ = _thinking_stream("gpt-oss", tok, renderer)
opening = "<|start|>assistant<|channel|>analysis<|message|>"
header = "assistant to=functions.weather" if channel == "tool" else "assistant"
channel_name = "commentary" if channel == "tool" else channel
body = '{"city":"Berlin"}' if channel == "tool" else "Answer"
stop = "<|call|>" if channel == "tool" else "<|return|>"
text = (
("" if prefilled else opening)
+ "Reasoning"
+ f"<|start|>{header}<|channel|>{channel_name}<|message|>{body}"
+ (stop if terminated else "")
)
sampled = _encode(tok, text)
parsed = renderer.parse_response(sampled, prompt_ids=prompt if prefilled else [])
assert parsed.reasoning_content == "Reasoning"
assert parsed.reasoning_complete is True
assert parsed.content == ("" if channel == "tool" else "Answer")
if channel == "tool":
from renderers.base import ToolCallParseStatus
assert len(parsed.tool_calls) == 1
call = parsed.tool_calls[0]
assert call.name == "weather"
assert call.arguments == {"city": "Berlin"}
assert call.status == (
ToolCallParseStatus.OK if terminated else ToolCallParseStatus.UNCLOSED_BLOCK
)
assert (
_encode(
tok,
f"<|start|>{header}<|channel|>{channel_name}<|message|>{body}"
+ (stop if terminated else ""),
)
== sampled[slice(*call.token_span)]
)
else:
assert not parsed.tool_calls
bridge = renderer.bridge_to_next_turn(
prompt, sampled, [{"role": "user", "content": "Continue."}]
)
assert bridge is not None
prefix = prompt + sampled
assert bridge.token_ids[: len(prefix)] == prefix
assert not any(bridge.sampled_mask[len(prefix) :])
def test_harmony_later_unfinished_analysis_preserves_earlier_output():
tok, renderer = _renderer("gpt-oss")
prompt, _, _ = _thinking_stream("gpt-oss", tok, renderer)
sampled = _encode(
tok,
"First reasoning"
"<|start|>assistant<|channel|>commentary<|message|>Working."
"<|start|>assistant<|channel|>analysis<|message|>More reasoning<|return|>",
)
parsed = renderer.parse_response(sampled, prompt_ids=prompt)
assert parsed.content == "Working."
assert parsed.reasoning_content == "First reasoningMore reasoning"
assert parsed.reasoning_complete is False
assert (
renderer.bridge_to_next_turn(
prompt, sampled, [{"role": "user", "content": "Continue."}]
)
is None
)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_renderer.cache_clear()
-391
View File
@@ -1,391 +0,0 @@
"""Barrage test: renderer.render_ids() must match tokenizer.apply_chat_template().
Every test case runs against every (model, renderer) pair from conftest.
If a test passes, the renderer is token-for-token correct for that case.
GPT-OSS is auto-skipped here by ``conftest._skip_gpt_oss_for_hf_parity_tests``
since our GptOssRenderer matches openai-harmony / vLLM, not the HF Jinja
template. See ``test_gpt_oss_harmony_parity.py`` for harmony parity coverage.
"""
from functools import lru_cache
from renderers import create_renderer
from renderers.base import load_tokenizer
def _expected(tokenizer, messages, **kwargs):
# Match the Renderer Protocol's default for add_generation_prompt (False)
# — some tokenizers (e.g. Kimi's) default it to True in their config,
# which would otherwise make this parity check fail on the flag alone.
# Callers that explicitly want the gen prompt still pass it through.
kwargs.setdefault("add_generation_prompt", False)
result = tokenizer.apply_chat_template(
messages, tokenize=True, return_dict=False, **kwargs
)
if isinstance(result, dict):
return list(result["input_ids"])
if isinstance(result, str):
# Some tokenizers return str even with tokenize=True; force encode
return list(tokenizer.encode(result, add_special_tokens=False))
return list(result)
# ── Basic messages ───────────────────────────────────────────────────
def test_system_and_user(model_name, tokenizer, renderer):
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hello!"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_single_turn(model_name, tokenizer, renderer):
msgs = [
{"role": "system", "content": "You are a math tutor."},
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_no_system_message(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Hello!"},
{"role": "assistant", "content": "Hi there!"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_multi_turn(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_multi_turn_many_rounds(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
{"role": "user", "content": "E"},
{"role": "assistant", "content": "F"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_empty_assistant_content(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": ""},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
# ── Thinking / reasoning ────────────────────────────────────────────
def test_reasoning_content_field(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "reasoning_content": "Simple arithmetic", "content": "4"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_thinking_multi_turn(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "reasoning_content": "greeting", "content": "Hi!"},
{"role": "user", "content": "Bye"},
{"role": "assistant", "reasoning_content": "farewell", "content": "Goodbye!"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
# ── Tool definitions ─────────────────────────────────────────────────
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"],
},
},
}
]
def test_tools_with_system(model_name, tokenizer, renderer):
msgs = [
{"role": "system", "content": "You are a weather assistant."},
{"role": "user", "content": "Weather?"},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_tools_without_system(model_name, tokenizer, renderer):
msgs = [{"role": "user", "content": "Weather?"}]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
# ── Tool calls ───────────────────────────────────────────────────────
def test_tool_call_with_content(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "Let me check.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_tool_call_no_content(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
]
try:
expected = _expected(tokenizer, msgs, tools=TOOLS)
except TypeError as exc:
# Qwen3-VL upstream chat-template bug. The assistant branch only
# checks `is string` and then unconditionally iterates the else,
# so `content=None` raises TypeError on `for x in None`:
#
# {%- if message.content is string %}
# {{- message.content }}
# {%- else %}
# {%- for content_item in message.content %} ← crash
# {%- if 'text' in content_item %}
# {{- content_item.text }}
# ...
#
# Same pattern in the user-role branch. The fix upstream would be
# `{%- elif message.content %}` to skip iteration on falsy content.
# Until Qwen ships a fixed template this is xfail; the imperative
# xfail auto-promotes to xpass when upstream is fixed.
import pytest
pytest.xfail(f"{model_name}: apply_chat_template raised {exc!r}")
assert renderer.render_ids(msgs, tools=TOOLS) == expected
def test_multiple_tool_calls(model_name, tokenizer, renderer):
msgs = [
{"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"}}},
],
},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
# ── Tool responses ───────────────────────────────────────────────────
def test_single_tool_response(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Weather?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
{"role": "tool", "content": '{"temp": 20}'},
{"role": "assistant", "content": "It's 20 degrees."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_tool_response_with_name(model_name, tokenizer, renderer):
"""Tool message carries `name` (function name). Pins the renderer contract
that if `name` is supplied it gets rendered (e.g., GPT-OSS Harmony emits
`<|start|>functions.{name} to=assistant`). Catches regressions where a
renderer silently drops the field."""
msgs = [
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
{"role": "tool", "name": "get_weather", "content": '{"temp": 20}'},
{"role": "assistant", "content": "It's 20 degrees."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_consecutive_tool_responses(model_name, tokenizer, renderer):
msgs = [
{"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."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
# ── Full tool cycle ──────────────────────────────────────────────────
def test_full_tool_cycle(model_name, tokenizer, renderer):
msgs = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the 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."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_multi_step_tool_cycle(model_name, tokenizer, renderer):
"""Two rounds of tool calling."""
msgs = [
{"role": "user", "content": "Compare weather in Paris and London"},
{
"role": "assistant",
"content": "Let me check Paris.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
{"role": "tool", "content": '{"temp": 20}'},
{
"role": "assistant",
"content": "Now London.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "London"}}}
],
},
{"role": "tool", "content": '{"temp": 15}'},
{"role": "assistant", "content": "Paris: 20, London: 15."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
# ── Qwen3-VL routing ────────────────────────────────────────────────────
@lru_cache
def _qwen3_vl():
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
def test_qwen3_vl_auto_renderer():
_, renderer = _qwen3_vl()
assert type(renderer).__name__ == "Qwen3VLRenderer"
# ── Kimi K2.5: tool_declare message handling ──────────────────────────
@lru_cache
def _kimi_k25():
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
def test_kimi_k2_inline_think_tags_render_verbatim():
"""Kimi K2's chat template emits assistant ``content`` verbatim — including
any inline ``<think>...</think>`` tags. The renderer must not strip them.
Regression for a bug where ``_extract_thinking`` mutated content by
splitting out ``<think>...</think>`` and then discarded the extracted
reasoning, producing tokens that disagreed with ``apply_chat_template``.
"""
tokenizer = load_tokenizer("moonshotai/Kimi-K2-Instruct")
renderer = create_renderer(tokenizer)
msgs = [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "<think>secret</think>visible"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_kimi_k25_tool_declare_message_without_tools_param():
"""``role=tool_declare`` messages must be emitted from their content when
no ``tools=`` arg is passed — not silently dropped.
Regression for the Kimi K2.5 chat template: the template's per-message loop
sends every message (including ``tool_declare``) through ``set_roles`` +
``render_content``, regardless of the ``tools`` parameter. The renderer
used to ``continue`` past ``tool_declare`` messages, dropping them.
"""
tokenizer, renderer = _kimi_k25()
msgs = [
{"role": "tool_declare", "content": "function calc(x: number): number;"},
{"role": "user", "content": "use the calc tool"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
+62 -29
View File
@@ -3,14 +3,16 @@ auto-resolution, and ``extra="forbid"`` enforcement on per-renderer
configs."""
from types import SimpleNamespace
from typing import Literal
import pytest
from pydantic import TypeAdapter, ValidationError
from renderers import (
AutoRendererConfig,
BaseRendererConfig,
DefaultRendererConfig,
GLM5RendererConfig,
GLM53RendererConfig,
GptOssRendererConfig,
Nemotron3RendererConfig,
Qwen3RendererConfig,
@@ -19,10 +21,17 @@ from renderers import (
RendererConfig,
base,
create_renderer,
create_renderer_pool,
)
def test_renderer_specific_fields_require_explicit_classification():
with pytest.raises(TypeError, match="missing=\\['unclassified'\\]"):
class _InvalidRendererConfig(BaseRendererConfig):
name: Literal["invalid-test"] = "invalid-test"
unclassified: bool = False
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``
@@ -44,6 +53,12 @@ def test_discriminated_union_dispatches_on_name():
assert parsed.clear_thinking is False
def test_glm53_defaults_match_its_template():
cfg = GLM53RendererConfig()
assert cfg.clear_thinking is False
assert cfg.reasoning_effort == "max"
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
@@ -131,31 +146,6 @@ def test_create_renderer_auto_applies_chat_template_kwargs(monkeypatch):
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")
@@ -163,7 +153,7 @@ def test_auto_unknown_model_rejects_chat_template_kwargs():
create_renderer(tok, chat_template_kwargs={"enable_thinking": False})
def test_chat_template_kwargs_validate_against_resolved_config(monkeypatch):
def test_chat_template_kwargs_validate_against_explicit_allowlist(monkeypatch):
class _FakeQwen3:
def __init__(self, tokenizer, config):
self.config = config
@@ -171,13 +161,50 @@ def test_chat_template_kwargs_validate_against_resolved_config(monkeypatch):
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeQwen3)
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen3", "qwen3")
with pytest.raises(ValidationError, match="enable_thinkng"):
with pytest.raises(ValueError, match="Allowed: enable_thinking"):
create_renderer(
SimpleNamespace(name_or_path="fake/qwen3"),
chat_template_kwargs={"enable_thinkng": False},
)
def test_chat_template_kwargs_reject_renderer_internal_fields(monkeypatch):
class _FakeQwen35:
def __init__(self, tokenizer, config):
self.config = config
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3.5", _FakeQwen35)
with pytest.raises(ValueError, match="image_cache_max"):
create_renderer(
SimpleNamespace(name_or_path="fake/qwen35"),
Qwen35RendererConfig(),
chat_template_kwargs={"image_cache_max": 1},
)
renderer = create_renderer(
SimpleNamespace(name_or_path="fake/qwen35"),
Qwen35RendererConfig(image_cache_max=1),
)
assert renderer.config.image_cache_max == 1
def test_default_renderer_chat_template_kwargs_remain_open_ended():
renderer = create_renderer(
SimpleNamespace(name_or_path="unknown/text-model"),
DefaultRendererConfig(),
chat_template_kwargs={"custom_jinja_kwarg": True},
)
assert renderer.config.model_extra == {"custom_jinja_kwarg": True}
with pytest.raises(ValueError, match="tool_parser"):
create_renderer(
SimpleNamespace(name_or_path="unknown/text-model"),
DefaultRendererConfig(),
chat_template_kwargs={"tool_parser": "qwen3"},
)
def test_chat_template_kwargs_conflict_with_explicit_config():
with pytest.raises(ValidationError, match="thinking_retention"):
create_renderer(
@@ -322,3 +349,9 @@ def test_default_renderer_config_rejects_legacy_preserve_flags():
cfg = DefaultRendererConfig(some_jinja_kwarg=True)
assert cfg.model_extra["some_jinja_kwarg"] is True
def test_message_required_keys():
assert base.Message.__required_keys__ == {"role", "content"}
assert "tool_calls" in base.Message.__optional_keys__
assert "reasoning_content" in base.Message.__optional_keys__
-563
View File
@@ -1,563 +0,0 @@
"""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)})"
)
+179 -320
View File
@@ -1,352 +1,211 @@
"""Render → parse round-trip.
"""Reference template → live generation prefix → client → parsed response.
Core renderer invariant: if you render
``[user, assistant(content=X, reasoning=Y, tool_calls=[T])]`` to tokens,
extract the assistant's completion slice, and feed it through
``parse_response``, you should get back an equivalent structured message.
Catches asymmetries between a renderer's emit path and its parse path —
bugs that slip past render-parity tests (which only check vs
apply_chat_template) and parse-robustness tests (which feed crafted text,
not rendered output).
Parametrizes over a wider model list than the shared conftest barrage
(which is kept conservative because several newer renderers still
disagree with apply_chat_template in complex tool-cycle edge cases).
The roundtrip invariant is renderer-self-consistent so it can tolerate
those gaps while still giving per-renderer coverage of the emit/parse
pair.
Only inference HTTP is replayed. Expected tokens come from the checkpoint's
chat template (or independent native encoder), never from our renderer. Every
catalog checkpoint and every declared template-setting combination participates.
"""
from __future__ import annotations
import json
from functools import lru_cache
from typing import Any
import pytest
from parity import MODEL_CATALOG, TOOLS, kwarg_combinations
from reference_continuations import ANSWER, REASONING, reference_continuation
from replay import assert_evidence, replay_client
# (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"),
("zai-org/GLM-5", "auto"),
("zai-org/GLM-5.1", "auto"),
("zai-org/GLM-4.7-Flash", "auto"),
("THUDM/GLM-4.5-Air", "auto"),
("MiniMaxAI/MiniMax-M2.5", "auto"),
("moonshotai/Kimi-K2-Instruct", "auto"),
("moonshotai/Kimi-K2.5", "auto"),
("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"),
]
from renderers import create_renderer
from renderers.base import MODEL_RENDERER_MAP, ToolCallParseStatus, load_tokenizer
from renderers.client import generate
from renderers.configs import config_from_name
@lru_cache(maxsize=None)
def _load_renderer(model_name: str, renderer_name: str):
from renderers import config_from_name, create_renderer
from renderers.base import load_tokenizer
tok = load_tokenizer(model_name)
return tok, create_renderer(tok, config_from_name(renderer_name))
def pytest_generate_tests(metafunc):
# Local parametrization only takes effect for tests in this file that
# declare these fixture names — conftest-level parametrization still
# applies to every other test module.
if "rt_model" in metafunc.fixturenames:
metafunc.parametrize(
"rt_model,rt_renderer_name",
_ROUNDTRIP_MODELS,
ids=[m for m, _ in _ROUNDTRIP_MODELS],
)
@pytest.fixture
def rt_tokenizer(rt_model, rt_renderer_name):
return _load_renderer(rt_model, rt_renderer_name)[0]
@pytest.fixture
def rt_renderer(rt_model, rt_renderer_name):
return _load_renderer(rt_model, rt_renderer_name)[1]
PROMPT = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is 2+2?"},
]
def _extract_assistant_tokens(renderer, prompt, assistant_msg):
"""Return the tokens the assistant turn contributes to the full render.
We slice at ``len(render(prompt, add_generation_prompt=False))`` rather
than walking the common prefix against ``add_generation_prompt=True``:
for chatml the two agree, but harmony's gen-prompt opens channel
``analysis`` while the same assistant rendered in-sequence uses
channel ``final``, so common-prefix walking would land inside the
channel name and drop the ``<|start|>assistant<|channel|>``
scaffolding the parser relies on.
"""
prompt_ids = renderer.render_ids(prompt, add_generation_prompt=False)
full_ids = renderer.render_ids(prompt + [assistant_msg])
return full_ids[len(prompt_ids) :]
def _normalize_args(args: Any) -> Any:
"""Normalize tool-call arguments to a dict for cross-renderer comparison.
Some parsers hand back a JSON string, others a dict. Compare by value.
"""
if isinstance(args, str):
try:
return json.loads(args)
except json.JSONDecodeError:
return args
return args
# ── content-only ──────────────────────────────────────────────────────
def test_roundtrip_content_only(rt_model, rt_tokenizer, rt_renderer):
"""Plain response, no thinking, no tool calls."""
msg = {"role": "assistant", "content": "Four."}
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
assert "Four" in parsed.content, f"{rt_model}: lost content, got {parsed.content!r}"
assert not parsed.tool_calls, (
f"{rt_model}: spurious tool_calls={parsed.tool_calls!r}"
# Both matrices visit checkpoints in groups; reuse within each group only.
_tokenizer = lru_cache(maxsize=1)(load_tokenizer)
# Default has no configured tool parser; Llama's template permits one call;
# Harmony's handoff ends generation at the first call. Other formats can emit
# multiple calls in one sampled continuation.
_CASES = [
pytest.param(case, kwargs, calls, id=f"{case.model}-{kwargs}-calls={calls}")
for case in MODEL_CATALOG
for kwargs in kwarg_combinations(case)
for calls in (
[0]
if case.resolved_renderer == "default"
else [0, 1]
if case.resolved_renderer in {"llama-3", "gpt-oss"}
else [0, 1, 2]
)
]
# ── reasoning ─────────────────────────────────────────────────────────
def test_roundtrip_reasoning_and_content(rt_model, rt_tokenizer, rt_renderer):
"""Assistant with reasoning_content + visible content — reasoning must
survive the round trip for templates that emit reasoning blocks."""
msg = {
"role": "assistant",
"content": "The answer is four.",
"reasoning_content": "Two plus two equals four.",
def test_continuation_catalog_covers_registered_renderers():
assert set(MODEL_RENDERER_MAP.values()) <= {
case.resolved_renderer for case in MODEL_CATALOG
}
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
assert "four" in parsed.content.lower(), (
f"{rt_model}: lost content, got {parsed.content!r}"
def _sampled_prefix(renderer, sampled):
# A server stops at the first configured stop token. Several templates emit
# trailing newlines after that token, which are history formatting, not sampled.
stops = renderer.get_stop_token_ids()
end = next(
(i + 1 for i, token in enumerate(sampled) if token in stops), len(sampled)
)
# DefaultRenderer may not carry reasoning unless the template explicitly
# emits a <think> block; hand-coded renderers always should.
if parsed.reasoning_content is not None:
assert "equals four" in parsed.reasoning_content.lower(), (
f"{rt_model}: reasoning mangled, got {parsed.reasoning_content!r}"
return sampled[:end]
@pytest.mark.asyncio
@pytest.mark.parametrize("case,kwargs,calls", _CASES)
async def test_reference_continuation_through_generate(case, kwargs, calls):
tok = _tokenizer(case.model)
renderer = create_renderer(
tok,
config_from_name(case.resolved_renderer),
chat_template_kwargs=kwargs or None,
)
tools = TOOLS if calls else None
messages = [{"role": "user", "content": "Check the weather."}]
prompt, sampled, reasoning = reference_continuation(
tok, case, kwargs, messages, tools, calls=calls
)
sampled = _sampled_prefix(renderer, sampled)
completions = [(sampled, "stop")]
if reasoning:
# Cut the SAME reference stream inside thinking, before its close, to
# exercise length termination with the real generation prefill.
cut = next(
i
for i in range(1, len(sampled) + 1)
if tok.decode(sampled[:i]).rstrip().endswith(REASONING)
)
unfinished = sampled[:cut]
completions.append((unfinished, "length"))
requests = []
async with replay_client(completions, requests) as client:
async def run():
return await generate(
client=client,
renderer=renderer,
model=case.model,
messages=messages,
tools=tools,
max_prompt_len=100000,
)
# ── tool calls ────────────────────────────────────────────────────────
def _maybe_skip_tool_calls(renderer_name: str) -> None:
"""DefaultRenderer without a tool_parser configured always returns an
empty tool_calls list. That's a documented limitation, not a bug — skip."""
if renderer_name == "default":
pytest.skip(
"DefaultRenderer requires an explicit tool_parser to parse tool "
"calls; not exercised in the round-trip matrix."
result = await run()
assert requests[0]["token_ids"] == prompt
assert result["prompt_ids"] == prompt
assert_evidence(result, sampled)
assert result["content"].strip() == ("" if calls else ANSWER)
assert (result["reasoning_content"] or "").strip() == reasoning
assert result["reasoning_complete"] is (
None if case.resolved_renderer == "default" else True
)
assert result["finish_reason"] == ("tool_calls" if calls else "stop")
assert len(result["tool_calls"]) == calls
for call, city in zip(result["tool_calls"], ["Tokyo", "Berlin"]):
assert call.status == ToolCallParseStatus.OK
assert call.name == "get_weather"
arguments = call.arguments
if isinstance(arguments, str):
arguments = json.loads(arguments)
assert arguments == {"city": city}
if reasoning:
truncated = await run()
assert requests[1]["token_ids"] == prompt
assert_evidence(truncated, unfinished)
assert truncated["content"] == ""
assert truncated["reasoning_content"].strip() == REASONING
assert truncated["reasoning_complete"] is False
assert truncated["tool_calls"] == []
assert truncated["finish_reason"] == "length"
def test_roundtrip_single_tool_call(
rt_model, rt_renderer_name, rt_tokenizer, rt_renderer
):
_maybe_skip_tool_calls(rt_renderer_name)
msg = {
@pytest.mark.asyncio
@pytest.mark.parametrize(
"case",
[case for case in MODEL_CATALOG if case.resolved_renderer != "default"],
ids=lambda case: case.model,
)
async def test_reference_continuation_after_tool_dispatch(case):
"""The tool observation can change the next generation's reasoning prefix."""
tok = _tokenizer(case.model)
renderer = create_renderer(tok, config_from_name(case.resolved_renderer))
messages = [{"role": "user", "content": "Check the weather."}]
prompt, sampled, _ = reference_continuation(tok, case, {}, messages, TOOLS, calls=1)
sampled = _sampled_prefix(renderer, sampled)
requests = []
async with replay_client([(sampled, "stop")], requests) as client:
result = await generate(
client=client,
renderer=renderer,
model=case.model,
messages=messages,
tools=TOOLS,
max_prompt_len=100000,
)
assert requests[0]["token_ids"] == prompt
(call,) = result["tool_calls"]
assert call.status == ToolCallParseStatus.OK
arguments = (
json.loads(call.arguments)
if isinstance(call.arguments, str)
else call.arguments
)
observation = {"get_weather": lambda city: f"Sunny in {city}."}[call.name](
**arguments
)
assistant = {
"role": "assistant",
"content": "",
"content": result["content"],
"tool_calls": [
{
# Kimi's parser extracts the function name from the id
# field ("functions.{name}:{idx}") — other renderers ignore
# the id shape, so this form is compatible across the matrix.
"id": "functions.get_weather:0",
"function": {
"name": "get_weather",
"arguments": '{"city": "Tokyo"}',
},
"type": "function",
"function": {"name": call.name, "arguments": arguments},
}
],
}
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
assert parsed.tool_calls, f"{rt_model}: tool_calls lost, got {parsed.tool_calls!r}"
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.name == "get_weather", f"{rt_model}: name mangled, got {tc!r}"
assert _normalize_args(tc.arguments) == {"city": "Tokyo"}, (
f"{rt_model}: args mangled, got {tc.arguments!r}"
)
def test_roundtrip_multiple_tool_calls(
rt_model, rt_renderer_name, rt_tokenizer, rt_renderer
):
"""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."
if result["reasoning_content"]:
assistant["reasoning_content"] = result["reasoning_content"]
if case.resolved_renderer in {"deepseek-v3", "deepseek-r1"}:
assistant["content"] = None
assistant["tool_calls"][0]["function"]["arguments"] = json.dumps(arguments)
messages += [
assistant,
{
"role": "tool",
"name": call.name,
"tool_call_id": "functions.get_weather:0",
"content": observation,
},
]
prompt, sampled, reasoning = reference_continuation(tok, case, {}, messages, TOOLS)
sampled = _sampled_prefix(renderer, sampled)
requests = []
async with replay_client([(sampled, "stop")], requests) as client:
result = await generate(
client=client,
renderer=renderer,
model=case.model,
prompt_ids=prompt,
messages=messages,
tools=TOOLS,
max_prompt_len=100000,
)
msg = {
"role": "assistant",
"content": "",
"tool_calls": [
{
# Kimi's parser extracts the function name from the id
# field ("functions.{name}:{idx}") — other renderers ignore
# the id shape, so this form is compatible across the matrix.
"id": "functions.get_weather:0",
"function": {
"name": "get_weather",
"arguments": '{"city": "Tokyo"}',
},
},
{
"id": "functions.get_time:1",
"function": {
"name": "get_time",
"arguments": '{"zone": "JST"}',
},
},
],
}
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
assert len(parsed.tool_calls) == 2, (
f"{rt_model}: expected 2 tool_calls, got {parsed.tool_calls!r}"
)
names = [tc.name for tc in parsed.tool_calls]
assert names == ["get_weather", "get_time"], (
f"{rt_model}: names/order wrong, got {names}"
)
assert _normalize_args(parsed.tool_calls[0].arguments) == {"city": "Tokyo"}
assert _normalize_args(parsed.tool_calls[1].arguments) == {"zone": "JST"}
# Feed the exact reference sampling prompt. Historical re-rendering may
# deliberately retain reasoning that a template drops; it is not the oracle
# for the parser's live channel state after a tool observation.
assert requests[0]["token_ids"] == prompt
assert_evidence(result, sampled)
assert result["content"].strip() == ANSWER
assert (result["reasoning_content"] or "").strip() == reasoning
assert result["reasoning_complete"] is True
assert result["tool_calls"] == []
assert result["finish_reason"] == "stop"
# ── byte-exact re-render invariant ─────────────────────────────────────
#
# When the chat template round-trips content/reasoning verbatim (no
# separator between `</think>` and content), the parser MUST preserve
# whitespace at the `</think>` boundary. Otherwise parse→re-render
# drops a `\n` token, the rendered assistant message BPE-realigns by
# ~O(tens of tokens), and multi-turn RL's extension property breaks at
# step 2+ on every rollout.
#
# Narrow scope: exercise the parser contract directly so this test
# surfaces only the strip-whitespace regression, not any of the pre-
# existing hand-coded-renderer round-trip quirks.
def test_think_reasoning_parser_preserves_boundary_whitespace():
"""ThinkTextReasoningParser (used when `reasoning_parser='think'`) must
preserve whitespace directly on either side of `</think>` for
byte-exact round-trip through templates like GLM-4.5 that emit
reasoning and content back-to-back with no separator.
Regression: the parser used to call `.strip()` and `.lstrip('\\n')`,
which drops the newline the model naturally emits after `</think>`,
breaking multi-turn trajectory token extension.
"""
from renderers.parsers import ThinkTextReasoningParser
parser = ThinkTextReasoningParser(tokenizer=None)
# Model naturally emits `\n<think>...</think>\nCONTENT` — the \n on
# each side of `</think>` is load-bearing.
reasoning, content = parser.extract(
"\n<think>Reason text</think>\nThe answer is four."
)
assert reasoning == "Reason text", f"reasoning boundary stripped: {reasoning!r}"
assert content.startswith("\n"), (
f"content lost leading '\\n' after </think>: {content!r}"
)
assert content == "\nThe answer is four.", f"content mangled: {content!r}"
def test_think_reasoning_parser_preserves_trailing_reasoning_whitespace():
"""If the model put a `\\n` BEFORE `</think>`, that belongs in
reasoning_content — the template renders it as part of the `<think>`
block and dropping it shifts downstream tokens.
"""
from renderers.parsers import ThinkTextReasoningParser
parser = ThinkTextReasoningParser(tokenizer=None)
reasoning, content = parser.extract(
"<think>Line one\nLine two\n</think>Final answer."
)
assert reasoning == "Line one\nLine two\n", (
f"lost trailing '\\n' inside <think>: {reasoning!r}"
)
assert content == "Final answer.", f"content mangled: {content!r}"
def test_default_renderer_fallback_parser_preserves_boundary_whitespace(
rt_tokenizer,
):
"""DefaultRenderer's built-in fallback (when no explicit reasoning
parser is configured) must apply the same whitespace-preservation
rule so models with `<think>`-emitting templates round-trip.
Uses whatever `rt_tokenizer` is available but skips if the tokenizer
can't round-trip `<think>` tags cleanly — we only care about the
parser's text handling here.
"""
from renderers.default import DefaultRenderer
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
# — we only exercise the parser's text-splitting logic.
text = "<think>reason</think>\nvisible"
ids = rt_tokenizer.encode(text, add_special_tokens=False)
# If decoding doesn't round-trip the `\n`, the test is N/A for this
# tokenizer — this is a parser-level invariant, not a tokenizer one.
if rt_tokenizer.decode(ids, skip_special_tokens=False) != text:
pytest.skip("tokenizer decode does not round-trip the fixture text")
parsed = renderer.parse_response(ids)
assert parsed.reasoning_content == "reason", (
f"reasoning stripped beyond `</think>`: {parsed.reasoning_content!r}"
)
assert (parsed.content or "").startswith("\n"), (
f"content lost leading '\\n' after `</think>`: {parsed.content!r}"
)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_tokenizer.cache_clear()
+2
View File
@@ -41,6 +41,8 @@ def test_sampled_mask_excludes_user_and_system(model_name, renderer):
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Another question"},
{"role": "assistant", "content": "Another answer"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
+258
View File
@@ -0,0 +1,258 @@
"""Token-response replays through the real client, renderer, and turn bridge.
Only the inference HTTP boundary is replayed. Tokenization, request rendering,
response parsing, tool dispatch, and continuation all use the production path.
"""
from functools import lru_cache
import pytest
from parity import TOOLS, models_for
from replay import assert_evidence, replay_client
from renderers import create_renderer
from renderers.base import ToolCallParseStatus, load_tokenizer
from renderers.client import generate
from renderers.configs import config_from_name
@lru_cache(maxsize=1)
def _tokenizer(model):
return load_tokenizer(model)
@pytest.fixture(
params=[
case
for case in models_for("shared")
if case.resolved_renderer.startswith("glm-")
or case.resolved_renderer == "deepseek-v4"
],
ids=lambda case: case.model,
)
def rollout(request):
case = request.param
tok = _tokenizer(case.model)
config = config_from_name(case.resolved_renderer)
updates = {"thinking_retention": "all"}
if "enable_thinking" in type(config).model_fields:
updates["enable_thinking"] = True
config = config.model_copy(update=updates)
return tok, create_renderer(tok, config), case.model
def _tool_text(model, city):
if model.startswith("deepseek"):
return (
'<|DSML|tool_calls>\n<|DSML|invoke name="get_weather">\n'
f'<|DSML|parameter name="city" string="true">{city}</|DSML|parameter>\n'
"</|DSML|invoke>\n</|DSML|tool_calls>"
)
return (
"<tool_call>get_weather<arg_key>city</arg_key>"
f"<arg_value>{city}</arg_value></tool_call>"
)
@pytest.mark.asyncio
@pytest.mark.parametrize("with_call", [False, True])
async def test_literal_delimiters_survive_generate_and_tool_continuation(
rollout, with_call
):
tok, renderer, model = rollout
def encode(text):
return tok.encode(text, add_special_tokens=False)
# Split encoding deliberately produces ordinary tokens spelling delimiters.
# These are sampled tokens, so re-encoding their decoded text is incorrect.
literal = (
encode("Before <thi")
+ encode("nk>literal</thi")
+ encode("nk> <tool_")
+ encode("call>example</tool_")
+ encode("call> After")
)
expected_content = (
"Before <think>literal</think> <tool_call>example</tool_call> After"
)
assert tok.decode(literal, skip_special_tokens=False) == expected_content
assert tok.convert_tokens_to_ids("<think>") not in literal
assert tok.convert_tokens_to_ids("</think>") not in literal
assert tok.convert_tokens_to_ids("<tool_call>") not in literal
argument = "東京<think>literal</think>"
call = _tool_text(model, argument)
sampled = encode("\n<think>Reasoning</think>") + literal
if with_call:
sampled += encode(call)
sampled += renderer.get_stop_token_ids()[:1]
answer = encode("<think>Checked</think>Sunny.") + renderer.get_stop_token_ids()[:1]
requests = []
messages = [{"role": "user", "content": "Check the weather."}]
async with replay_client([(sampled, "stop"), (answer, "stop")], requests) as client:
result = await generate(
client=client,
renderer=renderer,
model=model,
messages=messages,
tools=TOOLS,
max_prompt_len=100000,
)
assert_evidence(result, sampled)
assert result["content"] == expected_content
assert result["reasoning_content"] == "\nReasoning"
assert result["reasoning_complete"] is True
assert requests[0]["token_ids"] == renderer.render_ids(
messages, tools=TOOLS, add_generation_prompt=True
)
if not with_call:
assert result["tool_calls"] == []
assert result["finish_reason"] == "stop"
return
assert result["finish_reason"] == "tool_calls"
assert len(result["tool_calls"]) == 1
tool = result["tool_calls"][0]
assert tool.status == ToolCallParseStatus.OK
assert tool.name == "get_weather"
assert tool.arguments == {"city": argument}
assert tool.raw in tok.decode(sampled[slice(*tool.token_span)])
# Dispatch the parsed call and feed its result into the next real request.
functions = {"get_weather": lambda city: f"Sunny in {city}."}
observation = {
"role": "tool",
"name": tool.name,
"tool_call_id": "weather-1",
"content": functions[tool.name](**tool.arguments),
}
bridge = renderer.bridge_to_next_turn(
result["prompt_ids"], sampled, [observation], tools=TOOLS
)
assert bridge is not None
prefix = result["prompt_ids"] + sampled
assert bridge.token_ids[: len(prefix)] == prefix
assert not any(bridge.sampled_mask[len(prefix) :])
followup = await generate(
client=client,
renderer=renderer,
model=model,
messages=[observation],
tools=TOOLS,
prompt_ids=bridge.token_ids,
prompt_attribution=bridge,
max_prompt_len=100000,
)
assert_evidence(followup, answer)
assert requests[1]["token_ids"] == bridge.token_ids
assert followup["prompt_attribution"] is bridge
assert followup["content"] == "Sunny."
assert followup["reasoning_content"] == "Checked"
assert followup["reasoning_complete"] is True
assert followup["tool_calls"] == []
assert followup["finish_reason"] == "stop"
@pytest.mark.asyncio
@pytest.mark.parametrize("truncated", [False, True])
async def test_repeated_calls_keep_argument_markup_and_model_specific_tail(
rollout, truncated
):
tok, renderer, model = rollout
# An opener inside a string argument must not become an additional call.
argument = (
'<|DSML|invoke name="literal">'
if model.startswith("deepseek")
else "<tool_call>literal"
)
first = _tool_text(model, argument)
second = _tool_text(model, "Berlin")
if truncated:
second = second[: second.index("Berlin") + len("Berlin")]
text = "\n<think>First<think>Second" + first + second
if not truncated:
text += "After<think>More"
sampled = tok.encode(text, add_special_tokens=False)
requests = []
async with replay_client([(sampled, "length")], requests) as client:
result = await generate(
client=client,
renderer=renderer,
model=model,
messages=[{"role": "user", "content": "Check two cities."}],
tools=TOOLS,
max_prompt_len=100000,
)
assert_evidence(result, sampled)
calls = result["tool_calls"]
assert len(calls) == 2
assert calls[0].arguments == {"city": argument}
assert [c.status for c in calls] == [
ToolCallParseStatus.OK,
ToolCallParseStatus.UNCLOSED_BLOCK if truncated else ToolCallParseStatus.OK,
]
for call in calls:
assert call.raw in tok.decode(sampled[slice(*call.token_span)])
if not truncated:
assert calls[1].arguments == {"city": "Berlin"}
reopened = not truncated and not model.startswith("deepseek")
assert result["content"] == ("After" if reopened else "")
assert result["reasoning_content"] == "\nFirstSecond" + ("More" if reopened else "")
assert result["reasoning_complete"] is not reopened
assert result["finish_reason"] == "length"
bridge = renderer.bridge_to_next_turn(
result["prompt_ids"],
sampled,
[{"role": "user", "content": "Continue."}],
tools=TOOLS,
)
assert bridge is not None
prefix = result["prompt_ids"] + sampled
assert bridge.token_ids[: len(prefix)] == prefix
extension = bridge.token_ids[len(prefix) :]
close = tok.encode("</think>", add_special_tokens=False)
assert (extension[: len(close)] == close) is reopened
assert not any(bridge.sampled_mask[len(prefix) :])
@pytest.mark.asyncio
@pytest.mark.parametrize("stopped", [False, True])
async def test_unfinished_reasoning_survives_client_and_controls_bridge(
rollout, stopped
):
tok, renderer, model = rollout
sampled = tok.encode(
"\n<think>First</think>Before<think>Unfinished", add_special_tokens=False
)
if stopped:
sampled += renderer.get_stop_token_ids()[:1]
finish_reason = "stop" if stopped else "length"
async with replay_client([(sampled, finish_reason)], []) as client:
result = await generate(
client=client,
renderer=renderer,
model=model,
messages=[{"role": "user", "content": "Think carefully."}],
max_prompt_len=100000,
)
assert_evidence(result, sampled)
assert result["content"] == "Before"
assert result["reasoning_content"] == "\nFirstUnfinished"
assert result["reasoning_complete"] is False
assert result["tool_calls"] == []
assert result["finish_reason"] == finish_reason
bridge = renderer.bridge_to_next_turn(
result["prompt_ids"], sampled, [{"role": "user", "content": "Continue."}]
)
if stopped:
assert bridge is None
else:
assert bridge is not None
prefix = result["prompt_ids"] + sampled
assert bridge.token_ids[: len(prefix)] == prefix
close = tok.encode("</think>", add_special_tokens=False)
assert bridge.token_ids[len(prefix) : len(prefix) + len(close)] == close
assert not any(bridge.sampled_mask[len(prefix) :])
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_tokenizer.cache_clear()
+7 -10
View File
@@ -23,21 +23,13 @@ from functools import lru_cache
from typing import Any
import pytest
from parity import models_for
# (HuggingFace model name, renderer name). Two JSON-shaped controls
# (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
]
_MODELS = [(case.model, case.renderer) for case in models_for("tool-arg-types")]
@lru_cache(maxsize=None)
@@ -211,3 +203,8 @@ def test_union_with_string_emits_ok_status(
assert got == args, (
f"{model}: tool-arg drift — sent {args!r}, parser returned {got!r}"
)
def teardown_module():
"""Release model resources when this module finishes, not at process exit."""
_load.cache_clear()
Generated
+419 -453
View File
File diff suppressed because it is too large Load Diff