Compare commits

...
Author SHA1 Message Date
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
65 changed files with 10103 additions and 3384 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
+28 -18
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(
@@ -40,7 +57,7 @@ next_prompt_ids = r.bridge_to_next_turn(
)
```
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `deepseek-r1`, `kimi-k2`, `kimi-k2.5` / `kimi-k2.6`, `nemotron-3`, `nemotron-3-ultra`, `llama-3`, `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-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
@@ -76,17 +93,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 +119,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 +153,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.
@@ -159,7 +169,7 @@ Fallback for unsupported text-only models. Wraps `apply_chat_template` and accep
## 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 +179,7 @@ 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.
## License
+27 -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,28 @@ 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-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 +77,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 +92,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 +137,18 @@ 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-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
+22 -2
View File
@@ -19,7 +19,6 @@ dependencies = [
"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]
+43 -16
View File
@@ -7,6 +7,7 @@ except ImportError:
__version__ = "0+unknown"
from renderers.base import (
ChatTemplateTokenizer,
Content,
ContentPart,
ImagePart,
@@ -14,6 +15,7 @@ from renderers.base import (
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,13 +35,12 @@ from renderers.base import (
build_training_sample,
build_trajectory_step,
create_renderer,
create_renderer_pool,
extract_message_tool_names,
is_multimodal,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.client import OverlongPromptError
from renderers.client import MalformedGenerateResponseError, OverlongPromptError
from renderers.configs import (
AutoRendererConfig,
BaseRendererConfig,
@@ -47,58 +48,68 @@ from renderers.configs import (
DefaultRendererConfig,
DeepSeekR1RendererConfig,
DeepSeekV3RendererConfig,
DeepSeekV4RendererConfig,
GLM45RendererConfig,
GLM51RendererConfig,
GLM5RendererConfig,
Gemma4RendererConfig,
GptOssRendererConfig,
Hy3RendererConfig,
InklingRendererConfig,
KimiK25RendererConfig,
KimiK2RendererConfig,
LagunaM1RendererConfig,
LagunaS21RendererConfig,
LagunaXS2RendererConfig,
LagunaXS21RendererConfig,
Llama3RendererConfig,
MiniMaxM2RendererConfig,
Nemotron35RendererConfig,
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
PrimeQwen3RendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen38RendererConfig,
Qwen3RendererConfig,
Qwen3VLRendererConfig,
RendererConfig,
)
# Concrete renderer classes are lazy-loaded so that consumers needing
# only the config layer (``RendererConfig`` discriminated union) don't
# pay the ``transformers`` import cost. Each renderer module does
# ``from transformers.tokenization_utils import PreTrainedTokenizer``
# at module level, so eager imports here would drag ``transformers``
# into every downstream ``import renderers``. ``__getattr__`` (PEP 562)
# resolves the names on first attribute access, so ``from renderers
# import DefaultRenderer`` and ``renderers.DefaultRenderer`` both work
# transparently. ``create_renderer`` doesn't depend on these eager
# imports — ``renderers.base._populate_registry`` lazy-imports the
# concrete classes itself when a renderer is instantiated.
# 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",
"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,12 +133,15 @@ def __dir__() -> list[str]:
__all__ = [
"AutoRendererConfig",
"BaseRendererConfig",
"ChatTemplateTokenizer",
"Content",
"ContentPart",
"DeepSeekR1Renderer",
"DeepSeekR1RendererConfig",
"DeepSeekV3Renderer",
"DeepSeekV3RendererConfig",
"DeepSeekV4Renderer",
"DeepSeekV4RendererConfig",
"DefaultRenderer",
"DefaultRendererConfig",
"GLM45Renderer",
@@ -136,15 +150,23 @@ __all__ = [
"GLM51RendererConfig",
"GLM5Renderer",
"GLM5RendererConfig",
"Gemma4Renderer",
"Gemma4RendererConfig",
"GptOssRenderer",
"GptOssRendererConfig",
"Hy3Renderer",
"Hy3RendererConfig",
"ImagePart",
"InklingRenderer",
"InklingRendererConfig",
"KimiK25Renderer",
"KimiK25RendererConfig",
"KimiK2Renderer",
"KimiK2RendererConfig",
"LagunaM1Renderer",
"LagunaM1RendererConfig",
"LagunaS21Renderer",
"LagunaS21RendererConfig",
"LagunaXS2Renderer",
"LagunaXS2RendererConfig",
"LagunaXS21Renderer",
@@ -152,15 +174,19 @@ __all__ = [
"Llama3Renderer",
"Llama3RendererConfig",
"MULTIMODAL_MODELS",
"MalformedGenerateResponseError",
"Message",
"MiniMaxM2Renderer",
"MiniMaxM2RendererConfig",
"MultiModalData",
"MultimodalRenderer",
"Nemotron35Renderer",
"Nemotron35RendererConfig",
"Nemotron3Renderer",
"Nemotron3RendererConfig",
"Nemotron3UltraRenderer",
"Nemotron3UltraRendererConfig",
"OffsetTokenizer",
"OverlongPromptError",
"ParsedResponse",
"ParsedToolCall",
@@ -171,6 +197,8 @@ __all__ = [
"Qwen35RendererConfig",
"Qwen36Renderer",
"Qwen36RendererConfig",
"Qwen38Renderer",
"Qwen38RendererConfig",
"Qwen3Renderer",
"Qwen3RendererConfig",
"Qwen3VLRenderer",
@@ -180,9 +208,9 @@ __all__ = [
"RenderedTrainingSample",
"Renderer",
"RendererConfig",
"RendererPool",
"TextPart",
"ThinkingPart",
"Tokenizer",
"ToolCall",
"ToolCallFunction",
"ToolCallParseStatus",
@@ -194,7 +222,6 @@ __all__ = [
"build_trajectory_step",
"config_from_name",
"create_renderer",
"create_renderer_pool",
"extract_message_tool_names",
"is_multimodal",
"reject_assistant_in_extension",
+313 -224
View File
@@ -2,10 +2,7 @@ from __future__ import annotations
import enum
import logging
import queue
import threading
from collections.abc import Mapping
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
@@ -14,6 +11,7 @@ from typing import (
Literal,
Protocol,
TypedDict,
cast,
runtime_checkable,
)
@@ -117,6 +115,7 @@ class Message(TypedDict, total=False):
tool_calls: list[ToolCall]
tool_call_id: str
name: str
reasoning: str
reasoning_content: str
@@ -245,7 +244,9 @@ class RenderedTokens:
Empty ``sampled_mask`` (``[]``) means the renderer doesn't provide
this signal — consumers should fall back to attribution-only
masking. ``DefaultRenderer`` leaves it empty because the Jinja
template is opaque; hand-coded renderers populate it.
template is opaque. Hand-coded renderers normally populate it; a
renderer whose sampled/scaffold boundary depends on character
attribution may leave it empty for an offsetless tokenizer.
``is_content`` is a per-token signal generalizing the "scaffold vs
body" distinction across all roles: ``True`` iff the token was
@@ -271,7 +272,8 @@ class RenderedTokens:
Empty ``is_content`` (``[]``) — like ``sampled_mask`` — means the
renderer doesn't provide the signal. ``DefaultRenderer`` leaves it
empty for the same reason.
empty because its Jinja template is opaque; all renderers leave it
empty when the supplied tokenizer cannot return character offsets.
``message_tool_names`` is the per-message tool function name list,
parallel to ``message_roles`` (same length). For tool-role
@@ -478,7 +480,7 @@ class RenderedTokens:
Returns an empty dict when :attr:`is_content` or
:attr:`message_roles` is empty (renderer didn't populate the
signal — e.g. ``DefaultRenderer``).
signal — e.g. ``DefaultRenderer`` or an offsetless tokenizer).
Intended for selective loss masking: SFT on tool response
bodies while RL acts only on assistant turns is the canonical
@@ -558,8 +560,15 @@ class ToolCallParseStatus(str, enum.Enum):
"""Per-attempt outcome of parsing a single ``<tool_call>`` block.
The renderer parser's job is JSON-syntax → ``dict`` (the parser-level
contract). Schema validation — required fields, argument types, tool
name lookup — is the *tool*'s job and is intentionally not done here.
contract). Schema validation — required fields, argument types — is
the *tool*'s job and is intentionally not done here. Tool-*name*
lookup is the one exception, and only where the reference inference
parser does it: vLLM ≥ 0.24 aliases ``glm45``/``glm47`` to a parser
with ``validate_tool_names=True`` that silently drops any call whose
name isn't in the request's tool list. ``parse_glm`` mirrors that as
``UNKNOWN_TOOL`` (when ``tools`` is passed) so train-side parsing
agrees with what an eval client sees from the engine — but keeps the
attempt visible instead of swallowing it.
See ``ParsedToolCall.status`` for what each value means.
Diverges from vLLM/SGLang on purpose. Both engines collapse parse
@@ -576,6 +585,7 @@ class ToolCallParseStatus(str, enum.Enum):
UNCLOSED_BLOCK = "unclosed_block" # opening delim hit EOS / stop
MISSING_NAME = "missing_name" # parsed structurally, but no function name
MALFORMED_STRUCTURE = "malformed_structure" # format-specific shape error
UNKNOWN_TOOL = "unknown_tool" # name not in the provided tools list
@dataclass
@@ -654,6 +664,48 @@ class RenderedConversation:
)
@runtime_checkable
class Tokenizer(Protocol):
"""Structural tokenizer surface used by hand-coded renderers.
Hugging Face tokenizers satisfy this protocol, as can lightweight BYO
adapters around ``tokenizers.Tokenizer`` or another tokenizer backend.
Keeping the renderer-facing contract here makes ``transformers`` optional
for text rendering. Character offsets are a separate optional capability;
see :class:`OffsetTokenizer`.
"""
name_or_path: str
unk_token_id: int | None
eos_token_id: int | None
def encode(self, text: str, *args: Any, **kwargs: Any) -> list[int]: ...
def decode(self, token_ids: Any, *args: Any, **kwargs: Any) -> str: ...
def convert_tokens_to_ids(self, tokens: Any) -> Any: ...
@runtime_checkable
class OffsetTokenizer(Tokenizer, Protocol):
"""Tokenizer that can return character offsets alongside token IDs.
Hand-coded renderers use this optional capability to distinguish caller
content from adjacent template scaffold without changing the underlying
BPE pass. A basic :class:`Tokenizer` remains sufficient for rendering token
IDs; when offsets are unavailable, renderers leave ``is_content`` empty.
"""
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
@runtime_checkable
class ChatTemplateTokenizer(Tokenizer, Protocol):
"""Tokenizer surface required by :class:`DefaultRenderer`."""
def apply_chat_template(self, *args: Any, **kwargs: Any) -> Any: ...
@runtime_checkable
class Renderer(Protocol):
"""Owns message ↔ token conversion for a specific model family."""
@@ -670,10 +722,9 @@ class Renderer(Protocol):
Behaviour around historical ``reasoning_content`` is owned by the
renderer instance — the ``thinking_retention`` level is resolved at
construction, not passed per call. To render with a different
configuration, build a different renderer (or different pool). When
``thinking_retention`` is left unset, full renders follow the model's
chat template and bridge policy is derived from that template's own
history-retention knobs.
configuration, build a different renderer. When ``thinking_retention``
is left unset, full renders follow the model's chat template and bridge
policy is derived from that template's own history-retention knobs.
"""
...
@@ -785,10 +836,10 @@ class MultimodalRenderer(Renderer, Protocol):
"""A :class:`Renderer` that supports multimodal inputs (images, video).
Concrete classes (``Qwen3VLRenderer``, ``Qwen35Renderer``,
``Qwen36Renderer``, ``KimiK25Renderer``) implement this Protocol
structurally — no explicit inheritance required. Callers that need
to drive vLLM's ``multi_modal_data`` features field or carry images
forward across turns should dispatch on ``isinstance(r,
``Qwen36Renderer``, ``Qwen38Renderer``, ``KimiK25Renderer``) implement
this Protocol structurally — no explicit inheritance required.
Callers that need to drive vLLM's ``multi_modal_data`` features field or
carry images forward across turns should dispatch on ``isinstance(r,
MultimodalRenderer)`` and use the extended ``bridge_to_next_turn``
signature below.
"""
@@ -830,9 +881,7 @@ class MultimodalRenderer(Renderer, Protocol):
# Per-type cache for ``is_multimodal``. The ``runtime_checkable`` Protocol
# isinstance check walks every protocol member via ``hasattr`` on each
# call; per-type caching collapses that to a single dict lookup on the
# hot path (e.g. per-bridge dispatch). Pools expose ``is_multimodal``
# directly as a snapshot attribute (different pools share a class but
# wrap different renderer types), so we don't need to special-case them.
# hot path (e.g. per-bridge dispatch).
_IS_MULTIMODAL_BY_TYPE: dict[type, bool] = {}
@@ -854,127 +903,6 @@ def is_multimodal(r: object) -> bool:
return cached
class RendererPool:
"""Pool of Renderer instances that itself satisfies the Renderer protocol.
Callers treat a pool like a single renderer — ``pool.render_ids(...)``,
``pool.bridge_to_next_turn(...)``, ``isinstance(pool, MultimodalRenderer)``
all work via structural delegation. The pool internally serializes
access to its inner renderers (each wraps its own tokenizer copy).
Concurrency model:
- ``size == 1``: a single inner renderer guarded by a ``threading.Lock``.
Avoids the queue's per-call overhead on the common default config.
- ``size > 1``: a ``queue.Queue`` of independent renderers, checked out
one at a time. HuggingFace fast tokenizers release the GIL during
Rust encoding, so threads achieve real parallelism.
Construction parallelism for ``size > 1``: ``AutoTokenizer.from_pretrained``
takes hundreds of ms per call (JSON parse + Rust tokenizer build + HF
cache lookup), so populating a 32-slot pool serially costs ~10-15s on
startup and shows up directly as a step-0 stall. We fan the factory out
across a short-lived thread pool; the GIL-bound Python portion stops
scaling past ~8 workers, so we clamp there.
"""
def __init__(self, factory: Callable[[], Renderer], size: int):
from concurrent.futures import ThreadPoolExecutor
self._factory = factory
self._size = size
if size == 1:
renderer = factory()
self._sole: Renderer | None = renderer
self._lock: threading.Lock | None = threading.Lock()
self._pool: queue.Queue[Renderer] | None = None
sample: Renderer = renderer
else:
self._sole = None
self._lock = None
self._pool = queue.Queue(maxsize=size)
workers = min(size, 8)
with ThreadPoolExecutor(max_workers=workers) as executor:
for renderer in executor.map(lambda _: factory(), range(size)):
self._pool.put(renderer)
# Peek without removing — safe at construction time before any
# checkout has been served.
sample = self._pool.queue[0]
# Snapshot the protocol-shaped attributes from a sample renderer.
# They are constant per renderer class, so resolving them once at
# construction (a) eliminates per-call ``getattr``/``isinstance``
# overhead and (b) lets a future out-of-process pool variant skip
# holding a live tokenizer in the parent process.
self._renderer_cls: type[Renderer] = type(sample)
self.supports_tools: bool = getattr(sample, "supports_tools", True)
self.is_multimodal: bool = is_multimodal(sample)
# ``mm_token_type_id_map`` is set ONLY on pools wrapping a
# ``MultimodalRenderer``. We deliberately don't expose this as a
# class-level property: ``runtime_checkable`` Protocol's
# isinstance check uses ``inspect.getattr_static``, which finds
# property descriptors on the class regardless of whether their
# fget raises. Conditional instance attributes (present in
# ``self.__dict__`` only when applicable) are the only way to
# make ``isinstance(pool, MultimodalRenderer)`` reflect the
# inner renderer's actual protocol conformance.
if isinstance(sample, MultimodalRenderer):
self.mm_token_type_id_map: dict[int, int] = sample.mm_token_type_id_map
@contextmanager
def checkout(self):
if self._sole is not None:
assert self._lock is not None
with self._lock:
yield self._sole
return
assert self._pool is not None
renderer = self._pool.get()
try:
yield renderer
finally:
self._pool.put(renderer)
@property
def size(self) -> int:
return self._size
@property
def renderer_cls(self) -> type[Renderer]:
"""Class of the renderers in this pool (uniform across all slots)."""
return self._renderer_cls
# ── Renderer protocol delegation ────────────────────────────────────
# Pool structurally satisfies ``Renderer`` (and ``MultimodalRenderer``
# when its slots wrap multimodal renderers). Callers can call methods
# directly and dispatch with ``isinstance(pool, MultimodalRenderer)``
# without reaching into ``checkout()``.
def render(self, *args: Any, **kwargs: Any) -> "RenderedTokens":
with self.checkout() as r:
return r.render(*args, **kwargs)
def render_ids(self, *args: Any, **kwargs: Any) -> list[int]:
with self.checkout() as r:
return r.render_ids(*args, **kwargs)
def parse_response(self, *args: Any, **kwargs: Any) -> "ParsedResponse":
with self.checkout() as r:
return r.parse_response(*args, **kwargs)
def get_stop_token_ids(self) -> list[int]:
with self.checkout() as r:
return r.get_stop_token_ids()
def bridge_to_next_turn(self, *args: Any, **kwargs: Any) -> "RenderedTokens | None":
with self.checkout() as r:
return r.bridge_to_next_turn(*args, **kwargs)
# ``mm_token_type_id_map`` (the MultimodalRenderer protocol attribute)
# is set in ``__init__`` only for pools wrapping multimodal renderers;
# see the comment there for why this isn't a class-level property.
RENDERER_REGISTRY: dict[str, type] = {}
# Exact canonical HF model names → renderer. We do NOT use prefix
@@ -1022,10 +950,21 @@ MODEL_RENDERER_MAP: dict[str, str] = {
"Qwen/Qwen3.5-397B-A17B": "qwen3.5",
# Qwen3.6.
"Qwen/Qwen3.6-35B-A3B": "qwen3.6",
# Qwen3.8.
"Qwen/Qwen3.8-27B": "qwen3.8",
"Qwen/Qwen3.8-Flash-Next": "qwen3.8",
# Qwen3-VL.
"Qwen/Qwen3-VL-4B-Instruct": "qwen3-vl",
"Qwen/Qwen3-VL-8B-Instruct": "qwen3-vl",
"Qwen/Qwen3-VL-30B-A3B-Instruct": "qwen3-vl",
# Gemma 4 instruction checkpoints share Google's canonical turn/tool
# grammar and dynamic Gemma4Processor image expansion. E2B/E4B omit the
# disabled-thinking empty-channel prefill used by the 26B/31B revision;
# Gemma4Renderer detects that small template variant per tokenizer.
"google/gemma-4-E2B-it": "gemma4",
"google/gemma-4-E4B-it": "gemma4",
"google/gemma-4-26B-A4B-it": "gemma4",
"google/gemma-4-31B-it": "gemma4",
# GLM-5 family (GLM-4.7 reuses the GLM-5 template).
"zai-org/GLM-5": "glm-5",
"zai-org/GLM-5-FP8": "glm-5",
@@ -1043,6 +982,9 @@ MODEL_RENDERER_MAP: dict[str, str] = {
# DeepSeek R1 (reasoning).
"deepseek-ai/DeepSeek-R1": "deepseek-r1",
"deepseek-ai/DeepSeek-R1-0528": "deepseek-r1",
# DeepSeek V4 Flash 0731 uses the repository's Python DSML encoder (the
# tokenizer intentionally ships no Jinja chat_template).
"deepseek-ai/DeepSeek-V4-Flash-0731": "deepseek-v4",
# Kimi K2 (K2.5 and K2.6 share the K2.5 template, distinct from K2).
"moonshotai/Kimi-K2-Instruct": "kimi-k2",
"moonshotai/Kimi-K2.5": "kimi-k2.5",
@@ -1056,6 +998,9 @@ MODEL_RENDERER_MAP: dict[str, str] = {
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "nemotron-3",
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16": "nemotron-3-ultra",
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8": "nemotron-3-ultra",
# Nemotron 3.5 (Lightning). Its template is the Ultra variant's minus the
# effort kwarg (``nemotron-3.5``).
"nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16": "nemotron-3.5",
# Llama 3.2 (Instruct). Tested against the gated meta-llama repos and
# the unrestricted unsloth/... mirror, which ships a byte-identical
# chat template. ``Llama3Renderer`` defaults ``date_string`` to
@@ -1064,13 +1009,19 @@ MODEL_RENDERER_MAP: dict[str, str] = {
# construction to pin a different date.
"meta-llama/Llama-3.2-1B-Instruct": "llama-3",
"meta-llama/Llama-3.2-3B-Instruct": "llama-3",
# Poolside Laguna. The two checkpoints ship different chat templates,
# each mirrored by its own renderer class.
# Poolside Laguna. These checkpoints ship distinct chat templates, each
# mirrored by its own renderer class/config discriminator.
"poolside/Laguna-XS.2": "laguna-xs.2",
"poolside/Laguna-M.1": "laguna-m.1",
"poolside/Laguna-XS-2.1": "laguna-xs-2.1",
"poolside/Laguna-S-2.1": "laguna-s-2.1",
# GPT-OSS.
"openai/gpt-oss-20b": "gpt-oss",
"openai/gpt-oss-120b": "gpt-oss",
# Thinking Machines Inkling checkpoints share byte-identical tokenizer,
# chat-template, and processor assets (vision + audio; transformers >= 5.14).
"thinkingmachines/Inkling": "inkling",
"thinkingmachines/Inkling-Small": "inkling",
# Tencent Hunyuan Hy3 (295B-A21B MoE). The FP8 checkpoint shares the same
# tokenizer and chat template. Hy3-preview is deliberately unmapped: it
# ships an older, incompatible template (un-suffixed special tokens,
@@ -1093,6 +1044,10 @@ MULTIMODAL_MODELS: dict[str, set[str]] = {
"Qwen/Qwen3-VL-4B-Instruct": {"image"},
"Qwen/Qwen3-VL-8B-Instruct": {"image"},
"Qwen/Qwen3-VL-30B-A3B-Instruct": {"image"},
"google/gemma-4-E2B-it": {"image"},
"google/gemma-4-E4B-it": {"image"},
"google/gemma-4-26B-A4B-it": {"image"},
"google/gemma-4-31B-it": {"image"},
# Qwen3.5 is itself a VLM family (HF tag ``image-text-to-text``,
# processor class ``Qwen3VLProcessor``) — same vision tokens and
# image-processor as Qwen3-VL, with a different tool-call format.
@@ -1106,6 +1061,9 @@ MULTIMODAL_MODELS: dict[str, set[str]] = {
# Qwen3.6 extends Qwen3.5's chat template; same VL bits, only
# tool-call argument serialization differs.
"Qwen/Qwen3.6-35B-A3B": {"image"},
# Qwen3.8 adds reasoning-effort control and preserves thinking by default.
"Qwen/Qwen3.8-27B": {"image"},
"Qwen/Qwen3.8-Flash-Next": {"image"},
# Kimi K2.5 / K2.6 are unified VLMs (HF tag ``image-text-to-text``)
# with custom processor (``KimiK25Processor`` + ``KimiK25VisionProcessor``).
# Vision wrap is different from Qwen-VL:
@@ -1115,9 +1073,30 @@ MULTIMODAL_MODELS: dict[str, set[str]] = {
# ``grid_thws``.
"moonshotai/Kimi-K2.5": {"image"},
"moonshotai/Kimi-K2.6": {"image"},
"thinkingmachines/Inkling": {"image", "audio"},
"thinkingmachines/Inkling-Small": {"image", "audio"},
}
_TRANSFORMERS_INSTALL_HINT = (
"Install the optional dependency with "
"`pip install 'renderers[transformers]'` (or "
"`uv add 'renderers[transformers]'`). Text-only renderers work without "
"it when constructed with a compatible tokenizer object."
)
def _require_transformers(feature: str) -> Any:
"""Return ``transformers`` or raise an actionable optional-extra error."""
try:
import transformers
except ImportError as exc:
raise ImportError(
f"{feature} requires Transformers. {_TRANSFORMERS_INSTALL_HINT}"
) from exc
return transformers
def _model_has_vision_config(model_name: str) -> bool:
"""Return True if the HF config for ``model_name`` declares vision inputs.
@@ -1128,13 +1107,26 @@ def _model_has_vision_config(model_name: str) -> bool:
match what the trainer reconstructs — a class of bug the renderer
abstraction exists to prevent.
Returns False on any AutoConfig failure (offline, gated, missing) so
a flaky HF probe never blocks a legitimate text-only fine-tune.
Returns False on remote/config failures so a flaky HF probe never blocks a
legitimate text-only fine-tune. When Transformers itself is unavailable,
however, auto-resolution cannot safely distinguish an unknown text model
from an unknown VLM; callers must install the extra or choose an explicit
renderer config.
"""
try:
from transformers import AutoConfig
cfg = AutoConfig.from_pretrained(model_name, trust_remote_code=False)
transformers = _require_transformers("Auto-resolving an unregistered model")
except ImportError as exc:
raise ImportError(
f"Cannot auto-resolve unregistered model {model_name!r} without "
"checking whether it is multimodal. Install "
"`renderers[transformers]`, or pass an explicit typed renderer "
"config such as `DefaultRendererConfig()` for a known text-only "
"model."
) from exc
try:
cfg = transformers.AutoConfig.from_pretrained(
model_name, trust_remote_code=False
)
except Exception:
return False
# Most VLM configs nest a vision tower as ``vision_config`` (Qwen-VL,
@@ -1158,8 +1150,8 @@ def _model_has_vision_config(model_name: str) -> bool:
# Pinning the revision keeps the trust narrow: even with
# ``trust_remote_code=True``, transformers downloads / executes the
# tokenizer Python from this exact commit only. A future malicious push
# to the Moonshot HF repo doesn't auto-propagate to anyone using
# ``create_renderer_pool``. Bump these SHAs deliberately, with review.
# to the Moonshot HF repo doesn't auto-propagate to callers of
# ``load_tokenizer``. Bump these SHAs deliberately, with review.
TRUSTED_REVISIONS: dict[str, str] = {
"moonshotai/Kimi-K2-Instruct": "fd1984e2b7a3350dbf7305fe73a4ede25c14de50",
"moonshotai/Kimi-K2.5": "4d01dfe0332d63057c186e0b262165819efb6611",
@@ -1292,7 +1284,9 @@ def load_tokenizer(model_name_or_path: str):
those exact IDs we load tokenizer files from the audited unrestricted
``unsloth`` mirrors instead, then restore ``tokenizer.name_or_path`` to
the requested Meta ID so auto-resolution still selects ``Llama3Renderer``.
Requires the ``renderers[transformers]`` extra.
"""
_require_transformers("Loading a tokenizer")
load_name_or_path = _tokenizer_source_for(model_name_or_path)
kwargs = _tokenizer_load_kwargs(load_name_or_path)
tok = _load_tokenizer_via_auto(load_name_or_path, **kwargs)
@@ -1308,22 +1302,35 @@ def _populate_registry():
return
from renderers.deepseek_r1 import DeepSeekR1Renderer
from renderers.deepseek_v3 import DeepSeekV3Renderer
from renderers.deepseek_v4 import DeepSeekV4Renderer
from renderers.default import DefaultRenderer
from renderers.glm5 import GLM5Renderer, GLM51Renderer
from renderers.glm45 import GLM45Renderer
from renderers.gpt_oss import GptOssRenderer
from renderers.gemma4 import Gemma4Renderer
from renderers.hy3 import Hy3Renderer
from renderers.inkling import InklingRenderer
from renderers.kimi_k2 import KimiK2Renderer
from renderers.kimi_k25 import KimiK25Renderer
from renderers.laguna_xs2 import LagunaXS2Renderer, LagunaXS21Renderer
from renderers.laguna_s21 import LagunaS21Renderer
from renderers.laguna_xs2 import (
LagunaM1Renderer,
LagunaXS2Renderer,
LagunaXS21Renderer,
)
from renderers.llama_3 import Llama3Renderer
from renderers.minimax_m2 import MiniMaxM2Renderer
from renderers.nemotron3 import Nemotron3Renderer, Nemotron3UltraRenderer
from renderers.nemotron3 import (
Nemotron3Renderer,
Nemotron3UltraRenderer,
Nemotron35Renderer,
)
from renderers.prime_qwen3 import PrimeQwen3Renderer
from renderers.qwen3 import Qwen3Renderer
from renderers.qwen3_vl import Qwen3VLRenderer
from renderers.qwen35 import Qwen35Renderer
from renderers.qwen36 import Qwen36Renderer
from renderers.qwen38 import Qwen38Renderer
RENDERER_REGISTRY.update(
{
@@ -1331,65 +1338,34 @@ def _populate_registry():
"qwen3": Qwen3Renderer,
"prime-qwen3": PrimeQwen3Renderer,
"qwen3-vl": Qwen3VLRenderer,
"gemma4": Gemma4Renderer,
"qwen3.5": Qwen35Renderer,
"qwen3.6": Qwen36Renderer,
"qwen3.8": Qwen38Renderer,
"glm-5": GLM5Renderer,
"glm-5.1": GLM51Renderer,
"glm-4.5": GLM45Renderer,
"minimax-m2": MiniMaxM2Renderer,
"deepseek-v3": DeepSeekV3Renderer,
"deepseek-r1": DeepSeekR1Renderer,
"deepseek-v4": DeepSeekV4Renderer,
"hy3": Hy3Renderer,
"inkling": InklingRenderer,
"kimi-k2": KimiK2Renderer,
"kimi-k2.5": KimiK25Renderer,
"laguna-xs.2": LagunaXS2Renderer,
"laguna-m.1": LagunaM1Renderer,
"laguna-xs-2.1": LagunaXS21Renderer,
"laguna-s-2.1": LagunaS21Renderer,
"llama-3": Llama3Renderer,
"nemotron-3": Nemotron3Renderer,
"nemotron-3-ultra": Nemotron3UltraRenderer,
"nemotron-3.5": Nemotron35Renderer,
"gpt-oss": GptOssRenderer,
}
)
def create_renderer_pool(
tokenizer_name_or_path: str,
config: RendererConfig | None = None,
*,
size: int = 16,
chat_template_kwargs: Mapping[str, Any] | None = None,
) -> RendererPool:
"""Create a RendererPool with *size* independent tokenizer copies.
Each slot loads its own tokenizer so threads never share mutable
state. HuggingFace fast tokenizers release the GIL during Rust
encoding, so threads achieve real parallelism.
``config`` is the typed renderer config (one of the variants of
:data:`renderers.RendererConfig`). Defaults to
:class:`AutoRendererConfig`, which resolves to a concrete renderer
via ``MODEL_RENDERER_MAP`` at construction time using the loaded
tokenizer's name. ``chat_template_kwargs`` are merged into the
resolved concrete config and validated before renderer construction.
Every slot in the pool shares the same config; to run a different
config, build a different pool.
Tokenizers load via ``load_tokenizer`` — see its docstring for the
``trust_remote_code`` policy (default off; Moonshot Kimi-K2 family
opts in with a pinned ``revision``).
"""
def factory() -> Renderer:
tokenizer = load_tokenizer(tokenizer_name_or_path)
return create_renderer(
tokenizer,
config,
chat_template_kwargs=chat_template_kwargs,
)
return RendererPool(factory, size=size)
def create_renderer(
tokenizer,
config: RendererConfig | None = None,
@@ -1399,7 +1375,8 @@ def create_renderer(
"""Create a Renderer from a typed config.
Args:
tokenizer: HuggingFace tokenizer instance.
tokenizer: An object satisfying :class:`Tokenizer`; the generic
fallback additionally requires :class:`ChatTemplateTokenizer`.
config: Typed renderer config — one of the variants of
:data:`renderers.RendererConfig`. ``None`` defaults to
:class:`AutoRendererConfig`, which resolves to a concrete
@@ -1415,10 +1392,11 @@ def create_renderer(
config from ``tokenizer.name_or_path`` and then validates these
kwargs against that config.
Selecting the auto-renderer for a model without a registered
renderer falls back to :class:`DefaultRenderer` for text-only models
and raises for VLMs (where ``apply_chat_template`` would silently
drop images).
Selecting the auto-renderer for a model without a registered renderer
probes Hugging Face ``AutoConfig`` before falling back to
:class:`DefaultRenderer`, so unknown VLMs fail instead of silently dropping
media. Without the ``transformers`` extra, pass an explicit renderer config
for unregistered model names.
"""
_populate_registry()
@@ -1443,12 +1421,31 @@ def _merge_chat_template_kwargs(
return config
if not isinstance(chat_template_kwargs, Mapping):
raise TypeError("chat_template_kwargs must be a mapping.")
kwargs = dict(chat_template_kwargs)
config_cls = type(config)
allowed = config_cls.template_field_names()
if config_cls._allow_opaque_template_kwargs:
reserved = frozenset(config_cls.model_fields) - allowed - {"name"}
unsupported = frozenset(kwargs) & reserved
else:
unsupported = frozenset(kwargs) - allowed
if unsupported:
allowed_text = (
"opaque Jinja kwargs"
if config_cls._allow_opaque_template_kwargs
else ", ".join(sorted(allowed)) or "(none)"
)
raise ValueError(
f"Unsupported chat_template_kwargs for {config.name!r}: "
f"{sorted(unsupported)}. Allowed: {allowed_text}. Pass "
"renderer-internal options through the typed config instead."
)
data: dict[str, Any] = {"name": config.name}
for field_name in config.__pydantic_fields_set__:
data[field_name] = getattr(config, field_name)
data.update(getattr(config, "model_extra", None) or {})
data.update(dict(chat_template_kwargs))
return type(config).model_validate(data)
data.update(kwargs)
return config_cls.model_validate(data)
def _resolve_renderer_config(
@@ -1782,36 +1779,122 @@ def trim_to_turn_close(
return previous_ids
def _get_offset_tokenizer(tokenizer):
"""Assert ``tokenizer`` supports ``return_offsets_mapping=True``.
class AttributedTextSegments(list[tuple[int, bool]]):
"""Token/content pairs with an explicit attribution-availability flag."""
def __init__(
self,
values=(),
*,
has_content_attribution: bool,
) -> None:
super().__init__(values)
self.has_content_attribution = has_content_attribution
def _get_offset_tokenizer(tokenizer: Tokenizer) -> OffsetTokenizer | None:
"""Return ``tokenizer`` when it supports character offsets, else ``None``.
Hand-coded renderers concatenate scaffold + body in one BPE pass to
preserve cross-boundary merges, then attribute each resulting token
back to its source segment via the fast tokenizer's
``offset_mapping`` (see :func:`attribute_text_segments`). The
contract: every BYO tokenizer must be a fast tokenizer with offset
support. Tokenizers loaded via :func:`load_tokenizer` are
``PreTrainedTokenizerFast`` instances that satisfy this trivially.
``offset_mapping`` (see :func:`attribute_text_segments`). Tokenizers
loaded via :func:`load_tokenizer` are ``PreTrainedTokenizerFast``
instances that satisfy this capability, but BYO tokenizers need not.
"""
call = getattr(tokenizer, "__call__", None)
if not callable(call):
return None
try:
tokenizer("a", add_special_tokens=False, return_offsets_mapping=True)
except (NotImplementedError, ValueError, TypeError) as exc:
raise RuntimeError(
"Hand-coded renderers require a fast tokenizer with "
"``return_offsets_mapping=True`` support for body/scaffold "
"attribution. Pass a tokenizer loaded via "
"``renderers.base.load_tokenizer``, or any "
"``transformers.PreTrainedTokenizerFast`` instance."
) from exc
return tokenizer
encoding = call("a", add_special_tokens=False, return_offsets_mapping=True)
encoding["input_ids"]
encoding["offset_mapping"]
except (KeyError, NotImplementedError, TypeError, ValueError):
return None
return cast(OffsetTokenizer, tokenizer)
def _infer_offsets_from_decode(
tokenizer: Tokenizer,
token_ids: list[int],
text: str,
) -> list[tuple[int, int]] | None:
"""Recover token character spans from an exact decoder round-trip.
This is a narrow fallback for metadata that does not require exposing
content attribution. Some renderers join text from multiple messages in a
single BPE pass, so they still need to associate the resulting tokens with
the right message when a BYO tokenizer has no native offset mapping.
Decoding individual tokens is linear and exact for the common BPE/SentencePiece
backends. Byte-fallback tokenizers can require multiple tokens before text
becomes valid, so a validated cumulative-prefix pass handles that case.
If either strategy cannot reconstruct ``text`` exactly, callers must use a
conservative renderer-specific message-index fallback. This helper never
upgrades the tokenizer's content-attribution capability: ``is_content``
remains unavailable without native offsets.
"""
def decode(ids: list[int]) -> str | None:
variants = (
{"skip_special_tokens": False, "clean_up_tokenization_spaces": False},
{"skip_special_tokens": False},
{},
)
for kwargs in variants:
try:
decoded = tokenizer.decode(ids, **kwargs)
except TypeError:
continue
except (KeyError, NotImplementedError, UnicodeError, ValueError):
return None
return decoded if isinstance(decoded, str) else None
return None
pieces: list[str] = []
for token_id in token_ids:
piece = decode([token_id])
if piece is None:
break
pieces.append(piece)
if len(pieces) == len(token_ids) and "".join(pieces) == text:
offsets: list[tuple[int, int]] = []
position = 0
for piece in pieces:
end = position + len(piece)
offsets.append((position, end))
position = end
return offsets
offsets = []
previous_end = 0
for end_index in range(1, len(token_ids) + 1):
prefix = decode(token_ids[:end_index])
if prefix is None or len(prefix) < previous_end or not text.startswith(prefix):
return None
current_end = len(prefix)
offsets.append((previous_end, current_end))
previous_end = current_end
if previous_end != len(text):
return None
return offsets
def _content_mask_or_empty(
tokenizer: Tokenizer, content_mask: list[bool]
) -> list[bool]:
"""Return exact content attribution, or the empty-list unavailable sentinel."""
if _get_offset_tokenizer(tokenizer) is None:
return []
return content_mask
def attribute_text_segments(
tokenizer,
tokenizer: Tokenizer,
segments: "list[tuple[str, bool]]",
*,
overlap_is_content: bool = False,
) -> "list[tuple[int, bool]]":
) -> AttributedTextSegments:
"""Tokenize concatenated segments as a single BPE pass and return
``(token_id, is_content)`` pairs.
@@ -1839,23 +1922,29 @@ def attribute_text_segments(
every body byte inside the ``is_content=True`` run at the cost of a
few adjacent wrap bytes.
Requires a HuggingFace fast tokenizer with offset tracking. Every
model in ``MODEL_RENDERER_MAP`` ships one, so the offset lookup
always succeeds for tokenizers obtained via :func:`load_tokenizer`.
BYO tokenizers must be a ``PreTrainedTokenizerFast`` (or anything
else exposing ``return_offsets_mapping=True``); slow tokenizers
aren't supported — BPE drift at the wrap/body boundary would
defeat the whole point.
When ``tokenizer`` implements :class:`OffsetTokenizer`, the result's
``has_content_attribution`` flag is true and each bool is exact. For a
basic :class:`Tokenizer`, the joined text is still encoded in one pass so
token IDs remain identical, but the bools are placeholders and
``has_content_attribution`` is false. Renderers propagate that state as an
empty ``RenderedTokens.is_content`` list rather than exposing a partial or
inaccurate mask.
Empty input or empty joined text returns an empty list.
"""
if not segments:
return []
return AttributedTextSegments([], has_content_attribution=True)
full_text = "".join(text for text, _ in segments)
if not full_text:
return []
return AttributedTextSegments([], has_content_attribution=True)
offset_tokenizer = _get_offset_tokenizer(tokenizer)
if offset_tokenizer is None:
token_ids = tokenizer.encode(full_text, add_special_tokens=False)
return AttributedTextSegments(
((token_id, False) for token_id in token_ids),
has_content_attribution=False,
)
encoding = offset_tokenizer(
full_text,
add_special_tokens=False,
@@ -1910,7 +1999,7 @@ def attribute_text_segments(
# the last non-empty segment's bit.
pass
out.append((tok_id, is_content))
return out
return AttributedTextSegments(out, has_content_attribution=True)
def reject_assistant_in_extension(new_messages: list[Message]) -> bool:
+146 -46
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,17 @@ 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 +53,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 +110,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.
@@ -150,10 +138,64 @@ def parse_generate_response(raw: bytes) -> dict[str, Any]:
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,
@@ -236,9 +278,7 @@ 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)
@@ -292,14 +332,9 @@ async def generate(
choice = (data.get("choices") or [{}])[0]
completion_ids = choice.get("token_ids") or []
parsed = await _maybe_offload(
renderer, lambda: renderer.parse_response(completion_ids, tools=tools)
)
completion_logprobs = _parse_completion_logprobs(choice, completion_ids)
# 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 []]
parsed = renderer.parse_response(completion_ids, tools=tools)
routed_experts = choice.get("routed_experts")
kept_tokens = choice.get("kept_tokens")
@@ -346,7 +381,7 @@ async def generate(
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 +394,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 +405,19 @@ 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.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)
raise NotImplementedError(
f"Multimodal serialization not implemented for {renderer_cls.__name__}. "
@@ -392,6 +425,70 @@ def _build_mm_features(
)
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 +502,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:
+367 -24
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.
@@ -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,6 +155,8 @@ 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):
@@ -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`."""
@@ -243,10 +271,57 @@ class Qwen36RendererConfig(BaseRendererConfig):
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):
_reject_thinking_retention_conflict(
self,
"preserve_thinking",
true_implies="all",
false_implies="tool_cycle",
)
return self
class Qwen3VLRendererConfig(BaseRendererConfig):
"""Qwen3-VL renderer config."""
name: Literal["qwen3-vl"] = "qwen3-vl"
_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):
_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
@@ -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`."""
@@ -310,6 +415,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 +443,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.
@@ -380,6 +495,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):
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 +571,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``
@@ -449,6 +628,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 +641,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 +659,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 +674,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 +707,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 +717,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 +761,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 +780,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 +798,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
@@ -600,6 +843,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`."""
@@ -622,6 +868,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):
_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 +909,7 @@ class DeepSeekV3RendererConfig(BaseRendererConfig):
"""
name: Literal["deepseek-v3"] = "deepseek-v3"
_template_fields = frozenset()
class DeepSeekR1RendererConfig(BaseRendererConfig):
@@ -648,6 +927,48 @@ 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):
_reject_thinking_retention_conflict(
self,
"drop_thinking",
true_implies="tool_cycle",
false_implies="all",
)
return self
RendererConfig = Annotated[
@@ -658,22 +979,29 @@ RendererConfig = Annotated[
PrimeQwen3RendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen38RendererConfig,
Qwen3VLRendererConfig,
Gemma4RendererConfig,
GLM5RendererConfig,
GLM51RendererConfig,
GLM45RendererConfig,
GptOssRendererConfig,
Hy3RendererConfig,
InklingRendererConfig,
KimiK2RendererConfig,
KimiK25RendererConfig,
LagunaXS2RendererConfig,
LagunaM1RendererConfig,
LagunaXS21RendererConfig,
LagunaS21RendererConfig,
Llama3RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
Nemotron35RendererConfig,
DeepSeekV3RendererConfig,
DeepSeekR1RendererConfig,
DeepSeekV4RendererConfig,
],
Field(discriminator="name"),
]
@@ -698,22 +1026,29 @@ _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-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,
}
@@ -747,22 +1082,30 @@ __all__ = [
"DefaultRendererConfig",
"DeepSeekR1RendererConfig",
"DeepSeekV3RendererConfig",
"DeepSeekV4RendererConfig",
"GLM45RendererConfig",
"GLM51RendererConfig",
"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",
+7 -5
View File
@@ -14,13 +14,13 @@ from __future__ import annotations
import json
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,
@@ -63,7 +63,7 @@ class DeepSeekV3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: DeepSeekV3RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -260,7 +260,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),
)
@@ -409,7 +409,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),
)
+859
View File
@@ -0,0 +1,859 @@
"""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
_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``."""
_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]
@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(
_REASONING_EFFORT_PROMPTS[self.config.reasoning_effort],
-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
) -> ParsedResponse:
return parse_deepseek_v4(
self._tokenizer,
token_ids,
stop_ids={self._eos},
thinking_enabled=self.config.enable_thinking,
think_end_id=self._think_end,
dsml_id=self._dsml,
)
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
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"]
+2 -3
View File
@@ -11,9 +11,8 @@ from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
ChatTemplateTokenizer,
Message,
ParsedResponse,
RenderedTokens,
@@ -92,7 +91,7 @@ class DefaultRenderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: ChatTemplateTokenizer,
config: DefaultRendererConfig | None = None,
):
cfg = config or DefaultRendererConfig()
+1369
View File
File diff suppressed because it is too large Load Diff
+7 -5
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,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -55,7 +55,7 @@ class GLM45Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: GLM45RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -262,7 +262,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),
)
@@ -449,7 +449,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),
)
+7 -5
View File
@@ -14,13 +14,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,
@@ -64,7 +64,7 @@ class GLM5Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: GLM5RendererConfig | GLM51RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -284,7 +284,7 @@ class GLM5Renderer:
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),
)
@@ -466,7 +466,9 @@ class GLM5Renderer:
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),
)
+7 -5
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,
@@ -123,7 +123,7 @@ class GptOssRenderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: GptOssRendererConfig | None = None,
):
"""Initialise the renderer.
@@ -462,7 +462,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),
)
@@ -598,7 +598,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),
)
+45 -14
View File
@@ -27,13 +27,15 @@ 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,
_get_offset_tokenizer,
_infer_offsets_from_decode,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -74,7 +76,7 @@ class Hy3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Hy3RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -239,13 +241,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 +278,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 +461,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),
)
@@ -700,7 +729,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),
)
+997
View File
@@ -0,0 +1,997 @@
"""Inkling renderer — ``thinkingmachines/Inkling`` and ``Inkling-Small``.
Inkling's chat template is **token-delimited**: every structural piece is a
single atomic special token, so there is no BOS and text between markers BPEs
independently. The message stream is a flat sequence of role-tagged,
``<|end_message|>``-terminated blocks:
<|message_{role}|> [ <|content_{kind}|> {body} ] <|end_message|>
with these pieces (all single tokens):
- Roles: ``<|message_user|>`` / ``<|message_model|>`` (assistant) /
``<|message_system|>`` / ``<|message_tool|>``.
- Content kinds: ``<|content_text|>``, ``<|content_thinking|>`` (assistant
reasoning), ``<|content_image|>``, ``<|content_audio_input|>`` (… ``<|audio_end|>``),
``<|content_invoke_tool_json|>`` (tool call), ``<|content_xml|>`` (tools decl).
- ``<|content_model_end_sampling|>`` closes an assistant turn (also the eos).
Ordering: an optional tools declaration comes first, then a one-off
``Thinking effort level: {N}`` system message emitted immediately before the
first non-system message (or at the very end if the whole conversation is
system-only). See :class:`renderers.configs.InklingRendererConfig` for the
effort knob.
Multimodal parity matches the native ``InklingProcessor`` (transformers
≥ 5.14): the template emits a single placeholder per media item, and the
processor **expands** it — image → ``num_patches`` copies of ``<|unused_200054|>``,
audio → one ``<|unused_200053|>`` per mel frame. This renderer expands the same
way (counts taken straight from the processor) and ships ``pixel_values`` /
``audio_input_ids`` in :class:`~renderers.base.MultiModalData`. The processor is
a native transformers class, so it loads with **no** ``trust_remote_code``.
"""
from __future__ import annotations
import hashlib
import json
from collections.abc import Mapping
from typing import Any
import numpy as np
from renderers.base import (
Content,
Message,
MultiModalData,
ParsedResponse,
PlaceholderRange,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_require_transformers,
extract_message_tool_names,
reject_assistant_in_extension,
resolve_thinking_retention,
should_rerender_for_thinking_retention,
trim_to_turn_close,
)
from renderers.configs import INKLING_EFFORT_MAP, InklingRendererConfig
from renderers.parsing import parse_inkling
from renderers.qwen3_vl import _image_hash, _load_pil_image
# Content-part ``type`` values the template maps to each modality. Untyped
# parts (``type`` absent) are treated as text — matching the Jinja template's
# ``part.type is not defined or part.type in ("text", "input_text")`` gate.
_TEXT_TYPES = frozenset({"text", "input_text"})
_IMAGE_TYPES = frozenset({"image", "input_image", "image_url"})
_AUDIO_TYPES = frozenset({"audio", "input_audio", "audio_url"})
_VIDEO_TYPES = frozenset({"video", "input_video", "video_url"})
def _format_effort_number(num: float) -> str:
"""Render the effort number exactly as the chat template does.
``0.0`` prints as ``"0"``; every other value uses Python ``str`` of the
float (``0.9`` → ``"0.9"``), which matches Jinja's float stringification
for the values in :data:`INKLING_EFFORT_MAP` and arbitrary user floats.
"""
return "0" if num == 0.0 else str(num)
def _classify_part(part: Any) -> tuple[str, Any]:
"""Classify a content-list part → ``(kind, data)``.
``kind`` is one of ``"text"``/``"image"``/``"audio"``/``"video"``.
Mirrors the template's part dispatch: a bare string or an untyped/text part
is text; unknown part types raise just as the template does. Silently
dropping a part would produce a token stream that does not represent the
caller's conversation.
"""
if isinstance(part, str):
return "text", part
if not isinstance(part, Mapping):
raise ValueError(f"Unexpected Inkling content part: {part!r}")
part = dict(part)
ptype = part.get("type")
if ptype is None or ptype in _TEXT_TYPES:
text = part.get("text")
return "text", text if isinstance(text, str) else ""
if ptype in _IMAGE_TYPES:
return "image", part
if ptype in _AUDIO_TYPES:
return "audio", part
if ptype in _VIDEO_TYPES:
return "video", part
raise ValueError(f"Unsupported Inkling content part type: {ptype!r}")
def _load_inkling_image(part: Any):
"""Resolve Inkling's ``input_image`` alias before shared image loading."""
if isinstance(part, Mapping) and part.get("type") == "input_image":
normalized = dict(part)
raw = normalized.get("input_image")
if isinstance(raw, Mapping):
for key in ("image", "image_url", "url", "path"):
if key in raw:
normalized[key] = raw[key]
break
else:
normalized["image"] = raw
else:
normalized["image"] = raw
part = normalized
return _load_pil_image(part)
def _load_audio(part: Any) -> tuple[np.ndarray, int]:
"""Resolve an audio content part to ``(waveform, sampling_rate)``.
Accepts a raw mono waveform (``np.ndarray`` / list of floats) or a
HuggingFace-``datasets``-style ``{"array", "sampling_rate"}`` dict, under
``part["audio"]`` / ``["input_audio"]`` / ``["audio_url"]`` or the part
itself. Decoding bytes / paths / URLs is out of scope (the processor's
``apply_chat_template`` does that upstream) — those raise so the caller
passes a decoded waveform.
"""
data: Any = part
if isinstance(part, dict):
for key in ("audio", "input_audio", "audio_url"):
if key in part:
data = part[key]
break
sampling_rate = 16000
if isinstance(data, dict):
sampling_rate = int(data.get("sampling_rate", sampling_rate))
data = data.get("array")
if isinstance(data, str) or data is None:
raise NotImplementedError(
"InklingRenderer needs a decoded audio waveform (np.ndarray or a "
"{'array', 'sampling_rate'} dict); byte/path/URL decoding is not "
"supported here."
)
return np.asarray(data, dtype=np.float32), sampling_rate
def _audio_hash(wav: np.ndarray, sampling_rate: int) -> str:
# Sampling rate is part of the identity: identical samples at different
# rates yield different mel frames / sidecar tensors, so they must not
# share an ``mm_hashes`` entry (media IDs must be unique).
h = hashlib.sha256(str(sampling_rate).encode())
h.update(np.ascontiguousarray(wav).tobytes())
return h.hexdigest()
class InklingRenderer:
"""Deterministic renderer for both Thinking Machines Inkling checkpoints.
Text / tools / reasoning render to byte-parity with
``tokenizer.apply_chat_template``; image / audio render to byte-parity with
the native ``InklingProcessor`` (placeholder expansion included). Satisfies
the :class:`~renderers.base.MultimodalRenderer` protocol.
"""
def __init__(
self,
tokenizer: Tokenizer,
config: InklingRendererConfig | None = None,
*,
processor: Any = None,
):
self._tokenizer = tokenizer
self._processor = processor
self.config = config or InklingRendererConfig()
# Inkling always renders historical reasoning (the template has no
# history-dropping knob), so the effective bridge policy is "all".
self.effective_thinking_retention = resolve_thinking_retention(
self.config, "all"
)
eff = self.config.reasoning_effort
self._effort_num: float = (
INKLING_EFFORT_MAP[eff.strip()] if isinstance(eff, str) else float(eff)
)
# Role markers.
self._message_user = self._token_id("<|message_user|>")
self._message_model = self._token_id("<|message_model|>")
self._message_system = self._token_id("<|message_system|>")
self._message_tool = self._token_id("<|message_tool|>")
# Content-kind markers.
self._content_text = self._token_id("<|content_text|>")
self._content_thinking = self._token_id("<|content_thinking|>")
self._content_image = self._token_id("<|content_image|>")
self._content_audio_input = self._token_id("<|content_audio_input|>")
self._content_xml = self._token_id("<|content_xml|>")
self._content_invoke_tool_json = self._token_id("<|content_invoke_tool_json|>")
self._content_invoke_tool_text = self._token_id("<|content_invoke_tool_text|>")
self._content_model_end_sampling = self._token_id(
"<|content_model_end_sampling|>"
)
self._end_message = self._token_id("<|end_message|>")
self._audio_end = self._token_id("<|audio_end|>")
# Media soft-token placeholders (expanded per patch / mel frame).
self._image_pad = self._token_id("<|unused_200054|>")
self._audio_pad = self._token_id("<|unused_200053|>")
# eos: the model closes its turn with <|content_model_end_sampling|>.
self._endoftext = self._try_token_id("<|endoftext|>")
# Per-instance FIFO media caches (keyed by content hash).
self._image_cache: dict[str, tuple[Any, int]] = {}
self._audio_cache: dict[str, dict[str, Any]] = {}
@property
def mm_token_type_id_map(self) -> dict[int, int]:
"""Token-id → modality marker. Only the image placeholder carries a
vision marker (1); audio has no entry in the orchestrator's
image/video type map (the model consumes ``audio_input_ids`` directly)."""
return {self._image_pad: 1}
# ------------------------------------------------------------------
# Token / processor helpers
# ------------------------------------------------------------------
def _token_id(self, token: str) -> int:
tid = self._tokenizer.convert_tokens_to_ids(token)
assert isinstance(tid, int) and tid != self._tokenizer.unk_token_id, (
f"Special token {token!r} not found in tokenizer vocabulary"
)
return tid
def _try_token_id(self, token: str) -> int | None:
tid = self._tokenizer.convert_tokens_to_ids(token)
if not isinstance(tid, int) or tid == self._tokenizer.unk_token_id:
return None
return tid
def _encode(self, text: str) -> list[int]:
if not text:
return []
return self._tokenizer.encode(text, add_special_tokens=False)
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(
"InklingRenderer needs a processor to render image/audio "
"content. Pass processor=AutoProcessor.from_pretrained(name), "
"or load the tokenizer with a known name_or_path so the "
"processor can be auto-loaded."
)
# InklingProcessor is native in transformers >=5.14, so no
# trust_remote_code is required. Keep text-only rendering installable
# with older downstream pins and fail only when multimodal processing
# is actually requested.
transformers = _require_transformers("Auto-loading an Inkling processor")
try:
self._processor = transformers.AutoProcessor.from_pretrained(name)
except (ImportError, KeyError, ValueError) as exc:
raise RuntimeError(
"Inkling image/audio rendering requires Transformers >=5.14 "
"with native InklingProcessor support. Upgrade Transformers "
"and retry."
) from exc
return self._processor
def _process_image(self, pil, image_hash: str) -> tuple[Any, int]:
"""Return ``(processor_out, num_patches)`` for one image (cached).
``processor_out`` carries ``pixel_values`` (shape
``(num_patches, temporal, 40, 40, 3)``); ``num_patches`` is the count
of ``<|unused_200054|>`` placeholders the processor expands this image
into (``ceil(H/40) * (W//40 + 1)``)."""
cached = self._image_cache.get(image_hash)
if cached is not None:
return cached
out = self._get_processor().image_processor.preprocess(
[pil], return_tensors="pt"
)
num_patches = int(out["num_patches"][0])
if len(self._image_cache) >= self.config.image_cache_max:
self._image_cache.pop(next(iter(self._image_cache)))
self._image_cache[image_hash] = (out, num_patches)
return out, num_patches
def _process_audio(self, wav: np.ndarray, sampling_rate: int) -> dict[str, Any]:
"""Return the processor's ``{audio_input_ids, audio_input_ids_mask}``
for one clip (cached). The number of ``<|unused_200053|>`` placeholders
is ``audio_input_ids_mask[0].sum()`` (one per valid mel frame)."""
key = _audio_hash(wav, sampling_rate)
cached = self._audio_cache.get(key)
if cached is not None:
return cached
processed = self._get_processor()(
audio=[wav], sampling_rate=sampling_rate, return_tensors="pt"
)
if len(self._audio_cache) >= self.config.audio_cache_max:
self._audio_cache.pop(next(iter(self._audio_cache)))
self._audio_cache[key] = processed
return processed
# ------------------------------------------------------------------
# Render
# ------------------------------------------------------------------
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> RenderedTokens:
if not messages:
raise ValueError("No messages provided.")
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
mm_hashes: dict[str, list[str]] = {}
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
mm_items: dict[str, list[dict[str, Any]]] = {}
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_image(
part: Any,
msg_idx: int,
role_open,
*,
is_sampled: bool,
marker_is_content: bool,
) -> None:
pil = _load_inkling_image(part)
h = _image_hash(pil)
out, num_patches = self._process_image(pil, h)
role_open()
emit_special(
self._content_image,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
offset = len(tokens)
for _ in range(num_patches):
emit_special(
self._image_pad, msg_idx, is_sampled=is_sampled, is_content=True
)
emit_special(
self._end_message,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=num_patches)
)
mm_items.setdefault("image", []).append(
{"pixel_values": out["pixel_values"]}
)
def emit_audio(
part: Any,
msg_idx: int,
role_open,
*,
is_sampled: bool,
marker_is_content: bool,
) -> None:
wav, sr = _load_audio(part)
processed = self._process_audio(wav, sr)
n_frames = int(processed["audio_input_ids_mask"][0].sum())
role_open()
emit_special(
self._content_audio_input,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
offset = len(tokens)
for _ in range(n_frames):
emit_special(
self._audio_pad, msg_idx, is_sampled=is_sampled, is_content=True
)
emit_special(
self._audio_end,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
emit_special(
self._end_message,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
mm_hashes.setdefault("audio", []).append(_audio_hash(wav, sr))
mm_placeholders.setdefault("audio", []).append(
PlaceholderRange(offset=offset, length=n_frames)
)
mm_items.setdefault("audio", []).append(
{
"audio_input_ids": processed["audio_input_ids"],
"audio_input_ids_mask": processed["audio_input_ids_mask"],
}
)
tool_names = extract_message_tool_names(messages)
# ── Tools declaration (first, before the effort line) ──
if tools:
self._emit_tools(tools, emit_special, emit_text)
# ── Message loop; effort emitted once before the first non-system ──
effort_emitted = False
for i, msg in enumerate(messages):
role = msg.get("role", "")
if not effort_emitted and role != "system":
self._emit_effort(emit_special, emit_text)
effort_emitted = True
if role == "assistant":
self._render_assistant(
msg, i, emit_special, emit_text, emit_image, emit_audio
)
elif role == "tool":
self._render_tool(msg, i, tool_names[i], emit_special, emit_text)
elif role in ("system", "user"):
role_id = (
self._message_system if role == "system" else self._message_user
)
def role_open(_role_id=role_id, _i=i):
emit_special(_role_id, _i, is_sampled=False, is_content=False)
self._emit_content(
msg.get("content"),
i,
role_open=role_open,
is_sampled=False,
marker_is_content=False,
emit_special=emit_special,
emit_text=emit_text,
emit_image=emit_image,
emit_audio=emit_audio,
)
else:
raise ValueError(f"Unknown message role: {role!r}")
if not effort_emitted:
self._emit_effort(emit_special, emit_text)
# ── Generation prompt ──
if add_generation_prompt:
emit_special(self._message_model, -1, is_sampled=False, is_content=False)
mm_data: MultiModalData | None = None
if mm_hashes or mm_placeholders or mm_items:
mm_data = MultiModalData(
mm_hashes=mm_hashes,
mm_placeholders=mm_placeholders,
mm_items=mm_items,
)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=tool_names,
multi_modal_data=mm_data,
)
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 — args are native JSON, no schema coercion
) -> ParsedResponse:
return parse_inkling(
self._tokenizer,
token_ids,
stop_ids=set(self.get_stop_token_ids()),
message_model_id=self._message_model,
content_text_id=self._content_text,
content_thinking_id=self._content_thinking,
invoke_json_id=self._content_invoke_tool_json,
invoke_text_id=self._content_invoke_tool_text,
end_message_id=self._end_message,
)
def get_stop_token_ids(self) -> list[int]:
stop = [self._content_model_end_sampling]
if self._endoftext is not None:
stop.append(self._endoftext)
return stop
# ------------------------------------------------------------------
# Per-message emitters (shared by render + bridge)
# ------------------------------------------------------------------
def _emit_effort(self, emit_special, emit_text) -> None:
emit_special(self._message_system, -1, is_sampled=False, is_content=False)
emit_special(self._content_text, -1, is_sampled=False, is_content=False)
emit_text(
"Thinking effort level: " + _format_effort_number(self._effort_num),
-1,
is_sampled=False,
is_content=False,
)
emit_special(self._end_message, -1, is_sampled=False, is_content=False)
def _emit_tools(self, tools, emit_special, emit_text) -> None:
specs: list[dict[str, Any]] = []
for tool in tools:
fn = tool.get("function", tool) if isinstance(tool, dict) else tool
if not isinstance(fn, dict):
fn = {}
specs.append(
{
"description": fn.get("description") or "",
"name": fn.get("name"),
"parameters": fn.get("parameters") or {},
"type": (tool.get("type") if isinstance(tool, dict) else None)
or "function",
}
)
tools_json = json.dumps(
specs, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
emit_special(self._message_system, -1, is_sampled=False, is_content=False)
emit_text("tool_declare", -1, is_sampled=False, is_content=False)
emit_special(self._content_xml, -1, is_sampled=False, is_content=False)
emit_text(tools_json, -1, is_sampled=False, is_content=False)
emit_special(self._end_message, -1, is_sampled=False, is_content=False)
def _emit_content(
self,
content: Content | None,
msg_idx: int,
*,
role_open,
is_sampled: bool,
marker_is_content: bool,
emit_special,
emit_text,
emit_image,
emit_audio,
) -> None:
"""Emit a message's content as one or more role-tagged blocks.
String content is one ``<|content_text|>`` block (emitted even when
empty). List content is one block per part, each re-opening the role
via ``role_open`` — matching the template's per-part role re-emission.
``marker_is_content`` sets the ``is_content`` bit on the structural
markers (True for assistant, where every sampled token counts as body;
False for user/system, where markers are scaffold)."""
if isinstance(content, str):
role_open()
emit_special(
self._content_text,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
if content:
emit_text(content, msg_idx, is_sampled=is_sampled, is_content=True)
emit_special(
self._end_message,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
return
if not content:
return
for part in content:
kind, data = _classify_part(part)
if kind == "text":
role_open()
emit_special(
self._content_text,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
if data:
emit_text(data, msg_idx, is_sampled=is_sampled, is_content=True)
emit_special(
self._end_message,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
elif kind == "image":
emit_image(
data,
msg_idx,
role_open,
is_sampled=is_sampled,
marker_is_content=marker_is_content,
)
elif kind == "audio":
emit_audio(
data,
msg_idx,
role_open,
is_sampled=is_sampled,
marker_is_content=marker_is_content,
)
elif kind == "video":
raise NotImplementedError(
"Video parts are not supported by InklingRenderer."
)
def _render_tool(self, msg, msg_idx, inline_name, emit_special, emit_text) -> None:
"""Tool response: ``<|message_tool|>{name?}<|content_text|>{content}<|end_message|>``.
The name (resolved from ``msg['name']`` or the matching prior
assistant tool-call id) is structural routing info, so it is scaffold.
Only string content is rendered — the template drops list content in
tool messages."""
emit_special(self._message_tool, msg_idx, is_sampled=False, is_content=False)
if inline_name:
emit_text(inline_name, msg_idx, is_sampled=False, is_content=False)
emit_special(self._content_text, msg_idx, is_sampled=False, is_content=False)
content = msg.get("content")
if isinstance(content, str) and content:
emit_text(content, msg_idx, is_sampled=False, is_content=True)
emit_special(self._end_message, msg_idx, is_sampled=False, is_content=False)
def _render_assistant(
self, msg, msg_idx, emit_special, emit_text, emit_image, emit_audio
) -> None:
"""Assistant turn: optional reasoning block, content block(s), tool-call
blocks, then the ``<|content_model_end_sampling|>`` close.
The very first ``<|message_model|>`` is the generation-prompt-equivalent
(scaffold, never sampled); every token after it through the close is the
model's sampled emission, so ``is_content == sampled_mask`` holds across
the whole turn."""
reasoning = msg.get("reasoning_content")
reasoning = reasoning if isinstance(reasoning, str) and reasoning else ""
content = msg.get("content")
tool_calls = msg.get("tool_calls") or []
first = True
def model_tag():
nonlocal first
if first:
emit_special(
self._message_model, msg_idx, is_sampled=False, is_content=False
)
first = False
else:
emit_special(
self._message_model, msg_idx, is_sampled=True, is_content=True
)
if reasoning:
model_tag()
emit_special(
self._content_thinking, msg_idx, is_sampled=True, is_content=True
)
emit_text(reasoning, msg_idx, is_sampled=True, is_content=True)
emit_special(self._end_message, msg_idx, is_sampled=True, is_content=True)
self._emit_content(
content,
msg_idx,
role_open=model_tag,
is_sampled=True,
marker_is_content=True,
emit_special=emit_special,
emit_text=emit_text,
emit_image=emit_image,
emit_audio=emit_audio,
)
for tc in tool_calls:
name, args = self._tool_call_name_args(tc)
model_tag()
if name:
emit_text(name, msg_idx, is_sampled=True, is_content=True)
emit_special(
self._content_invoke_tool_json,
msg_idx,
is_sampled=True,
is_content=True,
)
emit_text(
self._invoke_json(name, args),
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._end_message, msg_idx, is_sampled=True, is_content=True)
emit_special(
self._content_model_end_sampling, msg_idx, is_sampled=True, is_content=True
)
@staticmethod
def _tool_call_name_args(tc: Any) -> tuple[str, Any]:
func = tc.get("function") if isinstance(tc, dict) else None
if not isinstance(func, dict):
func = tc if isinstance(tc, dict) else {}
name = func.get("name") or ""
args = func.get("arguments", {})
if isinstance(args, str):
try:
args = json.loads(args)
except (json.JSONDecodeError, ValueError) as exc:
raise TypeError(
"Inkling tool_calls[].function.arguments must be a JSON object."
) from exc
if not isinstance(args, dict):
raise TypeError(
"Inkling tool_calls[].function.arguments must be a JSON object."
)
return name, args
@staticmethod
def _invoke_json(name: str, args: Any) -> str:
"""``{"name":<name>,"args":<args>}`` with the template's compact,
key-sorted encoding."""
return (
'{"name":'
+ json.dumps(
name, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
+ ',"args":'
+ json.dumps(
args, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
+ "}"
)
# ------------------------------------------------------------------
# Bridge
# ------------------------------------------------------------------
def bridge_to_next_turn(
self,
previous_prompt_ids: list[int],
previous_completion_ids: list[int],
new_messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
previous_multi_modal_data: MultiModalData | None = None,
) -> "RenderedTokens | None":
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
if should_rerender_for_thinking_retention(
self.effective_thinking_retention, new_messages
):
return None
# A tool message whose name would be recovered from a prior-turn
# assistant tool-call id can't be resolved from ``new_messages`` alone
# (assistants are excluded), so a bridge would diverge from a full
# re-render — refuse and let the caller re-render.
for msg in new_messages:
if (
msg.get("role") == "tool"
and not msg.get("name")
and msg.get("tool_call_id")
):
return None
# Prior assistant turn closes with <|content_model_end_sampling|>;
# synthesise it on a truncated completion.
close_ids: set[int] = {self._content_model_end_sampling}
if self._endoftext is not None:
close_ids.add(self._endoftext)
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
close_ids,
synthesize_close=self._content_model_end_sampling,
)
if previous_ids is None:
return None
tokens: list[int] = list(previous_ids)
indices: list[int] = [-1] * len(previous_ids)
sampled: list[bool] = [False] * len(previous_ids)
content_mask: list[bool] = [False] * len(previous_ids)
new_hashes: dict[str, list[str]] = {}
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_image(
part, msg_idx, role_open, *, is_sampled, marker_is_content
) -> None:
pil = _load_inkling_image(part)
h = _image_hash(pil)
out, num_patches = self._process_image(pil, h)
role_open()
emit_special(
self._content_image,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
offset = len(tokens)
for _ in range(num_patches):
emit_special(
self._image_pad, msg_idx, is_sampled=is_sampled, is_content=True
)
emit_special(
self._end_message,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=num_patches)
)
new_items.setdefault("image", []).append(
{"pixel_values": out["pixel_values"]}
)
def emit_audio(
part, msg_idx, role_open, *, is_sampled, marker_is_content
) -> None:
wav, sr = _load_audio(part)
processed = self._process_audio(wav, sr)
n_frames = int(processed["audio_input_ids_mask"][0].sum())
role_open()
emit_special(
self._content_audio_input,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
offset = len(tokens)
for _ in range(n_frames):
emit_special(
self._audio_pad, msg_idx, is_sampled=is_sampled, is_content=True
)
emit_special(
self._audio_end,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
emit_special(
self._end_message,
msg_idx,
is_sampled=is_sampled,
is_content=marker_is_content,
)
new_hashes.setdefault("audio", []).append(_audio_hash(wav, sr))
new_placeholders.setdefault("audio", []).append(
PlaceholderRange(offset=offset, length=n_frames)
)
new_items.setdefault("audio", []).append(
{
"audio_input_ids": processed["audio_input_ids"],
"audio_input_ids_mask": processed["audio_input_ids_mask"],
}
)
tool_names = extract_message_tool_names(new_messages)
for i, msg in enumerate(new_messages):
role = msg.get("role")
if role == "tool":
self._render_tool(msg, i, tool_names[i], emit_special, emit_text)
elif role in ("system", "user"):
role_id = (
self._message_system if role == "system" else self._message_user
)
def role_open(_role_id=role_id, _i=i):
emit_special(_role_id, _i, is_sampled=False, is_content=False)
self._emit_content(
msg.get("content"),
i,
role_open=role_open,
is_sampled=False,
marker_is_content=False,
emit_special=emit_special,
emit_text=emit_text,
emit_image=emit_image,
emit_audio=emit_audio,
)
else:
return None
emit_special(self._message_model, -1, is_sampled=False, is_content=False)
# Merge carried-forward mm_data (prior turns) with this turn's items.
# Copy the per-modality lists (not just the outer dict) so appending
# this turn's items never mutates the 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
else {}
)
merged_placeholders = (
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
if 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
else {}
)
for modality, vals in new_hashes.items():
merged_hashes.setdefault(modality, []).extend(vals)
for modality, vals in new_placeholders.items():
merged_placeholders.setdefault(modality, []).extend(vals)
for modality, vals in new_items.items():
merged_items.setdefault(modality, []).extend(vals)
mm_data: MultiModalData | None = None
if merged_hashes or merged_placeholders or merged_items:
mm_data = MultiModalData(
mm_hashes=merged_hashes,
mm_placeholders=merged_placeholders,
mm_items=merged_items,
)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=_content_mask_or_empty(self._tokenizer, content_mask),
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=tool_names,
multi_modal_data=mm_data,
)
+7 -5
View File
@@ -16,13 +16,13 @@ from __future__ import annotations
import json
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,
@@ -47,7 +47,7 @@ class KimiK2Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: KimiK2RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -310,7 +310,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),
)
@@ -465,7 +465,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),
)
+13 -12
View File
@@ -25,8 +25,6 @@ import json
import re
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
MultiModalData,
@@ -36,6 +34,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,
@@ -592,7 +593,7 @@ class KimiK25Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: KimiK25RendererConfig | None = None,
*,
processor: Any = None,
@@ -655,8 +656,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 +665,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]):
@@ -955,7 +956,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,
@@ -1214,7 +1215,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 +1229,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,
+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
+144 -32
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,27 +36,41 @@ 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.base import (
Content,
Message,
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 = (
@@ -106,8 +120,14 @@ _TOOLS_HEADER_XS21 = (
class LagunaXS2Renderer:
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 +329,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),
)
@@ -466,7 +486,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 +503,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 +514,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 +577,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 +646,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 +695,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 +785,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 +884,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),
)
@@ -892,7 +1002,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 +1032,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.
+7 -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,
@@ -93,7 +93,7 @@ class Llama3Renderer:
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 +389,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),
)
@@ -521,7 +521,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),
)
+22 -9
View File
@@ -14,13 +14,14 @@ 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,
_get_offset_tokenizer,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -57,7 +58,7 @@ class MiniMaxM2Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: MiniMaxM2RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -165,9 +166,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 +281,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),
)
@@ -401,9 +407,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 +474,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),
)
+29 -8
View File
@@ -17,13 +17,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,
@@ -31,7 +31,11 @@ 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
# ---------------------------------------------------------------------------
@@ -76,10 +80,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.
@@ -112,7 +118,7 @@ class Nemotron3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Nemotron3RendererConfig | Nemotron3UltraRendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -478,7 +484,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),
)
@@ -662,7 +668,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 +860,16 @@ 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
+385 -7
View File
@@ -59,6 +59,26 @@ def _build_param_type_index(
return index
def _extract_tool_names(tools: list[ToolSpec] | None) -> set[str] | None:
"""Set of declared tool names, or ``None`` when ``tools`` is empty.
``None`` disables name validation — mirroring vLLM's
``ParserEngine._is_valid_tool_name``, which returns ``True`` whenever
the request carries no tools. Accepts both flat ``ToolSpec`` and the
OpenAI ``{"type": "function", "function": {...}}`` envelope, like
``_build_param_type_index`` (but independent of it: a tool with no
``parameters.properties`` still counts as a known name).
"""
if not tools:
return None
names: set[str] = set()
for tool in tools:
spec = tool.get("function", tool) if isinstance(tool, dict) else None
if isinstance(spec, dict) and isinstance(spec.get("name"), str):
names.add(spec["name"])
return names
def _coerce_arg_value(
text: str, param_schema: dict[str, Any] | None
) -> tuple[Any, bool]:
@@ -286,7 +306,15 @@ def parse_qwen35(
tool_call_end_id: int,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
"""Parse Qwen3.5 completion tokens. XML-style tool calls, token-level thinking."""
"""Parse Qwen3.5 completion tokens. XML-style tool calls, token-level thinking.
``reasoning_content`` contract: ``None`` means the completion carried no
think block at all; a string (possibly empty) means a think block was
present. The distinction matters for renderers with key-presence
semantics (PrimeQwen3Renderer): a sampled ``<think></think>`` must
round-trip parse → message → render back to the same tokens, so an
empty-but-present block is ``""``, never ``None``.
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
# Thinking: find </think> by token ID
@@ -300,12 +328,12 @@ def parse_qwen35(
ids = ids[think_end + 1 :]
parse_offset = think_end + 1
elif think_id in set(ids):
# <think> present but no </think> — truncated reasoning
# <think> present but no </think> — truncated reasoning. Block
# present ⇒ string (see docstring), even when nothing follows the
# opening tag.
think_start = _find(ids, think_id)
reasoning = _decode(tokenizer, ids[think_start + 1 :]).strip()
return ParsedResponse(
content="", reasoning_content=reasoning or None, tool_calls=[]
)
return ParsedResponse(content="", reasoning_content=reasoning, tool_calls=[])
tc_start = _find(ids, tool_call_id)
tool_calls: list[ParsedToolCall] = []
@@ -322,9 +350,14 @@ def parse_qwen35(
else:
content_text = _decode(tokenizer, ids).strip()
# ``reasoning`` is None only when no think block was found; keep ""
# (empty-but-present block) intact so ``<think></think>`` samples
# round-trip — collapsing it to None made PrimeQwen3Renderer drop the
# block on re-render, forking the token stream for the rest of the
# rollout.
return ParsedResponse(
content=content_text,
reasoning_content=reasoning or None,
reasoning_content=reasoning,
tool_calls=tool_calls,
)
@@ -421,7 +454,23 @@ def parse_glm(
arg_value_end_id: int,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
"""Parse GLM completion tokens. Token-level thinking + arg_key/arg_value tool calls."""
"""Parse GLM completion tokens. Token-level thinking + arg_key/arg_value tool calls.
When ``tools`` is passed, tool names are validated against it: a call
whose name isn't declared gets ``status=UNKNOWN_TOOL`` instead of
``OK``. This mirrors vLLM ≥ 0.24, where the ``glm45``/``glm47`` tool
parsers run with ``validate_tool_names=True`` and silently drop
unknown-name calls (``vllm/parser/glm47_moe.py``,
``ParserEngine._is_valid_tool_name``) — so a completion that yields no
tool call from the engine also yields no ``OK`` call here, and
downstream finish-reason promotion (``renderers/client.py``) agrees
with an OpenAI chat-completions client talking to the same engine.
Notably this covers the missing-``<arg_key>`` shape
(``<tool_call>bash\\n<arg_value>...</arg_value></tool_call>``): both
this parser and vLLM's resolve the whole block as the name, which then
fails validation. Without ``tools``, no validation happens (vLLM
behaves the same when the request carries no tools).
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
reasoning = None
@@ -455,6 +504,7 @@ def parse_glm(
arg_value_end_id,
section_offset=parse_offset + tc_start,
param_index=_build_param_type_index(tools),
known_names=_extract_tool_names(tools),
)
else:
content_text = _decode(tokenizer, ids).strip()
@@ -478,6 +528,7 @@ def _parse_glm_tool_calls(
*,
section_offset: int,
param_index: dict[str, dict[str, dict[str, Any]]],
known_names: set[str] | None = None,
) -> list[ParsedToolCall]:
"""Parse GLM-style tool calls: name + arg_key/arg_value pairs, all by token ID."""
tool_calls: list[ParsedToolCall] = []
@@ -535,6 +586,11 @@ def _parse_glm_tool_calls(
j += 1
if not name:
status = ToolCallParseStatus.MISSING_NAME
elif known_names is not None and name not in known_names:
# vLLM ≥ 0.24 drops the call entirely here; we keep the
# attempt visible but deny it OK so consumers agree with
# the engine on "no tool was called."
status = ToolCallParseStatus.UNKNOWN_TOOL
elif structure_broke:
status = ToolCallParseStatus.MALFORMED_STRUCTURE
elif any_json_fallback:
@@ -1093,6 +1149,196 @@ def _parse_deepseek_tool_calls(
return tool_calls
# ── DeepSeek V4: DSML tool calls + single-token </think> ────────────
def parse_deepseek_v4(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
thinking_enabled: bool,
think_end_id: int,
dsml_id: int,
) -> ParsedResponse:
"""Parse a DeepSeek V4 completion.
Thinking mode prefills ``<think>`` in the prompt, so the completion starts
with reasoning and closes it with the single-token ``</think>``. Tool
calls use DSML markup; the ``|DSML|`` marker is a special token, and the
decoded grammar carries an explicit ``string=`` flag for lossless argument
type recovery.
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
reasoning: str | None = None
content_offset = 0
if thinking_enabled:
think_end = _find(ids, think_end_id)
if think_end == -1:
return ParsedResponse(
content="",
reasoning_content=_decode(tokenizer, ids) or None,
tool_calls=[],
)
reasoning = _decode(tokenizer, ids[:think_end])
content_offset = think_end + 1
content_ids = ids[content_offset:]
decoded = _decode(tokenizer, content_ids)
section_marker = "\n\n<|DSML|tool_calls>"
section_pos = decoded.find(section_marker)
if section_pos == -1 or dsml_id not in content_ids:
return ParsedResponse(
content=decoded,
reasoning_content=reasoning or None,
tool_calls=[],
)
content = decoded[:section_pos]
section_text = decoded[section_pos:]
section_token_offset = content_offset + _decoded_char_to_token_index(
tokenizer,
content_ids,
section_pos,
)
tool_calls = _parse_deepseek_v4_tool_calls(
tokenizer,
section_text,
ids[section_token_offset:],
section_offset=section_token_offset,
)
return ParsedResponse(
content=content,
reasoning_content=reasoning or None,
tool_calls=tool_calls,
)
def _decoded_char_to_token_index(tokenizer, ids: list[int], char_index: int) -> int:
"""Return the first token boundary at or beyond a decoded char offset."""
if char_index <= 0:
return 0
for boundary in range(1, len(ids) + 1):
if len(_decode(tokenizer, ids[:boundary])) >= char_index:
return boundary
return len(ids)
def _parse_deepseek_v4_tool_calls(
tokenizer,
section_text: str,
section_ids: list[int],
*,
section_offset: int,
) -> list[ParsedToolCall]:
"""Parse every DSML ``invoke`` attempt from one tool-calls section."""
import re
invoke_start = '<|DSML|invoke name="'
invoke_end = "</|DSML|invoke>"
section_end = "</|DSML|tool_calls>"
parameter_pattern = re.compile(
r'<|DSML|parameter name="(.*?)" string="(true|false)">'
r"(.*?)</|DSML|parameter>",
re.DOTALL,
)
tool_calls: list[ParsedToolCall] = []
outer_end = section_text.find(section_end)
for invoke_match in re.finditer(r"<|DSML|invoke", section_text):
start = invoke_match.start()
if outer_end != -1 and outer_end < start:
break
close = section_text.find(invoke_end, start + len(invoke_start))
unclosed = close == -1 or (outer_end != -1 and outer_end < close)
block_end = outer_end if unclosed and outer_end != -1 else len(section_text)
if not unclosed:
block_end = close + len(invoke_end)
raw = section_text[start:block_end]
token_start = _decoded_char_to_token_index(tokenizer, section_ids, start)
token_end = _decoded_char_to_token_index(tokenizer, section_ids, block_end)
span = (section_offset + token_start, section_offset + token_end)
header_end = section_text.find(">\n", start, block_end)
name: str | None = None
malformed = False
if header_end == -1:
malformed = True
body = ""
else:
header = section_text[start : header_end + 2]
name_match = re.fullmatch(
r'<|DSML|invoke name="(.*?)">\n',
header,
flags=re.DOTALL,
)
if name_match:
name = name_match.group(1)
else:
malformed = True
body_end = close if not unclosed else block_end
body = section_text[header_end + 2 : body_end]
arguments: dict[str, Any] = {}
invalid_json = False
matched_ranges: list[tuple[int, int]] = []
for match in parameter_pattern.finditer(body):
key, is_string, raw_value = match.groups()
matched_ranges.append(match.span())
if key in arguments:
malformed = True
continue
if is_string == "true":
arguments[key] = raw_value
else:
try:
arguments[key] = json.loads(raw_value)
except (json.JSONDecodeError, ValueError):
arguments[key] = raw_value
invalid_json = True
remainder_parts: list[str] = []
previous_end = 0
for match_start, match_end in matched_ranges:
remainder_parts.append(body[previous_end:match_start])
previous_end = match_end
remainder_parts.append(body[previous_end:])
remainder = "".join(remainder_parts)
# The canonical form has one newline before ``</invoke>`` and newlines
# between parameters. Anything else left after removing parameter
# blocks is structural debris.
if remainder.strip("\n"):
malformed = True
if unclosed:
status = ToolCallParseStatus.UNCLOSED_BLOCK
elif not name:
status = ToolCallParseStatus.MISSING_NAME
elif malformed:
status = ToolCallParseStatus.MALFORMED_STRUCTURE
elif invalid_json:
status = ToolCallParseStatus.INVALID_JSON
else:
status = ToolCallParseStatus.OK
tool_calls.append(
ParsedToolCall(
raw=raw,
name=name,
arguments=arguments,
token_span=span,
status=status,
)
)
if unclosed:
break
return tool_calls
# ── MiniMax: <minimax:tool_call> ... </minimax:tool_call> ────────────
@@ -1611,3 +1857,135 @@ def parse_llama_3(
# "malformed attempt" against, so it falls through to content rather
# than producing a non-OK ParsedToolCall.
return ParsedResponse(content=text, reasoning_content=None)
def parse_inkling(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
message_model_id: int,
content_text_id: int,
content_thinking_id: int,
invoke_json_id: int,
invoke_text_id: int,
end_message_id: int,
) -> ParsedResponse:
"""Parse Inkling completion tokens.
Inkling's assistant turn is a sequence of ``<|end_message|>``-terminated
segments; the model re-emits ``<|message_model|>`` before each segment
after the first (the first's opener is the generation prompt). Each
segment is classified by its leading content marker:
- ``<|content_thinking|>{reasoning}`` → reasoning
- ``<|content_text|>{content}`` → visible content
- ``{name}<|content_invoke_tool_json|>{"name":…,"args":…}`` → tool call
Content and reasoning are decoded verbatim (the template renders them
without whitespace normalisation). Tool-call arguments arrive as native
JSON (the template ``tojson``-encodes them), so types are preserved
without the schema-driven coercion the XML formats need — ``tools`` is
accepted for signature uniformity but unused.
``token_span`` on each ``ParsedToolCall`` is the half-open slice of the
stop-stripped stream covering that tool-call segment (from its leading
``<|message_model|>`` through the terminating ``<|end_message|>``).
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
reasoning_parts: list[str] = []
content_parts: list[str] = []
tool_calls: list[ParsedToolCall] = []
pos = 0
n = len(ids)
while pos < n:
em = _find(ids, end_message_id, pos)
terminated = em != -1
seg_end = em if terminated else n
seg = ids[pos:seg_end]
# A non-first segment re-opens with <|message_model|>; drop it so the
# content marker is at the head. (The first segment's opener lives in
# the prompt, so it is usually already absent.)
s = 1 if seg and seg[0] == message_model_id else 0
body = seg[s:]
if not body:
pass
elif body[0] == content_thinking_id:
reasoning_parts.append(_decode(tokenizer, body[1:]))
elif body[0] == content_text_id:
content_parts.append(_decode(tokenizer, body[1:]))
else:
marker = _find_any(body, {invoke_json_id, invoke_text_id})
if marker != -1:
name = _decode(tokenizer, body[:marker]).strip()
payload = _decode(tokenizer, body[marker + 1 :])
tool_calls.append(
_build_inkling_tool_call(
name=name,
payload=payload,
token_span=(pos, seg_end + 1 if terminated else n),
terminated=terminated,
)
)
else:
# No content marker and no invoke marker — treat the decoded
# bytes as content rather than dropping them.
content_parts.append(_decode(tokenizer, body))
if not terminated:
break
pos = em + 1
return ParsedResponse(
content="".join(content_parts),
reasoning_content="".join(reasoning_parts) or None,
tool_calls=tool_calls,
)
def _build_inkling_tool_call(
*, name: str, payload: str, token_span: tuple[int, int], terminated: bool
) -> ParsedToolCall:
"""Build a ``ParsedToolCall`` from an Inkling ``<|content_invoke_tool_json|>``
payload — ``{"name": …, "args": …}`` (native JSON, types preserved).
The function name inside the JSON is authoritative; the pre-marker text
(rendered as ``<|message_model|>{name}<|content_invoke_tool_json|>``) is a
fallback for a truncated / malformed payload.
"""
parsed: Any = None
invalid_json = False
try:
parsed = json.loads(payload)
except (json.JSONDecodeError, ValueError):
invalid_json = True
fn_name: str | None = None
arguments: dict[str, Any] | str | None = None
if isinstance(parsed, dict):
raw_name = parsed.get("name")
fn_name = raw_name if isinstance(raw_name, str) and raw_name else (name or None)
arguments = parsed.get("args", {})
else:
fn_name = name or None
arguments = payload
if not terminated:
status = ToolCallParseStatus.UNCLOSED_BLOCK
elif invalid_json:
status = ToolCallParseStatus.INVALID_JSON
elif fn_name is None:
status = ToolCallParseStatus.MISSING_NAME
else:
status = ToolCallParseStatus.OK
return ParsedToolCall(
raw=payload,
name=fn_name,
arguments=arguments,
token_span=token_span,
status=status,
)
+17 -8
View File
@@ -6,13 +6,14 @@ import json
from collections.abc import Mapping, Sequence
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
_get_offset_tokenizer,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -120,7 +121,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] = []
@@ -192,7 +193,7 @@ class PrimeQwen3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: PrimeQwen3RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -316,8 +317,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),
)
@@ -684,8 +689,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),
)
+27 -6
View File
@@ -5,19 +5,28 @@ 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.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
Tokenizer,
_content_mask_or_empty,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
@@ -50,7 +59,7 @@ class Qwen3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Qwen3RendererConfig | None = None,
):
self._tokenizer = tokenizer
@@ -260,7 +269,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),
)
@@ -425,7 +434,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 +488,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")
+100 -39
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|>``
@@ -17,8 +25,6 @@ from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
MultiModalData,
@@ -26,6 +32,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 +103,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,
}
@@ -115,7 +127,7 @@ class Qwen35Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Qwen35RendererConfig | None = None,
*,
processor: Any = None,
@@ -174,8 +186,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 +194,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]):
@@ -297,6 +308,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
# ------------------------------------------------------------------
@@ -458,6 +504,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 +516,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 +534,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 +638,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,
@@ -865,7 +932,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 +946,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 +991,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 +1011,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)
+66
View File
@@ -0,0 +1,66 @@
"""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 renderers.base import Message
from renderers.configs import Qwen38RendererConfig
from renderers.qwen35 import Qwen35Renderer
from renderers.qwen36 import Qwen36Renderer
_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 _last_query_index(messages: list[Message]) -> int:
last_query_index = Qwen35Renderer._last_query_index(messages)
if last_query_index == len(messages):
raise ValueError("No user query found in messages.")
return last_query_index
@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"]
+10 -10
View File
@@ -33,8 +33,6 @@ import json
from typing import Any
from urllib.parse import urlparse
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
MultiModalData,
@@ -42,6 +40,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 +278,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."
@@ -311,7 +312,7 @@ class Qwen3VLRenderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
tokenizer: Tokenizer,
config: Qwen3VLRendererConfig | None = None,
*,
processor: Any = None,
@@ -375,8 +376,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 +384,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
@@ -620,7 +620,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,
@@ -865,7 +865,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,
+17 -111
View File
@@ -4,60 +4,16 @@ Each (model_name, renderer_name) pair gets a tokenizer + renderer.
The same barrage of tests runs against every pair.
"""
import os
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] = {}
@@ -73,10 +29,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 +57,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"
)
+782
View File
@@ -0,0 +1,782 @@
"""Shared catalog and scenario corpus for renderer reference-parity tests."""
from __future__ import annotations
from dataclasses import dataclass, 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-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: "
f"{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
+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",
]
+2 -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)
+17 -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"},
+181 -21
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,
@@ -67,33 +68,30 @@ class _FakeClient:
def __init__(self):
self.calls = []
self.base_url = "http://fake-host:8000/v1"
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],
}
return httpx.Response(
200,
@@ -101,6 +99,18 @@ class _FakeClient:
)
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"}}],
)
)
def test_generate_builds_request_body_and_parses_response():
client = _FakeClient()
renderer = _FakeRenderer()
@@ -172,6 +182,95 @@ def test_generate_builds_request_body_and_parses_response():
assert tc.status == ToolCallParseStatus.OK
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"."""
@@ -285,8 +384,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 +472,65 @@ 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"]
)
# ---------------------------------------------------------------------------
# Prompt overflow handling.
# ---------------------------------------------------------------------------
+3 -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()
+565
View File
@@ -0,0 +1,565 @@
"""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")
def test_dsml_roundtrip_preserves_string_and_json_argument_types():
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) + 2 # skip Assistant + <think>
parsed = renderer.parse_response(rendered[completion_start:])
assert parsed.reasoning_content == "Use weather."
assert parsed.content == "checking"
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
@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"])
def test_dsml_parser_requires_reference_encoders_two_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 == text
assert parsed.tool_calls == []
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,
)
+227
View File
@@ -0,0 +1,227 @@
"""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
+469
View File
@@ -0,0 +1,469 @@
"""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)
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]
+181
View File
@@ -0,0 +1,181 @@
"""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)
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]
-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
+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).
+523
View File
@@ -0,0 +1,523 @@
"""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
+154
View File
@@ -0,0 +1,154 @@
"""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)
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,
)
+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
# ---------------------------------------------------------------------------
+1 -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
+221 -11
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
@@ -120,7 +121,9 @@ def _load_processor_and_renderer(model_name: str):
revision = _PROCESSOR_TRUSTED_REVISIONS.get(model_name)
if revision is not None:
processor = AutoProcessor.from_pretrained(
model_name, trust_remote_code=True, revision=revision
model_name,
trust_remote_code=True,
revision=revision,
)
else:
processor = AutoProcessor.from_pretrained(model_name)
@@ -167,11 +170,22 @@ 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("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 +218,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 +271,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 +317,37 @@ 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,
}
# 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 +552,51 @@ 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.qwen35 import Qwen35Renderer
return isinstance(renderer, (Qwen35Renderer, KimiK25Renderer))
return isinstance(renderer, (Qwen35Renderer, KimiK25Renderer, Gemma4Renderer))
@pytest.mark.parametrize(
@@ -463,9 +614,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 +648,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)
@@ -562,12 +717,13 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
)
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 +732,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 +745,11 @@ 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]
completion_ids = tokenizer.encode("Saw it.", add_special_tokens=False) + [close_id]
bridged_raw = renderer.bridge_to_next_turn(
previous_prompt_ids=initial_rendered.token_ids,
@@ -665,6 +821,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 +915,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 +1004,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
-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)
+222
View File
@@ -0,0 +1,222 @@
"""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),
)
@lru_cache(maxsize=None)
def _tokenizer(model: str):
return load_tokenizer(model)
@lru_cache(maxsize=None)
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)})"
)
+64
View File
@@ -6,6 +6,8 @@ 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
@@ -105,6 +107,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)
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)
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.
-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})"
)
+178
View File
@@ -0,0 +1,178 @@
"""Focused Qwen3.8 registration and upstream-template parity coverage."""
from __future__ import annotations
from functools import lru_cache
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."}])
-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)
+49 -28
View File
@@ -3,12 +3,14 @@ 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,
GptOssRendererConfig,
@@ -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``
@@ -131,31 +140,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 +147,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 +155,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(
-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)})"
)
+12 -41
View File
@@ -5,13 +5,13 @@ Core renderer invariant: if you render
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).
bugs that slip past render-parity tests (which compare against each model's
reference encoder) 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).
(which is kept conservative because several newer renderers still disagree
with their upstream references 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.
@@ -24,38 +24,9 @@ from functools import lru_cache
from typing import Any
import pytest
from parity import models_for
# (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"),
]
_ROUNDTRIP_MODELS = [(case.model, case.renderer) for case in models_for("roundtrip")]
@lru_cache(maxsize=None)
@@ -167,10 +138,10 @@ def test_roundtrip_reasoning_and_content(rt_model, rt_tokenizer, rt_renderer):
# ── tool calls ────────────────────────────────────────────────────────
def _maybe_skip_tool_calls(renderer_name: str) -> None:
def _maybe_skip_tool_calls(renderer) -> 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":
if renderer.config.name == "default":
pytest.skip(
"DefaultRenderer requires an explicit tool_parser to parse tool "
"calls; not exercised in the round-trip matrix."
@@ -180,7 +151,7 @@ def _maybe_skip_tool_calls(renderer_name: str) -> None:
def test_roundtrip_single_tool_call(
rt_model, rt_renderer_name, rt_tokenizer, rt_renderer
):
_maybe_skip_tool_calls(rt_renderer_name)
_maybe_skip_tool_calls(rt_renderer)
msg = {
"role": "assistant",
@@ -215,8 +186,8 @@ def test_roundtrip_multiple_tool_calls(
):
"""Parsers that loop over ``<tool_call>…</tool_call>`` blocks can
silently drop the second one; this test catches that."""
_maybe_skip_tool_calls(rt_renderer_name)
if rt_renderer_name == "llama-3":
_maybe_skip_tool_calls(rt_renderer)
if rt_renderer.config.name == "llama-3":
pytest.skip(
"Llama-3's chat template forbids >1 tool call per assistant "
"message (the renderer raises, mirroring the template); the "
+2 -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)
Generated
+170 -181
View File
@@ -9,7 +9,7 @@ resolution-markers = [
]
[options]
exclude-newer = "2026-06-19T02:36:32.208558271Z"
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P7D"
[options.exclude-newer-package]
@@ -173,7 +173,7 @@ name = "cuda-bindings"
version = "13.2.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cuda-pathfinder", marker = "(python_full_version < '3.11' and sys_platform == 'emscripten') or (python_full_version < '3.11' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" },
{ name = "cuda-pathfinder" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/1a/fe/7351d7e586a8b4c9f89731bfe4cf0148223e8f9903ff09571f78b3fb0682/cuda_bindings-13.2.0-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:08b395f79cb89ce0cd8effff07c4a1e20101b873c256a1aeb286e8fd7bd0f556", size = 5744254, upload-time = "2026-03-11T00:12:29.798Z" },
@@ -196,45 +196,51 @@ wheels = [
[[package]]
name = "cuda-toolkit"
version = "13.0.2"
version = "13.0.3.0"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/57/b2/453099f5f3b698d7d0eab38916aac44c7f76229f451709e2eb9db6615dcd/cuda_toolkit-13.0.2-py2.py3-none-any.whl", hash = "sha256:b198824cf2f54003f50d64ada3a0f184b42ca0846c1c94192fa269ecd97a66eb", size = 2364, upload-time = "2025-12-19T23:24:07.328Z" },
{ url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" },
]
[package.optional-dependencies]
cublas = [
{ name = "nvidia-cublas", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
{ name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
cudart = [
{ name = "nvidia-cuda-runtime", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-cuda-runtime", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
cufft = [
{ name = "nvidia-cufft", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-cufft", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
{ name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
cufile = [
{ name = "nvidia-cufile", marker = "sys_platform == 'linux'" },
{ name = "nvidia-cufile", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
cupti = [
{ name = "nvidia-cuda-cupti", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-cuda-cupti", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
curand = [
{ name = "nvidia-curand", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-curand", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
cusolver = [
{ name = "nvidia-cusolver", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
{ name = "nvidia-cusolver", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
{ name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
{ name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
cusparse = [
{ name = "nvidia-cusparse", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
{ name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
nvjitlink = [
{ name = "nvidia-nvjitlink", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
nvrtc = [
{ name = "nvidia-cuda-nvrtc", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
nvtx = [
{ name = "nvidia-nvtx", marker = "(python_full_version < '3.11' and sys_platform == 'win32') or sys_platform == 'linux'" },
{ name = "nvidia-nvtx", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
]
[[package]]
@@ -260,7 +266,7 @@ name = "exceptiongroup"
version = "1.3.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
wheels = [
@@ -739,11 +745,14 @@ wheels = [
[[package]]
name = "nvidia-cublas"
version = "13.1.0.3"
version = "13.1.1.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "nvidia-cuda-nvrtc" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/e1/a5/fce49e2ae977e0ccc084e5adafceb4f0ac0c8333cb6863501618a7277f67/nvidia_cublas-13.1.0.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:c86fc7f7ae36d7528288c5d88098edcb7b02c633d262e7ddbb86b0ad91be5df2", size = 542851226, upload-time = "2025-10-09T08:59:04.818Z" },
{ url = "https://files.pythonhosted.org/packages/e7/44/423ac00af4dd95a5aeb27207e2c0d9b7118702149bf4704c3ddb55bb7429/nvidia_cublas-13.1.0.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:ee8722c1f0145ab246bccb9e452153b5e0515fd094c3678df50b2a0888b8b171", size = 423133236, upload-time = "2025-10-09T08:59:32.536Z" },
{ url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" },
{ url = "https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:37936a16db8fe4ac1f065c2139360608a543a09275cb1a1af612e08cfa065436", size = 423138758, upload-time = "2026-04-08T18:46:58.655Z" },
]
[[package]]
@@ -775,14 +784,14 @@ wheels = [
[[package]]
name = "nvidia-cudnn-cu13"
version = "9.19.0.56"
version = "9.20.0.48"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "nvidia-cublas", marker = "(python_full_version < '3.11' and sys_platform == 'emscripten') or (python_full_version < '3.11' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" },
{ name = "nvidia-cublas" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/f1/84/26025437c1e6b61a707442184fa0c03d083b661adf3a3eecfd6d21677740/nvidia_cudnn_cu13-9.19.0.56-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:6ed29ffaee1176c612daf442e4dd6cfeb6a0caa43ddcbeb59da94953030b1be4", size = 433781201, upload-time = "2026-02-03T20:40:53.805Z" },
{ url = "https://files.pythonhosted.org/packages/a3/22/0b4b932655d17a6da1b92fa92ab12844b053bb2ac2475e179ba6f043da1e/nvidia_cudnn_cu13-9.19.0.56-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:d20e1734305e9d68889a96e3f35094d733ff1f83932ebe462753973e53a572bf", size = 366066321, upload-time = "2026-02-03T20:44:52.837Z" },
{ url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" },
{ url = "https://files.pythonhosted.org/packages/6e/5e/edb9c0ae051602c3ccaffe424256463636d639e27d7f302dde9975ef9e7a/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0c45dd8eeb50b603f07995b1b300c62ffe6a1980482b82b3bcf94a4ca9d49304", size = 366173588, upload-time = "2026-03-09T19:29:34.474Z" },
]
[[package]]
@@ -790,7 +799,7 @@ name = "nvidia-cufft"
version = "12.0.0.61"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "nvidia-nvjitlink", marker = "(python_full_version < '3.11' and sys_platform == 'emscripten') or (python_full_version < '3.11' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" },
{ name = "nvidia-nvjitlink" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" },
@@ -820,9 +829,9 @@ name = "nvidia-cusolver"
version = "12.0.4.66"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "nvidia-cublas", marker = "(python_full_version < '3.11' and sys_platform == 'emscripten') or (python_full_version < '3.11' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" },
{ name = "nvidia-cusparse", marker = "(python_full_version < '3.11' and sys_platform == 'emscripten') or (python_full_version < '3.11' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" },
{ name = "nvidia-nvjitlink", marker = "(python_full_version < '3.11' and sys_platform == 'emscripten') or (python_full_version < '3.11' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" },
{ name = "nvidia-cublas" },
{ name = "nvidia-cusparse" },
{ name = "nvidia-nvjitlink" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" },
@@ -834,7 +843,7 @@ name = "nvidia-cusparse"
version = "12.6.3.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "nvidia-nvjitlink", marker = "(python_full_version < '3.11' and sys_platform == 'emscripten') or (python_full_version < '3.11' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" },
{ name = "nvidia-nvjitlink" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" },
@@ -843,20 +852,20 @@ wheels = [
[[package]]
name = "nvidia-cusparselt-cu13"
version = "0.8.0"
version = "0.8.1"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/46/10/8dcd1175260706a2fc92a16a52e306b71d4c1ea0b0cc4a9484183399818a/nvidia_cusparselt_cu13-0.8.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:400c6ed1cf6780fc6efedd64ec9f1345871767e6a1a0a552a1ea0578117ea77c", size = 220791277, upload-time = "2025-08-13T19:22:40.982Z" },
{ url = "https://files.pythonhosted.org/packages/fd/53/43b0d71f4e702fa9733f8b4571fdca50a8813f1e450b656c239beff12315/nvidia_cusparselt_cu13-0.8.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:25e30a8a7323935d4ad0340b95a0b69926eee755767e8e0b1cf8dd85b197d3fd", size = 169884119, upload-time = "2025-08-13T19:23:41.967Z" },
{ url = "https://files.pythonhosted.org/packages/46/e1/cdc1797eadf82d3a9a575a19b33fdc871a97edbec42c00b5b5e914f4aff4/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4dca476c50bf4780d46cd0bfbd82e2bc10a08e4fef7950917ce8d7578d22a23f", size = 221051344, upload-time = "2025-09-05T18:49:51.289Z" },
{ url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" },
]
[[package]]
name = "nvidia-nccl-cu13"
version = "2.28.9"
version = "2.29.7"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/39/55/1920646a2e43ffd4fc958536b276197ed740e9e0c54105b4bb3521591fc7/nvidia_nccl_cu13-2.28.9-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:01c873ba1626b54caa12272ed228dc5b2781545e0ae8ba3f432a8ef1c6d78643", size = 196561677, upload-time = "2025-11-18T05:49:03.45Z" },
{ url = "https://files.pythonhosted.org/packages/b0/b4/878fefaad5b2bcc6fcf8d474a25e3e3774bc5133e4b58adff4d0bca238bc/nvidia_nccl_cu13-2.28.9-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:e4553a30f34195f3fa1da02a6da3d6337d28f2003943aa0a3d247bbc25fefc42", size = 196493177, upload-time = "2025-11-18T05:49:17.677Z" },
{ url = "https://files.pythonhosted.org/packages/72/0d/daf50d44177ee0cbc7ff0a0c91eb5ff676c82be42f9a970bc7597f440c3a/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:674a12383e3c38a1bcccae7d4f3633b37852230b6047883cb2f4c2d1b36d9bf5", size = 206014712, upload-time = "2026-03-03T05:34:20.843Z" },
{ url = "https://files.pythonhosted.org/packages/67/f4/58e4e91b6919367c7aafb8e36fce9aad1a3047e536bf7e2fd560927d3a4c/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:edd81538446786ec3b73972543e53bb43bcaf0bfc8ef76cb679fcc390ffe136d", size = 205976000, upload-time = "2026-03-03T05:36:24.472Z" },
]
[[package]]
@@ -939,75 +948,54 @@ wheels = [
[[package]]
name = "pillow"
version = "12.2.0"
version = "12.3.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/8c/21/c2bcdd5906101a30244eaffc1b6e6ce71a31bd0742a01eb89e660ebfac2d/pillow-12.2.0.tar.gz", hash = "sha256:a830b1a40919539d07806aa58e1b114df53ddd43213d9c8b75847eee6c0182b5", size = 46987819, upload-time = "2026-04-01T14:46:17.687Z" }
sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/3a/aa/d0b28e1c811cd4d5f5c2bfe2e022292bd255ae5744a3b9ac7d6c8f72dd75/pillow-12.2.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:a4e8f36e677d3336f35089648c8955c51c6d386a13cf6ee9c189c5f5bd713a9f", size = 5354355, upload-time = "2026-04-01T14:42:15.402Z" },
{ url = "https://files.pythonhosted.org/packages/27/8e/1d5b39b8ae2bd7650d0c7b6abb9602d16043ead9ebbfef4bc4047454da2a/pillow-12.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2e589959f10d9824d39b350472b92f0ce3b443c0a3442ebf41c40cb8361c5b97", size = 4695871, upload-time = "2026-04-01T14:42:18.234Z" },
{ url = "https://files.pythonhosted.org/packages/f0/c5/dcb7a6ca6b7d3be41a76958e90018d56c8462166b3ef223150360850c8da/pillow-12.2.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a52edc8bfff4429aaabdf4d9ee0daadbbf8562364f940937b941f87a4290f5ff", size = 6269734, upload-time = "2026-04-01T14:42:20.608Z" },
{ url = "https://files.pythonhosted.org/packages/ea/f1/aa1bb13b2f4eba914e9637893c73f2af8e48d7d4023b9d3750d4c5eb2d0c/pillow-12.2.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:975385f4776fafde056abb318f612ef6285b10a1f12b8570f3647ad0d74b48ec", size = 8076080, upload-time = "2026-04-01T14:42:23.095Z" },
{ url = "https://files.pythonhosted.org/packages/a1/2a/8c79d6a53169937784604a8ae8d77e45888c41537f7f6f65ed1f407fe66d/pillow-12.2.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bd9c0c7a0c681a347b3194c500cb1e6ca9cab053ea4d82a5cf45b6b754560136", size = 6382236, upload-time = "2026-04-01T14:42:25.82Z" },
{ url = "https://files.pythonhosted.org/packages/b5/42/bbcb6051030e1e421d103ce7a8ecadf837aa2f39b8f82ef1a8d37c3d4ebc/pillow-12.2.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:88d387ff40b3ff7c274947ed3125dedf5262ec6919d83946753b5f3d7c67ea4c", size = 7070220, upload-time = "2026-04-01T14:42:28.68Z" },
{ url = "https://files.pythonhosted.org/packages/3f/e1/c2a7d6dd8cfa6b231227da096fd2d58754bab3603b9d73bf609d3c18b64f/pillow-12.2.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:51c4167c34b0d8ba05b547a3bb23578d0ba17b80a5593f93bd8ecb123dd336a3", size = 6493124, upload-time = "2026-04-01T14:42:31.579Z" },
{ url = "https://files.pythonhosted.org/packages/5f/41/7c8617da5d32e1d2f026e509484fdb6f3ad7efaef1749a0c1928adbb099e/pillow-12.2.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:34c0d99ecccea270c04882cb3b86e7b57296079c9a4aff88cb3b33563d95afaa", size = 7194324, upload-time = "2026-04-01T14:42:34.615Z" },
{ url = "https://files.pythonhosted.org/packages/2d/de/a777627e19fd6d62f84070ee1521adde5eeda4855b5cf60fe0b149118bca/pillow-12.2.0-cp310-cp310-win32.whl", hash = "sha256:b85f66ae9eb53e860a873b858b789217ba505e5e405a24b85c0464822fe88032", size = 6376363, upload-time = "2026-04-01T14:42:37.19Z" },
{ url = "https://files.pythonhosted.org/packages/e7/34/fc4cb5204896465842767b96d250c08410f01f2f28afc43b257de842eed5/pillow-12.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:673aa32138f3e7531ccdbca7b3901dba9b70940a19ccecc6a37c77d5fdeb05b5", size = 7083523, upload-time = "2026-04-01T14:42:39.62Z" },
{ url = "https://files.pythonhosted.org/packages/2d/a0/32852d36bc7709f14dc3f64f929a275e958ad8c19a6deba9610d458e28b3/pillow-12.2.0-cp310-cp310-win_arm64.whl", hash = "sha256:3e080565d8d7c671db5802eedfb438e5565ffa40115216eabb8cd52d0ecce024", size = 2463318, upload-time = "2026-04-01T14:42:42.063Z" },
{ url = "https://files.pythonhosted.org/packages/68/e1/748f5663efe6edcfc4e74b2b93edfb9b8b99b67f21a854c3ae416500a2d9/pillow-12.2.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:8be29e59487a79f173507c30ddf57e733a357f67881430449bb32614075a40ab", size = 5354347, upload-time = "2026-04-01T14:42:44.255Z" },
{ url = "https://files.pythonhosted.org/packages/47/a1/d5ff69e747374c33a3b53b9f98cca7889fce1fd03d79cdc4e1bccc6c5a87/pillow-12.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:71cde9a1e1551df7d34a25462fc60325e8a11a82cc2e2f54578e5e9a1e153d65", size = 4695873, upload-time = "2026-04-01T14:42:46.452Z" },
{ url = "https://files.pythonhosted.org/packages/df/21/e3fbdf54408a973c7f7f89a23b2cb97a7ef30c61ab4142af31eee6aebc88/pillow-12.2.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f490f9368b6fc026f021db16d7ec2fbf7d89e2edb42e8ec09d2c60505f5729c7", size = 6280168, upload-time = "2026-04-01T14:42:49.228Z" },
{ url = "https://files.pythonhosted.org/packages/d3/f1/00b7278c7dd52b17ad4329153748f87b6756ec195ff786c2bdf12518337d/pillow-12.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8bd7903a5f2a4545f6fd5935c90058b89d30045568985a71c79f5fd6edf9b91e", size = 8088188, upload-time = "2026-04-01T14:42:51.735Z" },
{ url = "https://files.pythonhosted.org/packages/ad/cf/220a5994ef1b10e70e85748b75649d77d506499352be135a4989c957b701/pillow-12.2.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3997232e10d2920a68d25191392e3a4487d8183039e1c74c2297f00ed1c50705", size = 6394401, upload-time = "2026-04-01T14:42:54.343Z" },
{ url = "https://files.pythonhosted.org/packages/e9/bd/e51a61b1054f09437acfbc2ff9106c30d1eb76bc1453d428399946781253/pillow-12.2.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e74473c875d78b8e9d5da2a70f7099549f9eb37ded4e2f6a463e60125bccd176", size = 7079655, upload-time = "2026-04-01T14:42:56.954Z" },
{ url = "https://files.pythonhosted.org/packages/6b/3d/45132c57d5fb4b5744567c3817026480ac7fc3ce5d4c47902bc0e7f6f853/pillow-12.2.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:56a3f9c60a13133a98ecff6197af34d7824de9b7b38c3654861a725c970c197b", size = 6503105, upload-time = "2026-04-01T14:42:59.847Z" },
{ url = "https://files.pythonhosted.org/packages/7d/2e/9df2fc1e82097b1df3dce58dc43286aa01068e918c07574711fcc53e6fb4/pillow-12.2.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:90e6f81de50ad6b534cab6e5aef77ff6e37722b2f5d908686f4a5c9eba17a909", size = 7203402, upload-time = "2026-04-01T14:43:02.664Z" },
{ url = "https://files.pythonhosted.org/packages/bd/2e/2941e42858ebb67e50ae741473de81c2984e6eff7b397017623c676e2e8d/pillow-12.2.0-cp311-cp311-win32.whl", hash = "sha256:8c984051042858021a54926eb597d6ee3012393ce9c181814115df4c60b9a808", size = 6378149, upload-time = "2026-04-01T14:43:05.274Z" },
{ url = "https://files.pythonhosted.org/packages/69/42/836b6f3cd7f3e5fa10a1f1a5420447c17966044c8fbf589cc0452d5502db/pillow-12.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:6e6b2a0c538fc200b38ff9eb6628228b77908c319a005815f2dde585a0664b60", size = 7082626, upload-time = "2026-04-01T14:43:08.557Z" },
{ url = "https://files.pythonhosted.org/packages/c2/88/549194b5d6f1f494b485e493edc6693c0a16f4ada488e5bd974ed1f42fad/pillow-12.2.0-cp311-cp311-win_arm64.whl", hash = "sha256:9a8a34cc89c67a65ea7437ce257cea81a9dad65b29805f3ecee8c8fe8ff25ffe", size = 2463531, upload-time = "2026-04-01T14:43:10.743Z" },
{ url = "https://files.pythonhosted.org/packages/58/be/7482c8a5ebebbc6470b3eb791812fff7d5e0216c2be3827b30b8bb6603ed/pillow-12.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d192a155bbcec180f8564f693e6fd9bccff5a7af9b32e2e4bf8c9c69dbad6b5", size = 5308279, upload-time = "2026-04-01T14:43:13.246Z" },
{ url = "https://files.pythonhosted.org/packages/d8/95/0a351b9289c2b5cbde0bacd4a83ebc44023e835490a727b2a3bd60ddc0f4/pillow-12.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3f40b3c5a968281fd507d519e444c35f0ff171237f4fdde090dd60699458421", size = 4695490, upload-time = "2026-04-01T14:43:15.584Z" },
{ url = "https://files.pythonhosted.org/packages/de/af/4e8e6869cbed569d43c416fad3dc4ecb944cb5d9492defaed89ddd6fe871/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:03e7e372d5240cc23e9f07deca4d775c0817bffc641b01e9c3af208dbd300987", size = 6284462, upload-time = "2026-04-01T14:43:18.268Z" },
{ url = "https://files.pythonhosted.org/packages/e9/9e/c05e19657fd57841e476be1ab46c4d501bffbadbafdc31a6d665f8b737b6/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b86024e52a1b269467a802258c25521e6d742349d760728092e1bc2d135b4d76", size = 8094744, upload-time = "2026-04-01T14:43:20.716Z" },
{ url = "https://files.pythonhosted.org/packages/2b/54/1789c455ed10176066b6e7e6da1b01e50e36f94ba584dc68d9eebfe9156d/pillow-12.2.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7371b48c4fa448d20d2714c9a1f775a81155050d383333e0a6c15b1123dda005", size = 6398371, upload-time = "2026-04-01T14:43:23.443Z" },
{ url = "https://files.pythonhosted.org/packages/43/e3/fdc657359e919462369869f1c9f0e973f353f9a9ee295a39b1fea8ee1a77/pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:62f5409336adb0663b7caa0da5c7d9e7bdbaae9ce761d34669420c2a801b2780", size = 7087215, upload-time = "2026-04-01T14:43:26.758Z" },
{ url = "https://files.pythonhosted.org/packages/8b/f8/2f6825e441d5b1959d2ca5adec984210f1ec086435b0ed5f52c19b3b8a6e/pillow-12.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:01afa7cf67f74f09523699b4e88c73fb55c13346d212a59a2db1f86b0a63e8c5", size = 6509783, upload-time = "2026-04-01T14:43:29.56Z" },
{ url = "https://files.pythonhosted.org/packages/67/f9/029a27095ad20f854f9dba026b3ea6428548316e057e6fc3545409e86651/pillow-12.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc3d34d4a8fbec3e88a79b92e5465e0f9b842b628675850d860b8bd300b159f5", size = 7212112, upload-time = "2026-04-01T14:43:32.091Z" },
{ url = "https://files.pythonhosted.org/packages/be/42/025cfe05d1be22dbfdb4f264fe9de1ccda83f66e4fc3aac94748e784af04/pillow-12.2.0-cp312-cp312-win32.whl", hash = "sha256:58f62cc0f00fd29e64b29f4fd923ffdb3859c9f9e6105bfc37ba1d08994e8940", size = 6378489, upload-time = "2026-04-01T14:43:34.601Z" },
{ url = "https://files.pythonhosted.org/packages/5d/7b/25a221d2c761c6a8ae21bfa3874988ff2583e19cf8a27bf2fee358df7942/pillow-12.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:7f84204dee22a783350679a0333981df803dac21a0190d706a50475e361c93f5", size = 7084129, upload-time = "2026-04-01T14:43:37.213Z" },
{ url = "https://files.pythonhosted.org/packages/10/e1/542a474affab20fd4a0f1836cb234e8493519da6b76899e30bcc5d990b8b/pillow-12.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:af73337013e0b3b46f175e79492d96845b16126ddf79c438d7ea7ff27783a414", size = 2463612, upload-time = "2026-04-01T14:43:39.421Z" },
{ url = "https://files.pythonhosted.org/packages/4a/01/53d10cf0dbad820a8db274d259a37ba50b88b24768ddccec07355382d5ad/pillow-12.2.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8297651f5b5679c19968abefd6bb84d95fe30ef712eb1b2d9b2d31ca61267f4c", size = 4100837, upload-time = "2026-04-01T14:43:41.506Z" },
{ url = "https://files.pythonhosted.org/packages/0f/98/f3a6657ecb698c937f6c76ee564882945f29b79bad496abcba0e84659ec5/pillow-12.2.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:50d8520da2a6ce0af445fa6d648c4273c3eeefbc32d7ce049f22e8b5c3daecc2", size = 4176528, upload-time = "2026-04-01T14:43:43.773Z" },
{ url = "https://files.pythonhosted.org/packages/69/bc/8986948f05e3ea490b8442ea1c1d4d990b24a7e43d8a51b2c7d8b1dced36/pillow-12.2.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:766cef22385fa1091258ad7e6216792b156dc16d8d3fa607e7545b2b72061f1c", size = 3640401, upload-time = "2026-04-01T14:43:45.87Z" },
{ url = "https://files.pythonhosted.org/packages/34/46/6c717baadcd62bc8ed51d238d521ab651eaa74838291bda1f86fe1f864c9/pillow-12.2.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5d2fd0fa6b5d9d1de415060363433f28da8b1526c1c129020435e186794b3795", size = 5308094, upload-time = "2026-04-01T14:43:48.438Z" },
{ url = "https://files.pythonhosted.org/packages/71/43/905a14a8b17fdb1ccb58d282454490662d2cb89a6bfec26af6d3520da5ec/pillow-12.2.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:56b25336f502b6ed02e889f4ece894a72612fe885889a6e8c4c80239ff6e5f5f", size = 4695402, upload-time = "2026-04-01T14:43:51.292Z" },
{ url = "https://files.pythonhosted.org/packages/73/dd/42107efcb777b16fa0393317eac58f5b5cf30e8392e266e76e51cff28c3d/pillow-12.2.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f1c943e96e85df3d3478f7b691f229887e143f81fedab9b20205349ab04d73ed", size = 6280005, upload-time = "2026-04-01T14:43:54.242Z" },
{ url = "https://files.pythonhosted.org/packages/a8/68/b93e09e5e8549019e61acf49f65b1a8530765a7f812c77a7461bca7e4494/pillow-12.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:03f6fab9219220f041c74aeaa2939ff0062bd5c364ba9ce037197f4c6d498cd9", size = 8090669, upload-time = "2026-04-01T14:43:57.335Z" },
{ url = "https://files.pythonhosted.org/packages/4b/6e/3ccb54ce8ec4ddd1accd2d89004308b7b0b21c4ac3d20fa70af4760a4330/pillow-12.2.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5cdfebd752ec52bf5bb4e35d9c64b40826bc5b40a13df7c3cda20a2c03a0f5ed", size = 6395194, upload-time = "2026-04-01T14:43:59.864Z" },
{ url = "https://files.pythonhosted.org/packages/67/ee/21d4e8536afd1a328f01b359b4d3997b291ffd35a237c877b331c1c3b71c/pillow-12.2.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eedf4b74eda2b5a4b2b2fb4c006d6295df3bf29e459e198c90ea48e130dc75c3", size = 7082423, upload-time = "2026-04-01T14:44:02.74Z" },
{ url = "https://files.pythonhosted.org/packages/78/5f/e9f86ab0146464e8c133fe85df987ed9e77e08b29d8d35f9f9f4d6f917ba/pillow-12.2.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:00a2865911330191c0b818c59103b58a5e697cae67042366970a6b6f1b20b7f9", size = 6505667, upload-time = "2026-04-01T14:44:05.381Z" },
{ url = "https://files.pythonhosted.org/packages/ed/1e/409007f56a2fdce61584fd3acbc2bbc259857d555196cedcadc68c015c82/pillow-12.2.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1e1757442ed87f4912397c6d35a0db6a7b52592156014706f17658ff58bbf795", size = 7208580, upload-time = "2026-04-01T14:44:08.39Z" },
{ url = "https://files.pythonhosted.org/packages/23/c4/7349421080b12fb35414607b8871e9534546c128a11965fd4a7002ccfbee/pillow-12.2.0-cp313-cp313-win32.whl", hash = "sha256:144748b3af2d1b358d41286056d0003f47cb339b8c43a9ea42f5fea4d8c66b6e", size = 6375896, upload-time = "2026-04-01T14:44:11.197Z" },
{ url = "https://files.pythonhosted.org/packages/3f/82/8a3739a5e470b3c6cbb1d21d315800d8e16bff503d1f16b03a4ec3212786/pillow-12.2.0-cp313-cp313-win_amd64.whl", hash = "sha256:390ede346628ccc626e5730107cde16c42d3836b89662a115a921f28440e6a3b", size = 7081266, upload-time = "2026-04-01T14:44:13.947Z" },
{ url = "https://files.pythonhosted.org/packages/c3/25/f968f618a062574294592f668218f8af564830ccebdd1fa6200f598e65c5/pillow-12.2.0-cp313-cp313-win_arm64.whl", hash = "sha256:8023abc91fba39036dbce14a7d6535632f99c0b857807cbbbf21ecc9f4717f06", size = 2463508, upload-time = "2026-04-01T14:44:16.312Z" },
{ url = "https://files.pythonhosted.org/packages/4d/a4/b342930964e3cb4dce5038ae34b0eab4653334995336cd486c5a8c25a00c/pillow-12.2.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:042db20a421b9bafecc4b84a8b6e444686bd9d836c7fd24542db3e7df7baad9b", size = 5309927, upload-time = "2026-04-01T14:44:18.89Z" },
{ url = "https://files.pythonhosted.org/packages/9f/de/23198e0a65a9cf06123f5435a5d95cea62a635697f8f03d134d3f3a96151/pillow-12.2.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:dd025009355c926a84a612fecf58bb315a3f6814b17ead51a8e48d3823d9087f", size = 4698624, upload-time = "2026-04-01T14:44:21.115Z" },
{ url = "https://files.pythonhosted.org/packages/01/a6/1265e977f17d93ea37aa28aa81bad4fa597933879fac2520d24e021c8da3/pillow-12.2.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:88ddbc66737e277852913bd1e07c150cc7bb124539f94c4e2df5344494e0a612", size = 6321252, upload-time = "2026-04-01T14:44:23.663Z" },
{ url = "https://files.pythonhosted.org/packages/3c/83/5982eb4a285967baa70340320be9f88e57665a387e3a53a7f0db8231a0cd/pillow-12.2.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d362d1878f00c142b7e1a16e6e5e780f02be8195123f164edf7eddd911eefe7c", size = 8126550, upload-time = "2026-04-01T14:44:26.772Z" },
{ url = "https://files.pythonhosted.org/packages/4e/48/6ffc514adce69f6050d0753b1a18fd920fce8cac87620d5a31231b04bfc5/pillow-12.2.0-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2c727a6d53cb0018aadd8018c2b938376af27914a68a492f59dfcaca650d5eea", size = 6433114, upload-time = "2026-04-01T14:44:29.615Z" },
{ url = "https://files.pythonhosted.org/packages/36/a3/f9a77144231fb8d40ee27107b4463e205fa4677e2ca2548e14da5cf18dce/pillow-12.2.0-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:efd8c21c98c5cc60653bcb311bef2ce0401642b7ce9d09e03a7da87c878289d4", size = 7115667, upload-time = "2026-04-01T14:44:32.773Z" },
{ url = "https://files.pythonhosted.org/packages/c1/fc/ac4ee3041e7d5a565e1c4fd72a113f03b6394cc72ab7089d27608f8aaccb/pillow-12.2.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9f08483a632889536b8139663db60f6724bfcb443c96f1b18855860d7d5c0fd4", size = 6538966, upload-time = "2026-04-01T14:44:35.252Z" },
{ url = "https://files.pythonhosted.org/packages/c0/a8/27fb307055087f3668f6d0a8ccb636e7431d56ed0750e07a60547b1e083e/pillow-12.2.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:dac8d77255a37e81a2efcbd1fc05f1c15ee82200e6c240d7e127e25e365c39ea", size = 7238241, upload-time = "2026-04-01T14:44:37.875Z" },
{ url = "https://files.pythonhosted.org/packages/ad/4b/926ab182c07fccae9fcb120043464e1ff1564775ec8864f21a0ebce6ac25/pillow-12.2.0-cp313-cp313t-win32.whl", hash = "sha256:ee3120ae9dff32f121610bb08e4313be87e03efeadfc6c0d18f89127e24d0c24", size = 6379592, upload-time = "2026-04-01T14:44:40.336Z" },
{ url = "https://files.pythonhosted.org/packages/c2/c4/f9e476451a098181b30050cc4c9a3556b64c02cf6497ea421ac047e89e4b/pillow-12.2.0-cp313-cp313t-win_amd64.whl", hash = "sha256:325ca0528c6788d2a6c3d40e3568639398137346c3d6e66bb61db96b96511c98", size = 7085542, upload-time = "2026-04-01T14:44:43.251Z" },
{ url = "https://files.pythonhosted.org/packages/00/a4/285f12aeacbe2d6dc36c407dfbbe9e96d4a80b0fb710a337f6d2ad978c75/pillow-12.2.0-cp313-cp313t-win_arm64.whl", hash = "sha256:2e5a76d03a6c6dcef67edabda7a52494afa4035021a79c8558e14af25313d453", size = 2465765, upload-time = "2026-04-01T14:44:45.996Z" },
{ url = "https://files.pythonhosted.org/packages/4e/b7/2437044fb910f499610356d1352e3423753c98e34f915252aafecc64889f/pillow-12.2.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0538bd5e05efec03ae613fd89c4ce0368ecd2ba239cc25b9f9be7ed426b0af1f", size = 5273969, upload-time = "2026-04-01T14:45:55.538Z" },
{ url = "https://files.pythonhosted.org/packages/f6/f4/8316e31de11b780f4ac08ef3654a75555e624a98db1056ecb2122d008d5a/pillow-12.2.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:394167b21da716608eac917c60aa9b969421b5dcbbe02ae7f013e7b85811c69d", size = 4659674, upload-time = "2026-04-01T14:45:58.093Z" },
{ url = "https://files.pythonhosted.org/packages/d4/37/664fca7201f8bb2aa1d20e2c3d5564a62e6ae5111741966c8319ca802361/pillow-12.2.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5d04bfa02cc2d23b497d1e90a0f927070043f6cbf303e738300532379a4b4e0f", size = 5288479, upload-time = "2026-04-01T14:46:01.141Z" },
{ url = "https://files.pythonhosted.org/packages/49/62/5b0ed78fce87346be7a5cfcfaaad91f6a1f98c26f86bdbafa2066c647ef6/pillow-12.2.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0c838a5125cee37e68edec915651521191cef1e6aa336b855f495766e77a366e", size = 7032230, upload-time = "2026-04-01T14:46:03.874Z" },
{ url = "https://files.pythonhosted.org/packages/c3/28/ec0fc38107fc32536908034e990c47914c57cd7c5a3ece4d8d8f7ffd7e27/pillow-12.2.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a6c9fa44005fa37a91ebfc95d081e8079757d2e904b27103f4f5fa6f0bf78c0", size = 5355404, upload-time = "2026-04-01T14:46:06.33Z" },
{ url = "https://files.pythonhosted.org/packages/5e/8b/51b0eddcfa2180d60e41f06bd6d0a62202b20b59c68f5a132e615b75aecf/pillow-12.2.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:25373b66e0dd5905ed63fa3cae13c82fbddf3079f2c8bf15c6fb6a35586324c1", size = 6002215, upload-time = "2026-04-01T14:46:08.83Z" },
{ url = "https://files.pythonhosted.org/packages/bc/60/5382c03e1970de634027cee8e1b7d39776b778b81812aaf45b694dfe9e28/pillow-12.2.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:bfa9c230d2fe991bed5318a5f119bd6780cda2915cca595393649fc118ab895e", size = 7080946, upload-time = "2026-04-01T14:46:11.734Z" },
{ url = "https://files.pythonhosted.org/packages/25/c2/669d88644cddb1485bd9534e63e8cf476c8e51cb3c3a1297677023505c0e/pillow-12.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a", size = 5392418, upload-time = "2026-07-01T11:53:27.808Z" },
{ url = "https://files.pythonhosted.org/packages/6b/ba/3762f376a2948e3036488d773a146e0ae6ecc2ca03ac20e2615bd0b2ba02/pillow-12.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7", size = 4785287, upload-time = "2026-07-01T11:53:29.761Z" },
{ url = "https://files.pythonhosted.org/packages/07/50/b5d688cc9c52d4482f3d5bcab6ce20bc2a74a85d2343841c907444a3be2c/pillow-12.3.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f", size = 6253754, upload-time = "2026-07-01T11:53:32.298Z" },
{ url = "https://files.pythonhosted.org/packages/4e/89/36f4cd76cf4baf05c50ababb976249153f18c959171c7f6ba09a6f217260/pillow-12.3.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec", size = 6925605, upload-time = "2026-07-01T11:53:34.487Z" },
{ url = "https://files.pythonhosted.org/packages/eb/c0/4de58cf6633b9e3a6061ef4be6fb91fc3c90b812ece886f531e3c523d777/pillow-12.3.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468", size = 6327788, upload-time = "2026-07-01T11:53:36.433Z" },
{ url = "https://files.pythonhosted.org/packages/87/3c/14d53682a19550dbbaf3b598f807d5457646c510805a44c7d7891cd1cd1a/pillow-12.3.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed", size = 7036288, upload-time = "2026-07-01T11:53:38.712Z" },
{ url = "https://files.pythonhosted.org/packages/38/1d/36279e3c77efe034e4cc2b0393ee74ffdb5a62391dacbf9b916154f5f0b8/pillow-12.3.0-cp310-cp310-win32.whl", hash = "sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1", size = 6472396, upload-time = "2026-07-01T11:53:40.781Z" },
{ url = "https://files.pythonhosted.org/packages/48/7c/8fa0039574c476d7c6fa57dd7c32a130436877c6ec1e5ce1cc8ec44878c1/pillow-12.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb", size = 7226887, upload-time = "2026-07-01T11:53:42.764Z" },
{ url = "https://files.pythonhosted.org/packages/fa/17/e324be141d173c1c919428066c3259f21c1b8982e564e01a4a81e96dbdcf/pillow-12.3.0-cp310-cp310-win_arm64.whl", hash = "sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f", size = 2568039, upload-time = "2026-07-01T11:53:45.372Z" },
{ url = "https://files.pythonhosted.org/packages/fb/c8/0a78b0e02d7ac54bc03e5321c9220da52f0c2ea83b21f7c40e7f3169c502/pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756", size = 5392415, upload-time = "2026-07-01T11:53:47.162Z" },
{ url = "https://files.pythonhosted.org/packages/b2/5b/a02d30018abd97ced9f5a6c63d28597694a00d066516b9c1c6de45859fc9/pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6", size = 4785266, upload-time = "2026-07-01T11:53:49.079Z" },
{ url = "https://files.pythonhosted.org/packages/c8/98/766667a4be768150a202836acd9fad19c06824ca86c4286d3cf6b274964e/pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd", size = 6263814, upload-time = "2026-07-01T11:53:51.32Z" },
{ url = "https://files.pythonhosted.org/packages/3b/2d/ede717bc1144f63886c21fd349bb95860b0d1a21149ff16f2bb362b612b6/pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd", size = 6934408, upload-time = "2026-07-01T11:53:53.487Z" },
{ url = "https://files.pythonhosted.org/packages/a3/48/9c58b685e69d49c31af6c8eb9012055fab7e665785165c84796e2c73ce72/pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c", size = 6337160, upload-time = "2026-07-01T11:53:55.457Z" },
{ url = "https://files.pythonhosted.org/packages/ff/fa/dc2a5c0ba6df93f67c31d34b808b7ce440b40cdbf96f0b81cde1d1e6fa93/pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5", size = 7045172, upload-time = "2026-07-01T11:53:57.736Z" },
{ url = "https://files.pythonhosted.org/packages/86/a5/444817a4d4c4c2417df00513086ca196f388d8f9ef40c2e4ccd1ad1af54b/pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b", size = 6472232, upload-time = "2026-07-01T11:53:59.767Z" },
{ url = "https://files.pythonhosted.org/packages/63/c6/4bad1b18d132a50b27e1365e1ab163616f7a5bb56d330f66f9d1d9d4f9d4/pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a", size = 7233653, upload-time = "2026-07-01T11:54:02.066Z" },
{ url = "https://files.pythonhosted.org/packages/fd/16/00f91ab7760dc842f5aad55217e80fc4a7067a0604535249bc8a2d6d9870/pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26", size = 2568195, upload-time = "2026-07-01T11:54:04.622Z" },
{ url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" },
{ url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" },
{ url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" },
{ url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" },
{ url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" },
{ url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" },
{ url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" },
{ url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" },
{ url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" },
{ url = "https://files.pythonhosted.org/packages/9d/ac/31fb64e1e7efb5a4b50cd3d92049ba89ac6e4d8d3bb6a74e15048ca3353e/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89", size = 4161684, upload-time = "2026-07-01T11:54:25.934Z" },
{ url = "https://files.pythonhosted.org/packages/87/b4/9805e23d2b4d77842b468513841fda254ee42f0289d25088340e4ff46e2d/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace", size = 4255487, upload-time = "2026-07-01T11:54:27.935Z" },
{ url = "https://files.pythonhosted.org/packages/df/39/ecf519435a200c693fe053a6ee4d835b41cf963a4dfc2551c4e637cb2a71/pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec", size = 3696433, upload-time = "2026-07-01T11:54:29.813Z" },
{ url = "https://files.pythonhosted.org/packages/42/92/2fc3ffad878ae8dd5469ec1bc8eb83b71f48e13efdf68f02709003982a32/pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66", size = 5345889, upload-time = "2026-07-01T11:54:31.97Z" },
{ url = "https://files.pythonhosted.org/packages/10/76/8803c13605b763d33d156c4678fc77f8443389c0c51c8aef707bb02015f4/pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35", size = 4780109, upload-time = "2026-07-01T11:54:34.026Z" },
{ url = "https://files.pythonhosted.org/packages/1f/01/e18aff37cb0b4aac47ac90f016d347a49aca667ef97f190b06ac2aabc928/pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65", size = 6263736, upload-time = "2026-07-01T11:54:36.131Z" },
{ url = "https://files.pythonhosted.org/packages/f7/62/de5bdd77d935331f4f802edc11e4d82950f642caad6cb2f949837b8560e2/pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3", size = 6937129, upload-time = "2026-07-01T11:54:38.216Z" },
{ url = "https://files.pythonhosted.org/packages/70/4d/105627a13300c5e0df1d174230b32fd1273062c96f7745fd552b945d1e1d/pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a", size = 6339562, upload-time = "2026-07-01T11:54:40.354Z" },
{ url = "https://files.pythonhosted.org/packages/6b/1d/f13de01a553988ab895ba1c722e06cf3144d4f57656fd5b81b6d881f1179/pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e", size = 7049439, upload-time = "2026-07-01T11:54:42.489Z" },
{ url = "https://files.pythonhosted.org/packages/c9/f9/066794cca041b969964f779ee5fa66a9498bbf34248ac39c5d7954e4198f/pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f", size = 6473287, upload-time = "2026-07-01T11:54:44.9Z" },
{ url = "https://files.pythonhosted.org/packages/a6/9b/7a58e61d62be561da3a356fe2384d4059a6345fc130e23ef1c36a5b81d24/pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8", size = 7239691, upload-time = "2026-07-01T11:54:47.141Z" },
{ url = "https://files.pythonhosted.org/packages/aa/b0/c4ed4f0ef8f8fa5ee8351537db6650bb8189f7e118842978dd6589065692/pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b", size = 2568185, upload-time = "2026-07-01T11:54:49.137Z" },
{ url = "https://files.pythonhosted.org/packages/75/18/2e8b40223153ccbc60df07f9e8928dc0c76202aa4e55ae9f53962b6510d6/pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468", size = 5302510, upload-time = "2026-07-01T11:56:25.736Z" },
{ url = "https://files.pythonhosted.org/packages/46/3e/51fabf59d5ab801ceab709453d3ab6b180083496579549de4c45ced6528a/pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94", size = 4736058, upload-time = "2026-07-01T11:56:28.041Z" },
{ url = "https://files.pythonhosted.org/packages/bf/20/22fe9384b7949e25fb1293bcfc84fb82590ff4ea6b37c95b24d26d793d86/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e", size = 5237776, upload-time = "2026-07-01T11:56:30.263Z" },
{ url = "https://files.pythonhosted.org/packages/08/14/f6ba68107680ffa74b39985f3f30884e41318fbc4250caa423c79b4788bb/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3", size = 5860358, upload-time = "2026-07-01T11:56:32.68Z" },
{ url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" },
]
[[package]]
@@ -1357,6 +1345,14 @@ dependencies = [
{ name = "openai-harmony" },
{ name = "prime-pydantic-config" },
{ name = "tiktoken" },
]
[package.optional-dependencies]
multimodal = [
{ name = "pillow" },
{ name = "transformers" },
]
transformers = [
{ name = "transformers" },
]
@@ -1369,6 +1365,7 @@ dev = [
{ name = "ruff" },
{ name = "torch" },
{ name = "torchvision" },
{ name = "transformers" },
{ name = "ty" },
]
@@ -1378,10 +1375,13 @@ requires-dist = [
{ name = "numpy" },
{ name = "openai", specifier = ">=1.108.1" },
{ name = "openai-harmony", specifier = ">=0.0.4" },
{ name = "pillow", marker = "extra == 'multimodal'", specifier = ">=12.2.0" },
{ name = "prime-pydantic-config", specifier = ">=0.3.0.dev83" },
{ name = "tiktoken" },
{ name = "transformers", specifier = ">=4.50.0" },
{ name = "transformers", marker = "extra == 'multimodal'", specifier = ">=4.50.0" },
{ name = "transformers", marker = "extra == 'transformers'", specifier = ">=4.50.0" },
]
provides-extras = ["multimodal", "transformers"]
[package.metadata.requires-dev]
dev = [
@@ -1392,6 +1392,7 @@ dev = [
{ name = "ruff" },
{ name = "torch", specifier = ">=2.11.0" },
{ name = "torchvision", specifier = ">=0.26.0" },
{ name = "transformers", specifier = ">=4.50.0" },
{ name = "ty", specifier = ">=0.0.1a29,<0.0.22" },
]
@@ -1450,37 +1451,35 @@ wheels = [
[[package]]
name = "safetensors"
version = "0.7.0"
version = "0.8.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/29/9c/6e74567782559a63bd040a236edca26fd71bc7ba88de2ef35d75df3bca5e/safetensors-0.7.0.tar.gz", hash = "sha256:07663963b67e8bd9f0b8ad15bb9163606cd27cc5a1b96235a50d8369803b96b0", size = 200878, upload-time = "2025-11-19T15:18:43.199Z" }
sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/fa/47/aef6c06649039accf914afef490268e1067ed82be62bcfa5b7e886ad15e8/safetensors-0.7.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c82f4d474cf725255d9e6acf17252991c3c8aac038d6ef363a4bf8be2f6db517", size = 467781, upload-time = "2025-11-19T15:18:35.84Z" },
{ url = "https://files.pythonhosted.org/packages/e8/00/374c0c068e30cd31f1e1b46b4b5738168ec79e7689ca82ee93ddfea05109/safetensors-0.7.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:94fd4858284736bb67a897a41608b5b0c2496c9bdb3bf2af1fa3409127f20d57", size = 447058, upload-time = "2025-11-19T15:18:34.416Z" },
{ url = "https://files.pythonhosted.org/packages/f1/06/578ffed52c2296f93d7fd2d844cabfa92be51a587c38c8afbb8ae449ca89/safetensors-0.7.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e07d91d0c92a31200f25351f4acb2bc6aff7f48094e13ebb1d0fb995b54b6542", size = 491748, upload-time = "2025-11-19T15:18:09.79Z" },
{ url = "https://files.pythonhosted.org/packages/ae/33/1debbbb70e4791dde185edb9413d1fe01619255abb64b300157d7f15dddd/safetensors-0.7.0-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8469155f4cb518bafb4acf4865e8bb9d6804110d2d9bdcaa78564b9fd841e104", size = 503881, upload-time = "2025-11-19T15:18:16.145Z" },
{ url = "https://files.pythonhosted.org/packages/8e/1c/40c2ca924d60792c3be509833df711b553c60effbd91da6f5284a83f7122/safetensors-0.7.0-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:54bef08bf00a2bff599982f6b08e8770e09cc012d7bba00783fc7ea38f1fb37d", size = 623463, upload-time = "2025-11-19T15:18:21.11Z" },
{ url = "https://files.pythonhosted.org/packages/9b/3a/13784a9364bd43b0d61eef4bea2845039bc2030458b16594a1bd787ae26e/safetensors-0.7.0-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:42cb091236206bb2016d245c377ed383aa7f78691748f3bb6ee1bfa51ae2ce6a", size = 532855, upload-time = "2025-11-19T15:18:25.719Z" },
{ url = "https://files.pythonhosted.org/packages/a0/60/429e9b1cb3fc651937727befe258ea24122d9663e4d5709a48c9cbfceecb/safetensors-0.7.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dac7252938f0696ddea46f5e855dd3138444e82236e3be475f54929f0c510d48", size = 507152, upload-time = "2025-11-19T15:18:33.023Z" },
{ url = "https://files.pythonhosted.org/packages/3c/a8/4b45e4e059270d17af60359713ffd83f97900d45a6afa73aaa0d737d48b6/safetensors-0.7.0-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1d060c70284127fa805085d8f10fbd0962792aed71879d00864acda69dbab981", size = 541856, upload-time = "2025-11-19T15:18:31.075Z" },
{ url = "https://files.pythonhosted.org/packages/06/87/d26d8407c44175d8ae164a95b5a62707fcc445f3c0c56108e37d98070a3d/safetensors-0.7.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:cdab83a366799fa730f90a4ebb563e494f28e9e92c4819e556152ad55e43591b", size = 674060, upload-time = "2025-11-19T15:18:37.211Z" },
{ url = "https://files.pythonhosted.org/packages/11/f5/57644a2ff08dc6325816ba7217e5095f17269dada2554b658442c66aed51/safetensors-0.7.0-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:672132907fcad9f2aedcb705b2d7b3b93354a2aec1b2f706c4db852abe338f85", size = 771715, upload-time = "2025-11-19T15:18:38.689Z" },
{ url = "https://files.pythonhosted.org/packages/86/31/17883e13a814bd278ae6e266b13282a01049b0c81341da7fd0e3e71a80a3/safetensors-0.7.0-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:5d72abdb8a4d56d4020713724ba81dac065fedb7f3667151c4a637f1d3fb26c0", size = 714377, upload-time = "2025-11-19T15:18:40.162Z" },
{ url = "https://files.pythonhosted.org/packages/4a/d8/0c8a7dc9b41dcac53c4cbf9df2b9c83e0e0097203de8b37a712b345c0be5/safetensors-0.7.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b0f6d66c1c538d5a94a73aa9ddca8ccc4227e6c9ff555322ea40bdd142391dd4", size = 677368, upload-time = "2025-11-19T15:18:41.627Z" },
{ url = "https://files.pythonhosted.org/packages/05/e5/cb4b713c8a93469e3c5be7c3f8d77d307e65fe89673e731f5c2bfd0a9237/safetensors-0.7.0-cp38-abi3-win32.whl", hash = "sha256:c74af94bf3ac15ac4d0f2a7c7b4663a15f8c2ab15ed0fc7531ca61d0835eccba", size = 326423, upload-time = "2025-11-19T15:18:45.74Z" },
{ url = "https://files.pythonhosted.org/packages/5d/e6/ec8471c8072382cb91233ba7267fd931219753bb43814cbc71757bfd4dab/safetensors-0.7.0-cp38-abi3-win_amd64.whl", hash = "sha256:d1239932053f56f3456f32eb9625590cc7582e905021f94636202a864d470755", size = 341380, upload-time = "2025-11-19T15:18:44.427Z" },
{ url = "https://files.pythonhosted.org/packages/a7/6a/4d08d89a6fcbe905c5ae68b8b34f0791850882fc19782d0d02c65abbdf3b/safetensors-0.7.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f4729811a6640d019a4b7ba8638ee2fd21fa5ca8c7e7bdf0fed62068fcaac737", size = 492430, upload-time = "2025-11-19T15:18:11.884Z" },
{ url = "https://files.pythonhosted.org/packages/dd/29/59ed8152b30f72c42d00d241e58eaca558ae9dbfa5695206e2e0f54c7063/safetensors-0.7.0-pp310-pypy310_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:12f49080303fa6bb424b362149a12949dfbbf1e06811a88f2307276b0c131afd", size = 503977, upload-time = "2025-11-19T15:18:17.523Z" },
{ url = "https://files.pythonhosted.org/packages/d3/0b/4811bfec67fa260e791369b16dab105e4bae82686120554cc484064e22b4/safetensors-0.7.0-pp310-pypy310_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0071bffba4150c2f46cae1432d31995d77acfd9f8db598b5d1a2ce67e8440ad2", size = 623890, upload-time = "2025-11-19T15:18:22.666Z" },
{ url = "https://files.pythonhosted.org/packages/58/5b/632a58724221ef03d78ab65062e82a1010e1bef8e8e0b9d7c6d7b8044841/safetensors-0.7.0-pp310-pypy310_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:473b32699f4200e69801bf5abf93f1a4ecd432a70984df164fc22ccf39c4a6f3", size = 531885, upload-time = "2025-11-19T15:18:27.146Z" },
{ url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" },
{ url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" },
{ url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" },
{ url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" },
{ url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" },
{ url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" },
{ url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" },
{ url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" },
{ url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" },
{ url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" },
{ url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" },
{ url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" },
{ url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" },
{ url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" },
{ url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" },
{ url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" },
]
[[package]]
name = "setuptools"
version = "81.0.0"
version = "83.0.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/0d/1c/73e719955c59b8e424d015ab450f51c0af856ae46ea2da83eba51cc88de1/setuptools-81.0.0.tar.gz", hash = "sha256:487b53915f52501f0a79ccfd0c02c165ffe06631443a886740b91af4b7a5845a", size = 1198299, upload-time = "2026-02-06T21:10:39.601Z" }
sdist = { url = "https://files.pythonhosted.org/packages/34/26/f5d29e25ffdb535afef2d35cdb55b325298f96debd670da4c325e08d70f4/setuptools-83.0.0.tar.gz", hash = "sha256:025bccbbf0fa05b6192bc64ae1e7b16e001fd6d6d4d5de03c97b1c1ade523bef", size = 1154254, upload-time = "2026-07-04T15:31:22.699Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e1/e3/c164c88b2e5ce7b24d667b9bd83589cf4f3520d97cad01534cd3c4f55fdb/setuptools-81.0.0-py3-none-any.whl", hash = "sha256:fdd925d5c5d9f62e4b74b30d6dd7828ce236fd6ed998a08d81de62ce5a6310d6", size = 1062021, upload-time = "2026-02-06T21:10:37.175Z" },
{ url = "https://files.pythonhosted.org/packages/5d/40/e1e72872c6354b306daef1703549e8e83b4d43cfea356311bf722a043752/setuptools-83.0.0-py3-none-any.whl", hash = "sha256:29b23c360f22f414dc7336bb39178cc7bcbf6021ed2733cde173f09dba19abb3", size = 1008090, upload-time = "2026-07-04T15:31:20.885Z" },
]
[[package]]
@@ -1628,7 +1627,7 @@ wheels = [
[[package]]
name = "torch"
version = "2.11.0"
version = "2.13.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cuda-bindings", marker = "sys_platform == 'linux'" },
@@ -1648,31 +1647,27 @@ dependencies = [
{ name = "typing-extensions" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/ac/f2/c1690994afe461aae2d0cac62251e6802a703dec0a6c549c02ecd0de92a9/torch-2.11.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2c0d7fcfbc0c4e8bb5ebc3907cbc0c6a0da1b8f82b1fc6e14e914fa0b9baf74e", size = 80526521, upload-time = "2026-03-23T18:12:06.86Z" },
{ url = "https://files.pythonhosted.org/packages/a4/f0/98ae802fa8c09d3149b0c8690741f3f5753c90e779bd28c9613257295945/torch-2.11.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:4cf8687f4aec3900f748d553483ef40e0ac38411c3c48d0a86a438f6d7a99b18", size = 419723025, upload-time = "2026-03-23T18:11:43.774Z" },
{ url = "https://files.pythonhosted.org/packages/f9/1e/18a9b10b4bd34f12d4e561c52b0ae7158707b8193c6cfc0aad2b48167090/torch-2.11.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:1b32ceda909818a03b112006709b02be1877240c31750a8d9c6b7bf5f2d8a6e5", size = 530589207, upload-time = "2026-03-23T18:11:23.756Z" },
{ url = "https://files.pythonhosted.org/packages/35/40/2d532e8c0e23705be9d1debce5bc37b68d59a39bda7584c26fe9668076fe/torch-2.11.0-cp310-cp310-win_amd64.whl", hash = "sha256:b3c712ae6fb8e7a949051a953fc412fe0a6940337336c3b6f905e905dac5157f", size = 114518313, upload-time = "2026-03-23T18:11:58.281Z" },
{ url = "https://files.pythonhosted.org/packages/ae/0d/98b410492609e34a155fa8b121b55c7dca229f39636851c3a9ec20edea21/torch-2.11.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7b6a60d48062809f58595509c524b88e6ddec3ebe25833d6462eeab81e5f2ce4", size = 80529712, upload-time = "2026-03-23T18:12:02.608Z" },
{ url = "https://files.pythonhosted.org/packages/84/03/acea680005f098f79fd70c1d9d5ccc0cb4296ec2af539a0450108232fc0c/torch-2.11.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:d91aac77f24082809d2c5a93f52a5f085032740a1ebc9252a7b052ef5a4fddc6", size = 419718178, upload-time = "2026-03-23T18:10:46.675Z" },
{ url = "https://files.pythonhosted.org/packages/8c/8b/d7be22fbec9ffee6cff31a39f8750d4b3a65d349a286cf4aec74c2375662/torch-2.11.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:7aa2f9bbc6d4595ba72138026b2074be1233186150e9292865e04b7a63b8c67a", size = 530604548, upload-time = "2026-03-23T18:10:03.569Z" },
{ url = "https://files.pythonhosted.org/packages/d1/bd/9912d30b68845256aabbb4a40aeefeef3c3b20db5211ccda653544ada4b6/torch-2.11.0-cp311-cp311-win_amd64.whl", hash = "sha256:73e24aaf8f36ab90d95cd1761208b2eb70841c2a9ca1a3f9061b39fc5331b708", size = 114519675, upload-time = "2026-03-23T18:11:52.995Z" },
{ url = "https://files.pythonhosted.org/packages/6f/8b/69e3008d78e5cee2b30183340cc425081b78afc5eff3d080daab0adda9aa/torch-2.11.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4b5866312ee6e52ea625cd211dcb97d6a2cdc1131a5f15cc0d87eec948f6dd34", size = 80606338, upload-time = "2026-03-23T18:11:34.781Z" },
{ url = "https://files.pythonhosted.org/packages/13/16/42e5915ebe4868caa6bac83a8ed59db57f12e9a61b7d749d584776ed53d5/torch-2.11.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:f99924682ef0aa6a4ab3b1b76f40dc6e273fca09f367d15a524266db100a723f", size = 419731115, upload-time = "2026-03-23T18:11:06.944Z" },
{ url = "https://files.pythonhosted.org/packages/1a/c9/82638ef24d7877510f83baf821f5619a61b45568ce21c0a87a91576510aa/torch-2.11.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:0f68f4ac6d95d12e896c3b7a912b5871619542ec54d3649cf48cc1edd4dd2756", size = 530712279, upload-time = "2026-03-23T18:10:31.481Z" },
{ url = "https://files.pythonhosted.org/packages/1c/ff/6756f1c7ee302f6d202120e0f4f05b432b839908f9071157302cedfc5232/torch-2.11.0-cp312-cp312-win_amd64.whl", hash = "sha256:fbf39280699d1b869f55eac536deceaa1b60bd6788ba74f399cc67e60a5fab10", size = 114556047, upload-time = "2026-03-23T18:10:55.931Z" },
{ url = "https://files.pythonhosted.org/packages/87/89/5ea6722763acee56b045435fb84258db7375c48165ec8be7880ab2b281c5/torch-2.11.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1e6debd97ccd3205bbb37eb806a9d8219e1139d15419982c09e23ef7d4369d18", size = 80606801, upload-time = "2026-03-23T18:10:18.649Z" },
{ url = "https://files.pythonhosted.org/packages/32/d1/8ed2173589cbfe744ed54e5a73efc107c0085ba5777ee93a5f4c1ab90553/torch-2.11.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:63a68fa59de8f87acc7e85a5478bb2dddbb3392b7593ec3e78827c793c4b73fd", size = 419732382, upload-time = "2026-03-23T18:08:30.835Z" },
{ url = "https://files.pythonhosted.org/packages/3d/e1/b73f7c575a4b8f87a5928f50a1e35416b5e27295d8be9397d5293e7e8d4c/torch-2.11.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:cc89b9b173d9adfab59fd227f0ab5e5516d9a52b658ae41d64e59d2e55a418db", size = 530711509, upload-time = "2026-03-23T18:08:47.213Z" },
{ url = "https://files.pythonhosted.org/packages/66/82/3e3fcdd388fbe54e29fd3f991f36846ff4ac90b0d0181e9c8f7236565f82/torch-2.11.0-cp313-cp313-win_amd64.whl", hash = "sha256:4dda3b3f52d121063a731ddb835f010dc137b920d7fec2778e52f60d8e4bf0cd", size = 114555842, upload-time = "2026-03-23T18:09:52.111Z" },
{ url = "https://files.pythonhosted.org/packages/db/38/8ac78069621b8c2b4979c2f96dc8409ef5e9c4189f6aac629189a78677ca/torch-2.11.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:8b394322f49af4362d4f80e424bcaca7efcd049619af03a4cf4501520bdf0fb4", size = 80959574, upload-time = "2026-03-23T18:10:14.214Z" },
{ url = "https://files.pythonhosted.org/packages/6d/6c/56bfb37073e7136e6dd86bfc6af7339946dd684e0ecf2155ac0eee687ae1/torch-2.11.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:2658f34ce7e2dabf4ec73b45e2ca68aedad7a5be87ea756ad656eaf32bf1e1ea", size = 419732324, upload-time = "2026-03-23T18:09:36.604Z" },
{ url = "https://files.pythonhosted.org/packages/07/f4/1b666b6d61d3394cca306ea543ed03a64aad0a201b6cd159f1d41010aeb1/torch-2.11.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:98bb213c3084cfe176302949bdc360074b18a9da7ab59ef2edc9d9f742504778", size = 530596026, upload-time = "2026-03-23T18:09:20.842Z" },
{ url = "https://files.pythonhosted.org/packages/48/6b/30d1459fa7e4b67e9e3fe1685ca1d8bb4ce7c62ef436c3a615963c6c866c/torch-2.11.0-cp313-cp313t-win_amd64.whl", hash = "sha256:a97b94bbf62992949b4730c6cd2cc9aee7b335921ee8dc207d930f2ed09ae2db", size = 114793702, upload-time = "2026-03-23T18:09:47.304Z" },
{ url = "https://files.pythonhosted.org/packages/7f/e7/19894fdb51c7dbaf94f5a79bb0871da0992e8e4241e579cb006da46d2e58/torch-2.13.0-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:94f0de129916f77b8dc2c7a8eff644cfeddfe59e39c9f55e9f6e17543410281d", size = 111178962, upload-time = "2026-07-08T16:05:49.855Z" },
{ url = "https://files.pythonhosted.org/packages/d1/5c/b1d5de470c54e339b30a92d96683a71bcebd78f5f2a7fc714cd6dc6bbd68/torch-2.13.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:0ab4b69f3ee03a62a002cfbf77b1ca5e88aceb4ea64cb4388bb28f638ddbb045", size = 427198333, upload-time = "2026-07-08T16:05:36.847Z" },
{ url = "https://files.pythonhosted.org/packages/50/c0/68a84105e1fcb8970144b388ff3d3e5dc15a3be28c1e247841f7d7247e41/torch-2.13.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:c78b7b4d04461855a764cf01bae9a462bb88bc93defcfa11235cbc8fdf3e12c4", size = 526555154, upload-time = "2026-07-08T16:05:06.507Z" },
{ url = "https://files.pythonhosted.org/packages/2e/c9/0bb9d097b03cbaf96bb75b15e867347b8e41bfcdfe0539452d17d9e63993/torch-2.13.0-cp310-cp310-win_amd64.whl", hash = "sha256:2bd30b6b730d987fa386ce3898933762c5cb8cc82eb0535211d787cc3ce2dfeb", size = 122015602, upload-time = "2026-07-08T16:05:45.25Z" },
{ url = "https://files.pythonhosted.org/packages/5b/fe/cba54dc58523434919b66f13a667e36e436deddd77ca519e96553617d4ec/torch-2.13.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:e76f9bcecc52b8ff711239a2f7547d5353df95878ab232f0773c1d95928b92f8", size = 111187938, upload-time = "2026-07-08T16:05:17.065Z" },
{ url = "https://files.pythonhosted.org/packages/c2/59/1e3160e18e12aa3038390efab3ce02b36a9d4d6a527ecdd8520dca2e68d8/torch-2.13.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:092790c696a760c729fd5722835f50b9d81fd7c8f141571f3f3cf4081a8f664c", size = 427199369, upload-time = "2026-07-08T16:04:51.054Z" },
{ url = "https://files.pythonhosted.org/packages/01/79/1f2d34ad7034ee1c7ffc1cf8bf0f8213af2a81df6ecdb3997ecec107c09d/torch-2.13.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:60fcdcb2f3876e21146cb4524ef06397d727ca9ad5f020818547e25075fe3cb7", size = 526574961, upload-time = "2026-07-08T16:04:07.075Z" },
{ url = "https://files.pythonhosted.org/packages/6c/fd/0f2ce40f58aefbdb3392f9acce3c8171940943ae2d661f70558bfa73befb/torch-2.13.0-cp311-cp311-win_amd64.whl", hash = "sha256:a0d8b11f16a48d60e2015d8213aa0390744cbebb98e58b62b3514dddc656e330", size = 122015870, upload-time = "2026-07-08T16:05:27.59Z" },
{ url = "https://files.pythonhosted.org/packages/c4/3a/ed0f4d4d1dcde03bced7aac9a28e800abcdc0cbd06b6775044c9fbd877b7/torch-2.13.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:2fe228aba290d14b9f31b049be550dbd469c3fd3013d7a19705b30454da97027", size = 111213045, upload-time = "2026-07-08T16:05:22.997Z" },
{ url = "https://files.pythonhosted.org/packages/df/a9/f6a2a4d763ff1df02e9a64c477029db614295bc9367f4131223791ccc243/torch-2.13.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:572df8be8ffb4599c88cbd6a0726f1f854f4da65d2e3c09f0e2c2283333cd6d4", size = 427210998, upload-time = "2026-07-08T16:04:37.708Z" },
{ url = "https://files.pythonhosted.org/packages/f3/82/fea946351658e6534db52d2cc12bc53087cbf87f9440c5f180f367c1950b/torch-2.13.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:796633c4cdf0fe2cdced72d8f88f22e73dbcfce83132763162f6d4bff13b820b", size = 526605292, upload-time = "2026-07-08T16:04:22.81Z" },
{ url = "https://files.pythonhosted.org/packages/21/d6/e8f3c6f7e01f626f77259de9860d2a78bc84c40539e28e79b7e98b0bb659/torch-2.13.0-cp312-cp312-win_amd64.whl", hash = "sha256:024c6cc0c1b085f2f91f20a3dc27b0471d021c31ce84b81be3afdc39f791fd9d", size = 122057313, upload-time = "2026-07-08T16:03:53.43Z" },
{ url = "https://files.pythonhosted.org/packages/0d/fa/c1c10b7aff4a9a3e8956d4f0a5f468fa6db7abc3208805719076772b4833/torch-2.13.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:33449899ce5496c1b84b4853179d94fd102028ae1407314d9fb956bb79e70d09", size = 111213743, upload-time = "2026-07-08T16:03:28.579Z" },
{ url = "https://files.pythonhosted.org/packages/11/18/9ecb37b56293a0be8d80f810bf672a72fe7e02f8b475d5ef1b9bf8a0d748/torch-2.13.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:1e09d6a722504957c694faceca843acde562786df1144ebcc5a74075ec7f6005", size = 427213008, upload-time = "2026-07-08T16:03:44.106Z" },
{ url = "https://files.pythonhosted.org/packages/d4/5a/7c50ba1b7b713d71d34669c6d13dab0a11531a3eceb0307a5162dbfec0f7/torch-2.13.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:a3a9a21312872af8a26950b2c15680335a386a1f56ed03e780653d78b9607e9e", size = 526602329, upload-time = "2026-07-08T16:03:12.649Z" },
{ url = "https://files.pythonhosted.org/packages/91/3d/e7adcc6aaf36961cd18f56cf8ad0f3058c3a5c84ccf391762176c94581b8/torch-2.13.0-cp313-cp313-win_amd64.whl", hash = "sha256:49b58f1e2c52440abb6f17c28f0335fe6c6d01ad1a7f55b0183b81e4b34d64e6", size = 122057920, upload-time = "2026-07-08T16:03:01.808Z" },
]
[[package]]
name = "torchvision"
version = "0.26.0"
version = "0.28.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
@@ -1681,26 +1676,22 @@ dependencies = [
{ name = "torch" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/74/b4/cdfee31e0402ea035135462cb0ab496e974d56fab6b4e7a1f0cbccb8cd28/torchvision-0.26.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a06d4772a8e13e772906ed736cc53ec6639e5e60554f8e5fa6ca165aabebc464", size = 1863503, upload-time = "2026-03-23T18:13:01.384Z" },
{ url = "https://files.pythonhosted.org/packages/e4/74/11fee109841e80ad14e5ca2d80bff6b10eb11b7838ff06f35bfeaa9f7251/torchvision-0.26.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:2adfbe438473236191ff077a4a9a0c767436879c89628aa97137e959b0c11a94", size = 7766423, upload-time = "2026-03-23T18:12:56.049Z" },
{ url = "https://files.pythonhosted.org/packages/5e/00/24d8c7845c3f270153fb81395a5135b2778e2538e81d14c6aea5106c689c/torchvision-0.26.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:b6f9ad1ecc0eab52647298b379ee9426845f8903703e6127973f8f3d049a798b", size = 7518249, upload-time = "2026-03-23T18:12:51.743Z" },
{ url = "https://files.pythonhosted.org/packages/d7/ed/e53cd7c0da7ae002e5e929c1796ebbe7ec0c700c29f7a0a6696497fb3d8b/torchvision-0.26.0-cp310-cp310-win_amd64.whl", hash = "sha256:f13f12b3791a266de2d599cb8162925261622a037d87fc03132848343cf68f75", size = 3669784, upload-time = "2026-03-23T18:12:49.949Z" },
{ url = "https://files.pythonhosted.org/packages/b4/bd/d552a2521bade3295b2c6e7a4a0d1022261cab7ca7011f4e2a330dbb3caa/torchvision-0.26.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:55bd6ad4ae77be01ba67a410b05b51f53b0d0ee45f146eb6a0dfb9007e70ab3c", size = 1863499, upload-time = "2026-03-23T18:12:58.696Z" },
{ url = "https://files.pythonhosted.org/packages/33/bf/21b899792b08cae7a298551c68398a79e333697479ed311b3b067aab4bdc/torchvision-0.26.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:1c55dc8affbcc0eb2060fbabbe996ae9e5839b24bb6419777f17848945a411b1", size = 7767527, upload-time = "2026-03-23T18:12:44.348Z" },
{ url = "https://files.pythonhosted.org/packages/9a/45/57bbf9e216850d065e66dd31a50f57424b607f1d878ab8956e56a1f4e36b/torchvision-0.26.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:fd10b5f994c210f4f6d6761cf686f82d748554adf486cb0979770c3252868c8f", size = 7519925, upload-time = "2026-03-23T18:12:53.283Z" },
{ url = "https://files.pythonhosted.org/packages/10/58/ed8f7754299f3e91d6414b6dc09f62b3fa7c6e5d63dfe48d69ab81498a37/torchvision-0.26.0-cp311-cp311-win_amd64.whl", hash = "sha256:de6424b12887ad884f39a0ee446994ae3cd3b6a00a9cafe1bead85a031132af0", size = 3983834, upload-time = "2026-03-23T18:13:00.224Z" },
{ url = "https://files.pythonhosted.org/packages/ae/e7/56b47cc3b132aea90ccce22bcb8975dec688b002150012acc842846039d0/torchvision-0.26.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c409e1c3fdebec7a3834465086dbda8bf7680eff79abf7fd2f10c6b59520a7a4", size = 1863502, upload-time = "2026-03-23T18:12:57.326Z" },
{ url = "https://files.pythonhosted.org/packages/f4/ec/5c31c92c08b65662fe9604a4067ae8232582805949f11ddc042cebe818ed/torchvision-0.26.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:406557718e62fdf10f5706e88d8a5ec000f872da913bf629aab9297622585547", size = 7767944, upload-time = "2026-03-23T18:12:42.805Z" },
{ url = "https://files.pythonhosted.org/packages/f5/d8/cb6ccda1a1f35a6597645818641701207b3e8e13553e75fce5d86bac74b2/torchvision-0.26.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:d61a5abb6b42a0c0c311996c2ac4b83a94418a97182c83b055a2a4ae985e05aa", size = 7522205, upload-time = "2026-03-23T18:12:54.654Z" },
{ url = "https://files.pythonhosted.org/packages/1c/a9/c272623a0f735c35f0f6cd6dc74784d4f970e800cf063bb76687895a2ab9/torchvision-0.26.0-cp312-cp312-win_amd64.whl", hash = "sha256:7993c01648e7c61d191b018e84d38fe0825c8fcb2720cd0f37caf7ba14404aa1", size = 4255155, upload-time = "2026-03-23T18:12:32.652Z" },
{ url = "https://files.pythonhosted.org/packages/da/80/0762f77f53605d10c9477be39bb47722cc8e383bbbc2531471ce0e396c07/torchvision-0.26.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:5d63dd43162691258b1b3529b9041bac7d54caa37eae0925f997108268cbf7c4", size = 1860809, upload-time = "2026-03-23T18:12:47.629Z" },
{ url = "https://files.pythonhosted.org/packages/e6/81/0b3e58d1478c660a5af4268713486b2df7203f35abd9195fea87348a5178/torchvision-0.26.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a39c7a26538c41fda453f9a9692b5ff9b35a5437db1d94f3027f6f509c160eac", size = 7727494, upload-time = "2026-03-23T18:12:46.062Z" },
{ url = "https://files.pythonhosted.org/packages/b6/dc/d9ab5d29115aa05e12e30f1397a3eeae1d88a511241dc3bce48dc4342675/torchvision-0.26.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:b7e6213620bbf97742e5f79832f9e9d769e6cf0f744c5b53dad80b76db633691", size = 7521747, upload-time = "2026-03-23T18:12:36.815Z" },
{ url = "https://files.pythonhosted.org/packages/a9/1b/f1bc86a918c5f6feab1eeff11982e2060f4704332e96185463d27855bdf5/torchvision-0.26.0-cp313-cp313-win_amd64.whl", hash = "sha256:4280c35ec8cba1fcc8294fb87e136924708726864c379e4c54494797d86bc474", size = 4319880, upload-time = "2026-03-23T18:12:38.168Z" },
{ url = "https://files.pythonhosted.org/packages/66/28/b4ad0a723ed95b003454caffcc41894b34bd8379df340848cae2c33871de/torchvision-0.26.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:358fc4726d0c08615b6d83b3149854f11efb2a564ed1acb6fce882e151412d23", size = 1951973, upload-time = "2026-03-23T18:12:48.781Z" },
{ url = "https://files.pythonhosted.org/packages/71/e2/7a89096e6cf2f3336353b5338ba925e0addf9d8601920340e6bdf47e8eb3/torchvision-0.26.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:3daf9cc149cf3cdcbd4df9c59dae69ffca86c6823250442c3bbfd63fc2e26c61", size = 7728679, upload-time = "2026-03-23T18:12:26.196Z" },
{ url = "https://files.pythonhosted.org/packages/69/1d/4e1eebc17d18ce080a11dcf3df3f8f717f0efdfa00983f06e8ba79259f61/torchvision-0.26.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:82c3965eca27e86a316e31e4c3e5a16d353e0bcbe0ef8efa2e66502c54493c4b", size = 7609138, upload-time = "2026-03-23T18:12:35.327Z" },
{ url = "https://files.pythonhosted.org/packages/f3/a4/f1155e943ae5b32400d7000adc81c79bb0392b16ceb33bcf13e02e48cced/torchvision-0.26.0-cp313-cp313t-win_amd64.whl", hash = "sha256:ebc043cc5a4f0bf22e7680806dbba37ffb19e70f6953bbb44ed1a90aeb5c9bea", size = 4248202, upload-time = "2026-03-23T18:12:41.423Z" },
{ url = "https://files.pythonhosted.org/packages/b4/df/1ba039ad6cfe6e69209c36766b9b6e8c6fe92481c6d4e4ca52296f5f699d/torchvision-0.28.0-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:2a1ef4b6f4bf5828b48cfad97372c8982db906830884b2868ba5c3df937a7d81", size = 1856019, upload-time = "2026-07-08T16:07:59.283Z" },
{ url = "https://files.pythonhosted.org/packages/88/ea/5c70ecf86f8e95174a85061cea78683a7bb7f422f09c3f3d4f30b7600fa9/torchvision-0.28.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:546fd85345cf8652f6cd099d4f9884b0ca5c2f3fae78689a21dd2f35ea6b622f", size = 7838211, upload-time = "2026-07-08T16:07:27.023Z" },
{ url = "https://files.pythonhosted.org/packages/46/22/2f7ff1997d793e45d85fafa8374ee25348b7dae9ac521ba8751d7e1c75d5/torchvision-0.28.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:6dfb0f45e2b4ceb4e76f158c3fbb5f44387099f3c466e3423a09ab665a194aba", size = 7669419, upload-time = "2026-07-08T16:07:41.648Z" },
{ url = "https://files.pythonhosted.org/packages/42/d0/2b3c30834ff23acd3854d0ff59bc580711f4b36d725de40105a852ed3719/torchvision-0.28.0-cp310-cp310-win_amd64.whl", hash = "sha256:7fad44dc9582570c7d92c4487d36ac46998f40cc39b438e8b8f5111a935ce4e8", size = 3500355, upload-time = "2026-07-08T16:07:56.865Z" },
{ url = "https://files.pythonhosted.org/packages/7a/b2/1e010052079e4c577007b789db336ea7075f1a426e84d17121fbc3745516/torchvision-0.28.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:83fe6c020866a85acd7d97deccc45ff11d66daf42916d04396a4309c66c0ccb8", size = 1856017, upload-time = "2026-07-08T16:07:55.533Z" },
{ url = "https://files.pythonhosted.org/packages/27/be/1b9c5de9c655ca2df4a74100fa671a7b848532ff787e077ccde14a7dea2a/torchvision-0.28.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:5a38bc6da3d72621be003400b66f66a2b4c6d644fde05f680c2cb7ca8cf8dd6c", size = 7841822, upload-time = "2026-07-08T16:07:49.207Z" },
{ url = "https://files.pythonhosted.org/packages/0b/9b/f1e68e861d4462e3e195a642c2b448e7b7d3fad5f209487162b9a2133d9b/torchvision-0.28.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:7e80f543b22503d9415e126db5f0ff3917036925e38560ee6b9ae38c571a4002", size = 7670718, upload-time = "2026-07-08T16:07:46.525Z" },
{ url = "https://files.pythonhosted.org/packages/f5/de/1494610ff54cbb154beb55033cc2cd50f3de04dac132fa2dd00e4f2b2556/torchvision-0.28.0-cp311-cp311-win_amd64.whl", hash = "sha256:9a45ea67235d965ef52187130d20002a4de20c54ea3d927a24286961d268dc37", size = 3814319, upload-time = "2026-07-08T16:07:37.153Z" },
{ url = "https://files.pythonhosted.org/packages/15/49/c1cab1ecbb3ff1a380a3f99283db1dee61b8afe354f6352c643b65937130/torchvision-0.28.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:e9f54c30cd52e3ef7fd034cc69b7bb7e0964e1c8f8743e018ab92e95b40f9eee", size = 1856020, upload-time = "2026-07-08T16:07:52.182Z" },
{ url = "https://files.pythonhosted.org/packages/f0/4c/95233776e2def960e5abb7a07931230a545f43717a56a1e1140162033598/torchvision-0.28.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:5cf78ebc401ce64ae19b8c55de866bb836797d559a4de9c25ccbe74cfa642d3a", size = 7842127, upload-time = "2026-07-08T16:07:53.446Z" },
{ url = "https://files.pythonhosted.org/packages/93/e4/e9b2495d0d57b9f60d63c57d0a910410a81b4b073bf70917bef815291119/torchvision-0.28.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:028a3d481b37d785605620d7cdad897064c5a55bae2aa1f2658766333e291940", size = 7675040, upload-time = "2026-07-08T16:07:58.017Z" },
{ url = "https://files.pythonhosted.org/packages/7c/9c/55ed9cb6dfe3ee9c837df5cd0e758372e5829aa38b8dd71343aa632cc4e2/torchvision-0.28.0-cp312-cp312-win_amd64.whl", hash = "sha256:87dc16b2df427c1318ad335f1e2be2b3b15b2cf20f7934c83b0505a48425ee5d", size = 4085785, upload-time = "2026-07-08T16:07:50.928Z" },
{ url = "https://files.pythonhosted.org/packages/20/55/08a726c14c67b37c8aca04b077766909f1c7ed23f76116884fe63b9bd033/torchvision-0.28.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:d483b4aa3f5237569053f749cd1a2b5bb548ca456e40461a5dd087f21149d123", size = 1856021, upload-time = "2026-07-08T16:07:45.386Z" },
{ url = "https://files.pythonhosted.org/packages/db/8f/40beacd53809194f5259e590d1afaeaa8ad57da15f77c646e6560bcc4616/torchvision-0.28.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:bb6dd6918460ed89cc7644adcc2402991474d6933cf1ce92b390641cb233fddf", size = 7797014, upload-time = "2026-07-08T16:07:43.04Z" },
{ url = "https://files.pythonhosted.org/packages/32/db/062cdb5a84380a60439775311fff34d89229760d2a50680393dc18699956/torchvision-0.28.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:ad7b3a439265cc3739a4ab5b4c998c0e38ea99c0ee7ca4dea35c5d0b099ec237", size = 7674669, upload-time = "2026-07-08T16:07:38.91Z" },
{ url = "https://files.pythonhosted.org/packages/f3/a6/b4081e2d04e1541abf82785ac9e5178a494c19330391f551356c8c18b7b3/torchvision-0.28.0-cp313-cp313-win_amd64.whl", hash = "sha256:7e9dd6f60d6e15f8dc27d4f877fdb6002fc70d70272412135f1c2ff9cfa08d3b", size = 4157380, upload-time = "2026-07-08T16:07:40.22Z" },
]
[[package]]
@@ -1717,7 +1708,7 @@ wheels = [
[[package]]
name = "transformers"
version = "5.6.2"
version = "5.14.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "huggingface-hub" },
@@ -1731,26 +1722,24 @@ dependencies = [
{ name = "tqdm" },
{ name = "typer" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a4/e9/c6c80a07690142a7d05444271f47b9f3c8aac7dea01d52e1137ee480ad78/transformers-5.6.2.tar.gz", hash = "sha256:e657134c3e5a6bc00a3c35f4e2674bb51adfcd89898495b788a18552bac2b91a", size = 8311867, upload-time = "2026-04-23T18:33:29.332Z" }
sdist = { url = "https://files.pythonhosted.org/packages/5a/fb/2a2ba88f325e68a921d8b69ff63b477830b2e73ade9a3c8c8cab2f06d741/transformers-5.14.1.tar.gz", hash = "sha256:60d196c27781eacf8637e2b533f517582907ad6f9ae142046d6b69431a5b2173", size = 9295927, upload-time = "2026-07-16T09:41:57.773Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5d/95/0b0218149b0d6f14df35f5b8f676fa83df4f19ed253c3cc447107ef86eca/transformers-5.6.2-py3-none-any.whl", hash = "sha256:f8d3a1bb96778fed9b8aabfd0dd6e19843e4b0f2bb6b59f32b8a92051b0f348f", size = 10364898, upload-time = "2026-04-23T18:33:26.081Z" },
{ url = "https://files.pythonhosted.org/packages/6f/67/8d85ca2323233ae3c0365a659c4e52ee1f587b440e4bc577e7d8e4416d0f/transformers-5.14.1-py3-none-any.whl", hash = "sha256:9db974c4079ede2d1a3ea7ca5a240df33f2cc26fc2b36ba64c5f2a4f43b6e725", size = 11625234, upload-time = "2026-07-16T09:41:54.143Z" },
]
[[package]]
name = "triton"
version = "3.6.0"
version = "3.7.1"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/44/ba/b1b04f4b291a3205d95ebd24465de0e5bf010a2df27a4e58a9b5f039d8f2/triton-3.6.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6c723cfb12f6842a0ae94ac307dba7e7a44741d720a40cf0e270ed4a4e3be781", size = 175972180, upload-time = "2026-01-20T16:15:53.664Z" },
{ url = "https://files.pythonhosted.org/packages/8c/f7/f1c9d3424ab199ac53c2da567b859bcddbb9c9e7154805119f8bd95ec36f/triton-3.6.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a6550fae429e0667e397e5de64b332d1e5695b73650ee75a6146e2e902770bea", size = 188105201, upload-time = "2026-01-20T16:00:29.272Z" },
{ url = "https://files.pythonhosted.org/packages/0f/2c/96f92f3c60387e14cc45aed49487f3486f89ea27106c1b1376913c62abe4/triton-3.6.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49df5ef37379c0c2b5c0012286f80174fcf0e073e5ade1ca9a86c36814553651", size = 176081190, upload-time = "2026-01-20T16:16:00.523Z" },
{ url = "https://files.pythonhosted.org/packages/e0/12/b05ba554d2c623bffa59922b94b0775673de251f468a9609bc9e45de95e9/triton-3.6.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e8e323d608e3a9bfcc2d9efcc90ceefb764a82b99dea12a86d643c72539ad5d3", size = 188214640, upload-time = "2026-01-20T16:00:35.869Z" },
{ url = "https://files.pythonhosted.org/packages/17/5d/08201db32823bdf77a0e2b9039540080b2e5c23a20706ddba942924ebcd6/triton-3.6.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:374f52c11a711fd062b4bfbb201fd9ac0a5febd28a96fb41b4a0f51dde3157f4", size = 176128243, upload-time = "2026-01-20T16:16:07.857Z" },
{ url = "https://files.pythonhosted.org/packages/ab/a8/cdf8b3e4c98132f965f88c2313a4b493266832ad47fb52f23d14d4f86bb5/triton-3.6.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74caf5e34b66d9f3a429af689c1c7128daba1d8208df60e81106b115c00d6fca", size = 188266850, upload-time = "2026-01-20T16:00:43.041Z" },
{ url = "https://files.pythonhosted.org/packages/3c/12/34d71b350e89a204c2c7777a9bba0dcf2f19a5bfdd70b57c4dbc5ffd7154/triton-3.6.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:448e02fe6dc898e9e5aa89cf0ee5c371e99df5aa5e8ad976a80b93334f3494fd", size = 176133521, upload-time = "2026-01-20T16:16:13.321Z" },
{ url = "https://files.pythonhosted.org/packages/f9/0b/37d991d8c130ce81a8728ae3c25b6e60935838e9be1b58791f5997b24a54/triton-3.6.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:10c7f76c6e72d2ef08df639e3d0d30729112f47a56b0c81672edc05ee5116ac9", size = 188289450, upload-time = "2026-01-20T16:00:49.136Z" },
{ url = "https://files.pythonhosted.org/packages/ce/4e/41b0c8033b503fd3cfcd12392cdd256945026a91ff02452bef40ec34bee7/triton-3.6.0-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1722e172d34e32abc3eb7711d0025bb69d7959ebea84e3b7f7a341cd7ed694d6", size = 176276087, upload-time = "2026-01-20T16:16:18.989Z" },
{ url = "https://files.pythonhosted.org/packages/35/f8/9c66bfc55361ec6d0e4040a0337fb5924ceb23de4648b8a81ae9d33b2b38/triton-3.6.0-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d002e07d7180fd65e622134fbd980c9a3d4211fb85224b56a0a0efbd422ab72f", size = 188400296, upload-time = "2026-01-20T16:00:56.042Z" },
{ url = "https://files.pythonhosted.org/packages/ec/ea/629cc37436ca5df93ce98956d09cd2ca1498bfee8ef4972d2fe48b9f958c/triton-3.7.1-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3daf64305d6cea88d3334c65ebc9bcd0c64c9564a977084366aa768d57cbcf64", size = 184551013, upload-time = "2026-06-17T20:03:37.551Z" },
{ url = "https://files.pythonhosted.org/packages/15/76/c79c34311625227a288df3e483fc5cdf3d596624cbd4b4758c4cbdc14af3/triton-3.7.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee89fbf782ec2ad50391dd1cf26cbea4f4467154c37f4773026da8fc31c0f58e", size = 197596267, upload-time = "2026-06-17T19:53:06.898Z" },
{ url = "https://files.pythonhosted.org/packages/7b/f9/19d842d06a08559534fa1eaab6ca551b1bcf40f06620bddec1babaa2772d/triton-3.7.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4a0e1cd4c4a76370ed74a8432a53cea28716827d19e40ffc732233e35ceb3f6", size = 184664887, upload-time = "2026-06-17T20:03:42.913Z" },
{ url = "https://files.pythonhosted.org/packages/cd/5e/fce69606f7f240297f163e25539906732b199530d486ce67ae319877e821/triton-3.7.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6744957e9fd610a29680ec2346057d0c86948ed3812468670719f391e94b44a5", size = 197701306, upload-time = "2026-06-17T19:53:13.673Z" },
{ url = "https://files.pythonhosted.org/packages/94/fa/f856e24deb462d5f18bd4b5a746957862ab9b6ee5834bda60605ec348366/triton-3.7.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9497f2e696ee368862a181a90b2dcc03ca978cc4f602abd67c7d81022a6988e1", size = 184692359, upload-time = "2026-06-17T20:03:48.288Z" },
{ url = "https://files.pythonhosted.org/packages/c4/6f/fb96d15db6f36d6eae4cafb998c2e0353bf59d7c4ea1662d7497f269134a/triton-3.7.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7e40869937a68206ec70d7f25bb7ec6433cb083f9135e1f36dbd318dc449a728", size = 197719725, upload-time = "2026-06-17T19:53:20.419Z" },
{ url = "https://files.pythonhosted.org/packages/00/42/c5089d4d9327fcd1e862c599cc2927f39418f84dd11a84cb2ccff9d4787a/triton-3.7.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cdbfc09d9ec58bc5e68321525653220de7515c199e7a8097a97c85e62b52cd0a", size = 184694629, upload-time = "2026-06-17T20:03:53.444Z" },
{ url = "https://files.pythonhosted.org/packages/07/42/2c3ac59253ae8892b6f307875263dd23dc875cdf732d3aea40d6d41fb7cb/triton-3.7.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:58c0e131da05134a2a4788ccbcc0c1105cf0f54c8e98f19e34cd465396dc15eb", size = 197729241, upload-time = "2026-06-17T19:53:27.801Z" },
]
[[package]]