Compare commits

...
Author SHA1 Message Date
minh hoangandGitHub 1933293372 Merge pull request #90 from PrimeIntellect-ai/fix/unsloth-llama-tokenizer
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
fix: use ungated llama tokenizer mirrors
2026-06-18 18:46:32 -07:00
eexwhyzee 0dc19a060e Classify canonical Llama as preserve-thinking no-op 2026-06-18 16:22:01 -07:00
eexwhyzee fe1dcdaed7 Format tokenizer alias test 2026-06-18 16:20:02 -07:00
eexwhyzee 20d89be418 Use ungated Llama tokenizer mirrors 2026-06-18 16:05:01 -07:00
Matej SirovatkaandGitHub 67568f79cf fix: _get_offset_tokenizer immune to global fastokens patch (concurrent-pool race) (#86)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-15 01:22:27 +02:00
halleriteandGitHub a3bf7e88b4 fix(nemotron3): faithful Nano/Super/Ultra rendering + per-variant config split (#84)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-12 11:01:40 -07:00
halleriteandGitHub d80f36e287 feat(deepseek): split into separate DeepSeek-V3 and DeepSeek-R1 renderers (#81)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-09 17:03:22 -07:00
1dca3b9a2d fix(parsing): don't parse in-<think> tool calls as real calls (#78) (#80)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
* fix(parsing): don't parse in-<think> tool calls as real calls

Reasoning models (Qwen3-*-Thinking, Kimi-K2.5, R1-distill via the
DeepSeek-V3 renderer) routinely draft tool-call syntax *inside* their
<think>...</think> trace while planning. The qwen3, deepseek_v3, and
kimi_k2.5 parsers scanned the whole completion for tool-call delimiters
and only extracted reasoning afterward, so those in-think drafts were
mis-parsed. Symptoms differed by format but all corrupt the tool result:

- qwen3 / qwen3_vl: emits the draft *and* the real call -> phantom
  duplicate (the reported #78 case; same code executed twice).
- kimi_k2.5: the in-think section trips the "truncated reasoning" guard
  and *all* tool calls are dropped (returns zero).
- deepseek_v3: returns the *wrong* call (the draft) and loses reasoning.

Fix: extract reasoning first, then scan for tool calls only in the
post-</think> region — mirroring vLLM's DelegatingParser (reasoning
parser runs before the tool parser). Where </think> is a single special
token (Qwen3) we anchor on its id; where it's multi-token / context-
sensitive text (DeepSeek-V3, Kimi-K2.5) we locate the boundary by
decoding. content_ids still starts at 0 so reasoning extraction is
unchanged, and genuine parallel calls after </think> are preserved.

Audited all parsers: qwen3.5/glm/minimax/laguna/nemotron3 already strip
reasoning first; gpt_oss (channel-segregated) and llama_3 (no reasoning)
are safe; kimi_k2 (K2-Instruct) has no thinking path so is unaffected.

Validated against real Qwen3, Kimi-K2.5 and DeepSeek-V3 tokenizers.

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

* style: ruff format

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 00:26:25 +02:00
halleriteandGitHub e6dba5ad6c feat: add Llama-3 renderer for Llama-3.2-1B/3B-Instruct (#9)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-08 19:47:06 +02:00
halleriteandGitHub 596c15ffd9 feat(nemotron3): add Nemotron-3 Ultra chat-template variant (#77)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-06-04 16:46:36 +02:00
Kemal ErdemandGitHub 942449c37a Merge pull request #76 from PrimeIntellect-ai/security/cooldown-7d
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
security: extend cooldown exempt list with prime-pydantic-config
2026-05-31 00:30:01 +02:00
Kemal ErdemandClaude Opus 4.7 9f3b24c0ac chore(security): extend cooldown exempt list with prime-pydantic-config
renderers already had exclude-newer = "7 days" with a per-package
exemption for fastokens. This PR splits the inline table into a
[tool.uv.exclude-newer-package] section and adds the only other
PrimeIntellect-published package in renderers' dep closure:
prime-pydantic-config.

Only packages in this project's `uv tree` are exempted — the resolver
ignores entries for packages it never sees.

Pins `required-version = ">=0.11.1"` so older uvs fail loudly instead
of silently parsing "7 days" as an RFC 3339 date and proceeding
*without* the cooldown — see uv#17908.

Part 1 of 3 in a coordinated supply-chain hardening across PI repos.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 22:30:23 +02:00
halleriteandGitHub 35c2407e92 fix(tokenizer): apply config-build fallback to offset tokenizer too (#75)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-28 20:58:02 +02:00
Sebastian MüllerandGitHub a11f8d8193 feat(base): add message_tool_names field for per-message tool attribution (#74)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-28 20:49:47 +02:00
halleriteandGitHub 89ab3f0bed fix(tokenizer): fall back to direct fast-tokenizer load when model config build fails (#72)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-28 00:19:19 +02:00
halleriteandGitHub e729baa5af refactor(qwen3.5): hard-code enable_thinking default per model (#71)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-27 19:54:58 +02:00
halleriteandGitHub 74425da166 fix(examples): update multi-turn examples to current renderer API (#68)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-27 19:07:11 +02:00
halleriteandGitHub 1569dc980d fix(deps): lower openai-harmony floor to >=0.0.4 for SGLang compatibility (#69)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-27 19:01:20 +02:00
halleriteandGitHub 1d69232253 feat(glm): make next-message role marker trainable after assistant turns (#66)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-26 22:56:24 +02:00
halleriteandGitHub 88aa42d40f fix(nemotron3): forward tools to parse_qwen35 for schema-aware coercion (#65)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-26 16:52:50 +02:00
eligottsandGitHub 647335489d fix(parsing): accept bare-string args for union schemas with string (#63)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-26 15:59:43 +02:00
halleriteandGitHub 2ec28a8543 Lazy-load concrete renderer classes via PEP 562 __getattr__ (#64)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-26 01:51:14 +02:00
c86c50b72e Typed renderer configs (#60)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
Co-authored-by: hallerite <git@hallerite.com>
2026-05-26 00:07:01 +02:00
halleriteandGitHub 1831bcc50c fix(base): suppress fastokens per-load print, log once instead (#61)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-24 13:29:35 +02:00
3ae276c446 ci: auto-publish dev release to PyPI on every commit to main (#58)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
Adds .github/workflows/publish-dev.yml which, on every push to main, tags
the commit as ``renderers-v<next-patch>.dev<commits-since-release>`` and
publishes the resulting wheel to PyPI as a pre-release. Build runs from
the freshly-created tag so hatch-vcs produces a clean PEP 440 version
without the ``+gHASH`` local segment PyPI rejects.

Mirrors the build/publish split from publish.yml so OIDC stays scoped to
the publish job only.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 11:19:14 -07:00
Sebastian MüllerandGitHub 1691f87e90 feat(base): per-token is_content mask for body/scaffold attribution (#53) 2026-05-20 16:42:24 +02:00
Zafir StojanovskiandGitHub 9e11214dd5 fix(kimi_k25): emit JSON literals for bool/null in tool schema rendering (#55) 2026-05-20 15:09:19 +02:00
dependabot[bot]andGitHub 143ffdee56 build(deps): bump idna from 3.13 to 3.15 (#56) 2026-05-20 13:59:13 +02:00
halleriteandGitHub f9414b1e95 chore(deps): bump fastokens to 0.2.0, drop MiniMax-M2 from denylist (#57) 2026-05-20 13:54:05 +02:00
will brownandGitHub ee9703fcc9 Merge pull request #54 from PrimeIntellect-ai/fix/routed-experts-sidecar-parse
Handle routed experts as response sidecar
2026-05-19 21:15:42 -05:00
S1ro1 3177399b79 Handle routed experts as response sidecar 2026-05-19 21:49:28 +05:30
halleriteandGitHub 8704f9d502 feat(map): add Qwen3-30B-A3B-{Instruct,Thinking}-2507, GLM-5-FP8 (#50)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-18 19:47:42 +02:00
halleriteandGitHub fdc03f2861 feat(client): pre-flight overflow check with auto-discovery (#48) 2026-05-18 18:33:28 +02:00
eligottsandGitHub d547eef54c fix(client): add Qwen35Renderer to _build_mm_features dispatch (#45) 2026-05-18 12:11:01 +02:00
eligottsandGitHub 25ba413d46 fix(qwen3_vl): require truthy value in untyped image_part fallback (#46) 2026-05-18 12:09:58 +02:00
halleriteandGitHub 17d0584f87 feat(base): per-message / per-role analytics on RenderedTokens (#38)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-16 14:08:10 +02:00
58 changed files with 9905 additions and 1587 deletions
+104
View File
@@ -0,0 +1,104 @@
name: Publish Dev
# Tag every commit on main as ``renderers-v<next>.dev<N>`` and publish the
# wheel to PyPI as a pre-release. ``<next>`` is the latest release tag with
# its patch bumped; ``<N>`` is the number of commits since that release so
# each main commit maps to a unique PEP 440 dev version.
#
# Building from the freshly-created tag means hatch-vcs resolves the version
# cleanly (no ``+gHASH`` local segment), which PyPI requires.
on:
push:
branches: [main]
concurrency:
group: publish-dev-${{ github.ref }}
cancel-in-progress: false
jobs:
tag:
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
tag: ${{ steps.compute.outputs.tag }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Compute next dev tag
id: compute
run: |
set -euo pipefail
LATEST_RELEASE=$(git tag --list 'renderers-v*' --sort=-v:refname \
| grep -Ev '(dev|rc|a[0-9]|b[0-9])' \
| head -1)
if [ -z "$LATEST_RELEASE" ]; then
echo "No release tag matching 'renderers-v<MAJOR.MINOR.PATCH>' found" >&2
exit 1
fi
BASE=${LATEST_RELEASE#renderers-v}
MAJOR=$(echo "$BASE" | cut -d. -f1)
MINOR=$(echo "$BASE" | cut -d. -f2)
PATCH=$(echo "$BASE" | cut -d. -f3)
NEXT="${MAJOR}.${MINOR}.$((PATCH + 1))"
N=$(git rev-list --count "${LATEST_RELEASE}..HEAD")
TAG="renderers-v${NEXT}.dev${N}"
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "Computed tag: ${TAG} (base=${LATEST_RELEASE}, commits=${N})"
- name: Create and push tag
env:
TAG: ${{ steps.compute.outputs.tag }}
run: |
set -euo pipefail
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
echo "Tag ${TAG} already exists on origin — nothing to do" >&2
exit 0
fi
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git tag -a "$TAG" -m "Automated dev release ${TAG}"
git push origin "$TAG"
build:
needs: tag
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
ref: refs/tags/${{ needs.tag.outputs.tag }}
- uses: astral-sh/setup-uv@v7
- name: Build renderers
run: uv build
- name: Upload dist artifacts
uses: actions/upload-artifact@v4
with:
name: dist-dev
path: dist/
if-no-files-found: error
retention-days: 7
publish:
needs: build
runs-on: ubuntu-latest
environment: pypi-prod
permissions:
id-token: write
steps:
- name: Download dist artifacts
uses: actions/download-artifact@v4
with:
name: dist-dev
path: dist/
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
+3
View File
@@ -31,3 +31,6 @@ coverage.xml
.idea/
.vscode/
*.swp
# agent harness state
.claude/
+39 -14
View File
@@ -17,7 +17,7 @@ from transformers import AutoTokenizer
from renderers import create_renderer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
r = create_renderer(tok, renderer="auto") # → Qwen3Renderer
r = create_renderer(tok) # → Qwen3Renderer (auto-resolved)
prompt_ids = r.render_ids(
[{"role": "user", "content": "hi"}],
@@ -40,7 +40,7 @@ next_prompt_ids = r.bridge_to_next_turn(
)
```
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `nemotron-3-ultra`, `gpt-oss`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
## API
@@ -71,17 +71,17 @@ Each hand-coded bridge:
### Picking a renderer
```python
r = create_renderer(tok, renderer="auto")
r = create_renderer(tok) # AutoRendererConfig is the implicit default
```
Auto-detect matches `tokenizer.name_or_path` against `MODEL_RENDERER_MAP` by **exact match**. Prefix matching is intentionally off — same architecture can ship different chat templates (base vs instruct, fine-tune renames). Fine-tunes must pass `renderer=<name>` explicitly; unknown names fall back to `DefaultRenderer`.
Auto-detect matches `tokenizer.name_or_path` against `MODEL_RENDERER_MAP` by **exact match**. Prefix matching is intentionally off — same architecture can ship different chat templates (base vs instruct, fine-tune renames). Fine-tunes must pass an explicit typed config (e.g. `Qwen3RendererConfig()`); unknown names fall back to `DefaultRenderer`.
### Pools
```python
from renderers import create_renderer_pool
pool = create_renderer_pool("Qwen/Qwen3-8B", renderer="auto", size=16)
pool = create_renderer_pool("Qwen/Qwen3-8B", size=16)
with pool.checkout() as r:
ids = r.render_ids(messages)
```
@@ -108,25 +108,50 @@ Empirical delta on Qwen3.5-35B-A3B + mini-swe-agent-plus, step 0:
Each break fragments a rollout into multiple training samples — every fragment re-encodes its prefix, inflating compute roughly linearly with the number of breaks.
## Compaction overrides
## Typed renderer configs
`create_renderer` and `create_renderer_pool` accept two constructor-only flags:
Each renderer accepts a typed pydantic config that pins its template-control kwargs at construction. `create_renderer` and `create_renderer_pool` take one positional `config` argument:
```python
preserve_all_thinking: bool = False
preserve_thinking_between_tool_calls: bool = False
from renderers import (
create_renderer,
AutoRendererConfig,
Qwen3RendererConfig,
GLM5RendererConfig,
DefaultRendererConfig,
)
# Auto-resolve renderer from the tokenizer's model name. Carries the
# shared preserve_* flags; template kwargs require an explicit choice.
renderer = create_renderer(tokenizer)
renderer = create_renderer(tokenizer, AutoRendererConfig(preserve_all_thinking=True))
# Explicit choice — the typed config exposes exactly the fields that
# renderer's chat template honours.
renderer = create_renderer(tokenizer, Qwen3RendererConfig(enable_thinking=False))
renderer = create_renderer(tokenizer, GLM5RendererConfig(clear_thinking=False))
# Default renderer (apply_chat_template fallback) — extra fields are
# captured via pydantic ``extra="allow"`` and forwarded to the Jinja
# template; tool / reasoning parsers are typed.
renderer = create_renderer(
tokenizer,
DefaultRendererConfig(tool_parser="qwen3", reasoning_parser="think"),
)
```
Defaults preserve byte-identity with the model's chat template. Flipping a flag at construction restores `reasoning_content` the template would otherwise drop:
Discriminated union: every per-renderer config is a variant of `RendererConfig`, dispatched on the `name` field. Bogus combinations (e.g. `add_vision_id` under `name="qwen3"`) error at construction with a `pydantic.ValidationError`. Downstream pydantic configs (prime-rl orchestrator, verifiers `ClientConfig`) hold a single field typed as `RendererConfig` and inherit the same strict-per-variant validation.
- `preserve_all_thinking=True` — every past assistant's reasoning is kept.
- `preserve_thinking_between_tool_calls=True` — reasoning is kept on assistants in the in-flight tool cycle (no-op for current renderers; reserved for future templates that drop it).
Two shared behaviour flags live on every variant via `_BaseRendererConfig`:
The canonical use case is **compaction**. Injecting a `user` turn like *"summarize the work so far"* puts every prior assistant in a "past cycle", so template-default rules drop their `reasoning_content` before the summarizer sees it. Build the renderer with `preserve_all_thinking=True` to keep reasoning visible end-to-end on those flows. Both flags only ever *add* tokens vs the template default.
- `preserve_all_thinking=True` — every past assistant's `reasoning_content` is kept, even when the chat template would drop it.
- `preserve_thinking_between_tool_calls=True` — reasoning is kept on assistants in the in-flight tool cycle (post-last-user A-T-…-A block when it contains a tool response). A new user turn closes the block and drops its thinking.
These OR-compose with template-level toggles (e.g. GLM-5 `clear_thinking`, Nemotron-3 `truncate_history_thinking`): either flag saying "keep" wins. preserve_* can only ever *extend* retention — never override a template kwarg into a "drop" decision. The canonical use case is **compaction**: injecting a `user` turn like *"summarize the work so far"* puts every prior assistant in a past cycle, and `preserve_all_thinking=True` keeps reasoning visible end-to-end.
## `DefaultRenderer`
Fallback for unsupported models. Wraps `apply_chat_template` and accepts `tool_parser` / `reasoning_parser` kwargs (vLLM convention). `bridge_to_next_turn` returns `None` because the template's close is unknown, so multi-turn rollouts fall back to full re-render. Implementing a hand-coded renderer is a few hundred lines of Python (`render_ids` + `parse_response` + `bridge_to_next_turn`) and is the only path that closes the failure modes above by construction.
Fallback for unsupported models. Wraps `apply_chat_template` and accepts `tool_parser` / `reasoning_parser` (vLLM convention) plus arbitrary Jinja kwargs via `DefaultRendererConfig`'s `extra="allow"`. `bridge_to_next_turn` returns `None` because the template's close is unknown, so multi-turn rollouts fall back to full re-render. Implementing a hand-coded renderer is a few hundred lines of Python (`render_ids` + `parse_response` + `bridge_to_next_turn`) and is the only path that closes the failure modes above by construction.
## Roadmap
+163
View File
@@ -0,0 +1,163 @@
# Renderer config
`renderers.RendererConfig` is the typed input to `create_renderer` and
`create_renderer_pool`. It pins the renderer choice and its template-control
kwargs at construction.
```python
from renderers import create_renderer, Qwen35RendererConfig
r = create_renderer(tokenizer, Qwen35RendererConfig(enable_thinking=False))
```
`RendererConfig` is a pydantic discriminated union (one variant per renderer,
dispatched on the `name` field). Selecting a variant exposes exactly the
fields that renderer's chat template honours; anything else raises a
`pydantic.ValidationError` at construction.
## Per-renderer configs
Each hand-coded renderer has a typed config class with the template kwargs
its Jinja chat template reads. For example:
| Renderer | Config class | Template fields |
|----------------|--------------------------|----------------------------------------------------------------|
| Qwen3 | `Qwen3RendererConfig` | `enable_thinking` |
| Qwen3.5 / 3.6 | `Qwen35RendererConfig` | `enable_thinking`, `add_vision_id` |
| Qwen3-VL | `Qwen3VLRendererConfig` | `add_vision_id` |
| GLM-5 / 5.1 | `GLM5RendererConfig` | `enable_thinking`, `clear_thinking` |
| GLM-4.5 | `GLM45RendererConfig` | `enable_thinking` |
| Nemotron-3 | `Nemotron3RendererConfig`| `enable_thinking`, `truncate_history_thinking` |
| Kimi K2.5 | `KimiK25RendererConfig` | `thinking` |
| MiniMax-M2 | `MiniMaxM2RendererConfig`| `model_identity` |
| Laguna-XS.2 | `LagunaXS2RendererConfig`| `enable_thinking`, `render_assistant_messages_raw` |
| gpt-oss | `GptOssRendererConfig` | `reasoning_effort`, `conversation_start_date` |
Field names mirror the upstream Jinja variable names. Passing
`Qwen3RendererConfig(add_vision_id=True)` raises — Qwen3 is text-only, so
the field doesn't exist on its config. Use
`type(config).template_field_names()` to introspect the fields that mirror
chat-template kwargs (parity is verified against `apply_chat_template` in
`tests/test_renderer_config_parity.py`).
Configs are frozen. To override a field, construct a new instance or call
`config.model_copy(update={...})`.
## Auto-resolution
`create_renderer(tokenizer)` (no config) resolves the renderer from
`tokenizer.name_or_path` via `MODEL_RENDERER_MAP`:
```python
r = create_renderer(tokenizer) # AutoRendererConfig() is the default
r = create_renderer(tokenizer, AutoRendererConfig(preserve_all_thinking=True))
```
`AutoRendererConfig` carries only the shared `preserve_*` flags. Template
kwargs depend on the renderer, so overriding them requires naming the
renderer explicitly:
```python
r = create_renderer(tokenizer, GLM5RendererConfig(clear_thinking=False))
```
Auto-resolution fails loudly for VLMs that miss the exact-match lookup —
`DefaultRenderer` only knows `apply_chat_template` + text tokens, so silently
falling back for a VLM would produce token streams the trainer can't
reconstruct. Text-only fine-tunes without a registered renderer fall back to
`DefaultRenderer` and log the choice at INFO.
## `preserve_*` flags
Every variant carries two renderer-agnostic flags on `_BaseRendererConfig`:
- `preserve_all_thinking: bool = False` — re-emit `reasoning_content` on
every past assistant turn, even when the chat template would drop it.
- `preserve_thinking_between_tool_calls: bool = False` — re-emit
`reasoning_content` only inside the in-flight tool cycle (the contiguous
A-T-…-A block after the most recent `user` message, when it contains at
least one `tool` response). A new user turn closes the block and drops
its thinking.
These OR-compose with template-level toggles. GLM-5's `clear_thinking` and
Nemotron-3's `truncate_history_thinking` already gate past thinking; the
`preserve_*` flags add to that:
| `clear_thinking` | `preserve_all_thinking` | past thinking? |
|------------------|-------------------------|----------------|
| `True` (default — drop) | `False` (default) | dropped |
| `True` | `True` | kept |
| `False` (keep) | `False` | kept |
| `False` | `True` | kept |
`preserve_*` can only extend retention, never force a drop. The canonical
use case is **compaction**: injecting a `user` turn like *"summarize the work
so far"* puts every prior assistant in a past cycle, and
`preserve_all_thinking=True` keeps reasoning visible end-to-end.
## `DefaultRendererConfig` accepts arbitrary Jinja kwargs
`DefaultRenderer` wraps `tokenizer.apply_chat_template` for any model that
doesn't have a hand-coded renderer. Its config sets `extra="allow"`:
```python
from renderers import create_renderer, DefaultRendererConfig
r = create_renderer(
tokenizer,
DefaultRendererConfig(
tool_parser="qwen3", # registered in renderers.parsers
reasoning_parser="think",
enable_thinking=False, # forwarded to apply_chat_template
custom_jinja_kwarg=True, # ditto
),
)
```
`tool_parser` and `reasoning_parser` are typed because they configure
`DefaultRenderer`'s own parsing pipeline. Every other field lands in
`model_extra` and `DefaultRenderer._apply` forwards `model_extra` verbatim
to `apply_chat_template`.
## Downstream integration
Downstream pydantic configs (`prime-rl` orchestrator, `verifiers`
`ClientConfig`) hold a single field typed as `RendererConfig`:
```python
from pydantic import BaseModel, Field
from renderers import AutoRendererConfig, RendererConfig
class ClientConfig(BaseModel):
renderer: RendererConfig = Field(default_factory=AutoRendererConfig)
```
In TOML / YAML, the discriminator routes deserialization:
```toml
[client.renderer]
name = "qwen3.5"
enable_thinking = false
add_vision_id = true
preserve_all_thinking = true
```
Pydantic dispatches on `name = "qwen3.5"` to `Qwen35RendererConfig`. Bogus
combinations (e.g. `add_vision_id` under `name = "qwen3"`) raise at
config-load with a clear message naming the offending field and the variant
that rejected it.
To construct a config from a renderer name string (e.g. from a CLI flag):
```python
from renderers import config_from_name
cfg = config_from_name("glm-5") # → GLM5RendererConfig() with defaults
cfg = config_from_name("auto") # → None, the implicit "auto" form
```
## Renaming a renderer is a breaking change
The discriminator key is the renderer name string. Renaming `"qwen3.5"` to
something else would break any downstream config that references it by
name. Add new renderers; don't rename existing ones.
+29 -10
View File
@@ -22,6 +22,7 @@ import json
import os
import sglang as sgl
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from transformers import AutoTokenizer
@@ -52,7 +53,9 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None):
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
return Qwen35Renderer(
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
@@ -62,8 +65,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -141,21 +145,33 @@ def main() -> None:
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -167,11 +183,14 @@ def main() -> None:
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
+29 -10
View File
@@ -44,6 +44,7 @@ from typing import Any
import httpx
from renderers.base import Renderer
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from transformers import AutoTokenizer
@@ -71,7 +72,9 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None) -> Renderer:
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
return Qwen35Renderer(
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
@@ -116,8 +119,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -164,21 +168,33 @@ async def run_one(
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages: list[dict[str, Any]] = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -190,11 +206,14 @@ async def run_one(
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
+29 -10
View File
@@ -22,6 +22,7 @@ import json
import os
import tinker
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from tinker import types
@@ -53,7 +54,9 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None):
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
return Qwen35Renderer(
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
@@ -63,8 +66,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -131,21 +135,33 @@ async def main() -> None:
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -157,11 +173,14 @@ async def main() -> None:
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
@@ -26,6 +26,7 @@ import os
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
@@ -55,7 +56,8 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None):
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking), tokenizer
config = Qwen35RendererConfig(enable_thinking=enable_thinking)
return Qwen35Renderer(tokenizer, config), tokenizer
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer), tokenizer
raise ValueError(f"unsupported demo model: {model}")
@@ -65,8 +67,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -139,21 +142,33 @@ def main() -> None:
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -165,11 +180,14 @@ def main() -> None:
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
+29 -10
View File
@@ -21,6 +21,7 @@ import gc
import json
import os
from renderers.configs import Qwen35RendererConfig
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from transformers import AutoTokenizer
@@ -52,7 +53,9 @@ TOOLS = [
def make_renderer(model: str, enable_thinking: bool | None):
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
return Qwen35Renderer(
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
@@ -62,8 +65,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
for tc in parsed.tool_calls:
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
if parsed.content:
print(f"content: {parsed.content}")
@@ -134,21 +138,33 @@ def main() -> None:
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
assistant["tool_calls"] = [
{
"id": tc.id or f"call_{idx}",
"type": "function",
"function": {
"name": tc.name,
"arguments": tc.arguments
if isinstance(tc.arguments, str)
else json.dumps(tc.arguments),
},
}
for idx, tc in enumerate(parsed1.tool_calls)
]
messages.append(assistant)
if parsed1.tool_calls:
new_messages = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
tool_args = tool_call.arguments or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"tool_call_id": tool_call.id or f"call_{idx}",
"name": tool_call.name or "multiply",
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
@@ -160,11 +176,14 @@ def main() -> None:
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
# extended id stream is on ``.token_ids``.
bridged = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
if bridged is None:
raise RuntimeError("bridge_to_next_turn returned None")
bridged_ids = bridged.token_ids
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
+34 -5
View File
@@ -23,13 +23,25 @@ dependencies = [
# Used by GptOssRenderer to render and parse harmony tokens. Vendoring
# OpenAI's reference implementation keeps us byte-identical with vLLM
# (which also uses it) and saves us mirroring a 330-line Jinja template.
"openai-harmony>=0.0.8",
#
# Floor is ``>=0.0.4`` (not the latest 0.0.8) on purpose: every SGLang
# release through 0.5.12.post1 hard-pins ``openai-harmony==0.0.4``, so a
# higher floor makes ``renderers`` uninstallable alongside SGLang. The
# GptOssRenderer renders byte-identically on 0.0.4 (verified token-for-token
# against 0.0.8) and ``tests/test_gpt_oss_harmony_parity.py`` passes on it,
# so the older harmony is safe.
"openai-harmony>=0.0.4",
# Crusoe's Rust BPE tokenizer; ~10x faster encode vs HF's tokenizers.
# ``load_tokenizer`` patches it in by default for every supported model
# except a small denylist (DeepSeek-V3 family, MiniMax-M2 family). The
# patch is bracketed around ``from_pretrained``, so subsequent
# ``AutoTokenizer`` calls outside the renderers package stay vanilla.
"fastokens>=0.1.1",
# except a small denylist (DeepSeek-V3 family). The patch is bracketed
# around ``from_pretrained``, so subsequent ``AutoTokenizer`` calls
# outside the renderers package stay vanilla.
"fastokens>=0.2.0",
# ``BaseRendererConfig`` inherits from ``pydantic_config.BaseConfig`` so
# the typed-config surface stays uniform with prime-rl / verifiers config
# bases. Transitively brings pydantic, which ``renderers.configs`` also
# imports directly.
"prime-pydantic-config>=0.3.0.dev83",
]
[tool.hatch.version]
@@ -67,8 +79,25 @@ dev = [
]
[tool.uv]
# Enforce a uv version that supports the friendly-duration form
# (`"7 days"`) in the static pyproject parser. Older uvs silently parse
# the value as an RFC 3339 date, emit a TOML parse warning, and proceed
# *without* the cooldown — bypassing this security policy.
required-version = ">=0.11.1"
exclude-newer = "7 days"
[tool.uv.exclude-newer-package]
# fastokens 0.2.0 was published on 2026-05-17 and contains the
# ``unpatch_transformers`` fix (crusoecloud/fastokens#32) needed for
# MiniMax-M2's slow→fast tokenizer conversion path. Exempting it from
# the project-wide 7-day cutoff lets the lockfile pick it up immediately
# while the rest of the dependency graph stays gated.
fastokens = false
# PrimeIntellect-published packages in this project's dependency closure —
# fast-track so first-party releases can land same-day. Only packages that
# appear in `uv tree` are listed.
prime-pydantic-config = false
[tool.ty.environment]
python-version = "3.13"
+107 -17
View File
@@ -28,57 +28,144 @@ from renderers.base import (
ToolCallParseStatus,
ToolSpec,
VideoPart,
attribute_text_segments,
build_training_sample,
build_trajectory_step,
create_renderer,
create_renderer_pool,
extract_message_tool_names,
is_multimodal,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.deepseek_v3 import DeepSeekV3Renderer
from renderers.default import DefaultRenderer
from renderers.glm5 import GLM5Renderer
from renderers.glm45 import GLM45Renderer
from renderers.gpt_oss import GptOssRenderer
from renderers.kimi_k2 import KimiK2Renderer
from renderers.kimi_k25 import KimiK25Renderer
from renderers.laguna_xs2 import LagunaXS2Renderer
from renderers.minimax_m2 import MiniMaxM2Renderer
from renderers.nemotron3 import Nemotron3Renderer
from renderers.qwen3 import Qwen3Renderer
from renderers.qwen3_vl import Qwen3VLRenderer
from renderers.qwen35 import Qwen35Renderer
from renderers.qwen36 import Qwen36Renderer
from renderers.client import OverlongPromptError
from renderers.configs import (
AutoRendererConfig,
BaseRendererConfig,
config_from_name,
DefaultRendererConfig,
DeepSeekR1RendererConfig,
DeepSeekV3RendererConfig,
GLM45RendererConfig,
GLM51RendererConfig,
GLM5RendererConfig,
GptOssRendererConfig,
KimiK25RendererConfig,
KimiK2RendererConfig,
LagunaXS2RendererConfig,
Llama3RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen3RendererConfig,
Qwen3VLRendererConfig,
RendererConfig,
)
# Concrete renderer classes are lazy-loaded so that consumers needing
# only the config layer (``RendererConfig`` discriminated union) don't
# pay the ``transformers`` import cost. Each renderer module does
# ``from transformers.tokenization_utils import PreTrainedTokenizer``
# at module level, so eager imports here would drag ``transformers``
# into every downstream ``import renderers``. ``__getattr__`` (PEP 562)
# resolves the names on first attribute access, so ``from renderers
# import DefaultRenderer`` and ``renderers.DefaultRenderer`` both work
# transparently. ``create_renderer`` doesn't depend on these eager
# imports — ``renderers.base._populate_registry`` lazy-imports the
# concrete classes itself when a renderer is instantiated.
_LAZY_RENDERERS: dict[str, str] = {
"DeepSeekR1Renderer": "renderers.deepseek_r1",
"DeepSeekV3Renderer": "renderers.deepseek_v3",
"DefaultRenderer": "renderers.default",
"GLM45Renderer": "renderers.glm45",
"GLM51Renderer": "renderers.glm5",
"GLM5Renderer": "renderers.glm5",
"GptOssRenderer": "renderers.gpt_oss",
"KimiK25Renderer": "renderers.kimi_k25",
"KimiK2Renderer": "renderers.kimi_k2",
"LagunaXS2Renderer": "renderers.laguna_xs2",
"Llama3Renderer": "renderers.llama_3",
"MiniMaxM2Renderer": "renderers.minimax_m2",
"Nemotron3Renderer": "renderers.nemotron3",
"Nemotron3UltraRenderer": "renderers.nemotron3",
"Qwen35Renderer": "renderers.qwen35",
"Qwen36Renderer": "renderers.qwen36",
"Qwen3Renderer": "renderers.qwen3",
"Qwen3VLRenderer": "renderers.qwen3_vl",
}
def __getattr__(name: str):
if name in _LAZY_RENDERERS:
import importlib
module = importlib.import_module(_LAZY_RENDERERS[name])
value = getattr(module, name)
globals()[name] = value # cache for subsequent lookups
return value
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
def __dir__() -> list[str]:
return sorted(set(globals().keys()) | set(_LAZY_RENDERERS))
__all__ = [
"AutoRendererConfig",
"BaseRendererConfig",
"Content",
"ContentPart",
"DeepSeekR1Renderer",
"DeepSeekR1RendererConfig",
"DeepSeekV3Renderer",
"DeepSeekV3RendererConfig",
"DefaultRenderer",
"DefaultRendererConfig",
"GLM45Renderer",
"GLM45RendererConfig",
"GLM51Renderer",
"GLM51RendererConfig",
"GLM5Renderer",
"GLM5RendererConfig",
"GptOssRenderer",
"GptOssRendererConfig",
"ImagePart",
"KimiK2Renderer",
"KimiK25Renderer",
"KimiK25RendererConfig",
"KimiK2Renderer",
"KimiK2RendererConfig",
"LagunaXS2Renderer",
"LagunaXS2RendererConfig",
"Llama3Renderer",
"Llama3RendererConfig",
"MULTIMODAL_MODELS",
"Message",
"MiniMaxM2Renderer",
"MiniMaxM2RendererConfig",
"MultiModalData",
"MultimodalRenderer",
"Nemotron3Renderer",
"Nemotron3RendererConfig",
"Nemotron3UltraRenderer",
"Nemotron3UltraRendererConfig",
"OverlongPromptError",
"ParsedResponse",
"ParsedToolCall",
"PlaceholderRange",
"Qwen3Renderer",
"Qwen3VLRenderer",
"Qwen35Renderer",
"Qwen35RendererConfig",
"Qwen36Renderer",
"Qwen36RendererConfig",
"Qwen3Renderer",
"Qwen3RendererConfig",
"Qwen3VLRenderer",
"Qwen3VLRendererConfig",
"RenderedConversation",
"RenderedTokens",
"Renderer",
"RendererConfig",
"RendererPool",
"TextPart",
"ThinkingPart",
@@ -88,10 +175,13 @@ __all__ = [
"ToolSpec",
"VideoPart",
"__version__",
"attribute_text_segments",
"build_training_sample",
"build_trajectory_step",
"config_from_name",
"create_renderer",
"create_renderer_pool",
"extract_message_tool_names",
"is_multimodal",
"reject_assistant_in_extension",
"trim_to_turn_close",
+936 -138
View File
File diff suppressed because it is too large Load Diff
+166 -68
View File
@@ -12,16 +12,18 @@ achieve real parallelism.
from __future__ import annotations
import asyncio
import base64
import json
import logging
from collections.abc import Mapping
from typing import Any, cast
import numpy as np
from openai import AsyncOpenAI, BadRequestError
import httpx
from openai import AsyncOpenAI
from renderers.base import (
Message,
MultiModalData,
RenderedTokens,
Renderer,
RendererPool,
ToolCallParseStatus,
@@ -29,6 +31,80 @@ from renderers.base import (
)
_request_logger = logging.getLogger("renderers.client")
ROUTED_EXPERTS_DATA_PREFIX = b'"routed_experts":{"data":"'
class OverlongPromptError(Exception):
"""The rendered prompt exceeds the engine's context window.
Raised by :func:`generate` when the rendered token sequence is strictly
longer than the resolved cap — either an explicit ``max_prompt_len`` the
caller passed in, or the engine's ``max_model_len`` discovered via
``GET /v1/models``. Caught client-side before the engine ever sees the
request, so callers route the failure to a deterministic policy (skip /
truncate / count) instead of round-tripping through an engine 4xx.
Named after the corresponding ``verifiers.errors.OverlongPromptError``;
the two are distinct classes (different package hierarchies) but the
concept is the same and downstream clients translate one to the other.
"""
def __init__(self, *, prompt_len: int, max_prompt_len: int) -> None:
self.prompt_len = prompt_len
self.max_prompt_len = max_prompt_len
super().__init__(
f"Prompt length ({prompt_len}) exceeds maximum "
f"context length ({max_prompt_len})."
)
# Per-process cache of resolved engine context-length caps, keyed by
# ``(base_url, model)``. ``None`` is the "we asked the engine and it didn't
# tell us" sentinel — distinct from "key missing" (haven't asked yet). The
# lock serializes the first lookup per key; cache hits avoid the lock.
_max_prompt_len_cache: dict[tuple[str, str], int | None] = {}
_max_prompt_len_lock = asyncio.Lock()
async def _resolve_max_prompt_len(client: AsyncOpenAI, model: str) -> int | None:
"""Discover ``max_model_len`` from the engine via ``GET /v1/models``.
OpenAI-API-compatible engines expose model metadata at this endpoint;
vLLM extends its ``ModelCard`` with a ``max_model_len`` field. Engines
that don't (SGLang as of this writing, third-party gateways, etc.) get
a cached ``None`` and the pre-flight overflow check silently disables —
callers fall back to whatever reactive handling they have for engine
4xx, which the verifiers ``@handle_openai_overlong_prompt`` decorator
already supplies for the prime-rl path.
Any exception during lookup (network error, non-JSON body, attribute
miss on a mock client in tests) is treated as "unknown cap": cached
``None`` so we don't retry on every call.
"""
key = (str(getattr(client, "base_url", "")), model)
if key in _max_prompt_len_cache:
return _max_prompt_len_cache[key]
async with _max_prompt_len_lock:
if key in _max_prompt_len_cache:
return _max_prompt_len_cache[key]
try:
payload = await client.get("/models", cast_to=cast(Any, dict[str, Any]))
except Exception as exc:
_request_logger.debug("max_prompt_len lookup failed: %s", exc)
_max_prompt_len_cache[key] = None
return None
value: int | None = None
for card in payload.get("data") or []:
if not isinstance(card, Mapping):
continue
if card.get("id") != model:
continue
raw = card.get("max_model_len")
if isinstance(raw, int) and raw > 0:
value = raw
break
_max_prompt_len_cache[key] = value
return value
async def _maybe_offload(renderer: Renderer | RendererPool, fn):
@@ -45,6 +121,26 @@ async def _maybe_offload(renderer: Renderer | RendererPool, fn):
return fn()
def strip_routed_experts_data(raw: bytes) -> tuple[bytes, memoryview | None]:
data_start = raw.find(ROUTED_EXPERTS_DATA_PREFIX)
if data_start < 0:
return raw, None
data_start += len(ROUTED_EXPERTS_DATA_PREFIX)
data_end = raw.index(b'"', data_start)
routed_data = memoryview(raw)[data_start:data_end]
stripped = raw[:data_start] + raw[data_end:]
return stripped, routed_data
def parse_generate_response(raw: bytes) -> dict[str, Any]:
stripped, routed_data = strip_routed_experts_data(raw)
payload: dict[str, Any] = json.loads(stripped)
if routed_data is not None:
payload["choices"][0]["routed_experts"]["data"] = routed_data
return payload
async def generate(
*,
client: AsyncOpenAI,
@@ -53,11 +149,13 @@ async def generate(
model: str,
prompt_ids: list[int] | None = None,
multi_modal_data: MultiModalData | None = None,
prompt_attribution: RenderedTokens | None = None,
tools: list[ToolSpec] | None = None,
sampling_params: dict[str, Any] | None = None,
cache_salt: str | None = None,
priority: int | None = None,
extra_headers: dict[str, str] | None = None,
max_prompt_len: int | None = None,
) -> dict[str, Any]:
"""Tokenize messages, call vLLM /inference/v1/generate, parse the response.
@@ -66,7 +164,11 @@ async def generate(
renderer) and ``logprobs=1`` (we always emit completion_logprobs). Pass
``prompt_ids`` to skip rendering and use a prebuilt token sequence —
pair it with ``multi_modal_data`` when the prebuilt prompt has image /
video placeholders that need engine-side mm payload.
video placeholders that need engine-side mm payload, and with
``prompt_attribution`` (a :class:`RenderedTokens` whose ``token_ids``
match the passed-in ``prompt_ids``) to carry the renderer's per-token
attribution (``is_content`` / ``sampled_mask`` / ``message_indices`` /
``message_roles``) into the result without re-rendering.
For multimodal renderers (e.g. ``Qwen3VLRenderer``), the call goes
through ``renderer.render(...)`` to recover the ``multi_modal_data``
@@ -74,9 +176,31 @@ async def generate(
mm_placeholders, kwargs_data) before POSTing. The serializer imports
``vllm.*`` lazily so text-only consumers never pay for the import.
``max_prompt_len`` controls the pre-flight overflow check. When the
rendered prompt is strictly longer than the cap, the request is never
sent and ``OverlongPromptError`` is raised. If ``max_prompt_len`` is
``None`` (the default), the cap is auto-discovered once per
``(base_url, model)`` via ``GET /v1/models`` (vLLM's
``ModelCard.max_model_len`` extension); engines that don't expose it
cache a ``None`` cap and the pre-flight silently disables. Engine 4xx
that still slip through propagate raw — converting them into a domain
error is the calling client's job (its error shape is engine-specific).
Returns a dict with: request_id, prompt_ids, completion_ids,
completion_logprobs, content, reasoning_content, tool_calls,
finish_reason, routed_experts.
finish_reason, routed_experts, multi_modal_data, prompt_attribution.
``prompt_attribution`` is the renderer's :class:`RenderedTokens` for
the prompt — either the one this call computed via
``renderer.render(...)`` or the one the caller threaded in alongside
``prompt_ids``. Carries ``token_ids``, ``message_indices``,
``sampled_mask``, ``is_content``, ``message_roles``, and
``multi_modal_data``, so downstream consumers (verifiers
``RendererClient`` → prime-rl) can build per-token loss masks
(``content_mask_for_roles({"tool"})`` for SFT-on-tool-body,
``sampled_mask`` for RL trainable spans) without a second render
pass. ``None`` when the caller passed pre-built ``prompt_ids``
without attribution.
"""
if tools and not getattr(renderer, "supports_tools", True):
raise ValueError(
@@ -86,15 +210,33 @@ async def generate(
def _prepare():
if prompt_ids is not None:
return list(prompt_ids), renderer.get_stop_token_ids(), multi_modal_data
# Caller-supplied prompt; if they also gave us pre-computed
# attribution (e.g. the bridge path in verifiers), thread it
# through unchanged.
return (
list(prompt_ids),
renderer.get_stop_token_ids(),
multi_modal_data,
prompt_attribution,
)
rendered = renderer.render(messages, tools=tools, add_generation_prompt=True)
return (
rendered.token_ids,
renderer.get_stop_token_ids(),
rendered.multi_modal_data,
rendered,
)
prompt_ids, stop_token_ids, mm_data = await _maybe_offload(renderer, _prepare)
prompt_ids, stop_token_ids, mm_data, prompt_attr = await _maybe_offload(
renderer, _prepare
)
if max_prompt_len is None:
max_prompt_len = await _resolve_max_prompt_len(client, model)
if max_prompt_len is not None and len(prompt_ids) > max_prompt_len:
raise OverlongPromptError(
prompt_len=len(prompt_ids), max_prompt_len=max_prompt_len
)
sp: dict[str, Any] = dict(sampling_params or {})
sp["stop_token_ids"] = stop_token_ids
@@ -130,21 +272,13 @@ async def generate(
sp.get("max_tokens"),
)
post_kwargs: dict[str, Any] = {
"cast_to": cast(Any, dict[str, Any]),
"cast_to": httpx.Response,
"body": body,
}
if extra_headers:
post_kwargs["options"] = cast(Any, {"headers": extra_headers})
try:
data = await client.post(endpoint, **post_kwargs)
except BadRequestError as exc:
_log_overlong_prompt_diagnostic(
prompt_ids=prompt_ids,
messages=messages,
max_tokens=sp.get("max_tokens"),
exc=exc,
)
raise
raw_response = await client.post(endpoint, **post_kwargs)
data = parse_generate_response(raw_response.content)
choice = (data.get("choices") or [{}])[0]
completion_ids = choice.get("token_ids") or []
@@ -158,14 +292,7 @@ async def generate(
content_lp = raw_logprobs.get("content") if isinstance(raw_logprobs, dict) else None
completion_logprobs = [float(c.get("logprob") or 0.0) for c in content_lp or []]
routed_experts = None
raw_re = choice.get("routed_experts")
if isinstance(raw_re, dict) and "data" in raw_re and "shape" in raw_re:
routed_experts = (
np.frombuffer(base64.b85decode(raw_re["data"]), dtype=np.int32)
.reshape(raw_re["shape"])
.tolist()
)
routed_experts = choice.get("routed_experts")
# /inference/v1/generate returns finish_reason in {"stop","length",...} —
# never "tool_calls" (a chat-completions concept). Promote stop→tool_calls
@@ -196,6 +323,14 @@ async def generate(
# callers can persist it on the trajectory step for downstream
# multi-turn bridging and training-sample construction.
"multi_modal_data": mm_data,
# The renderer's per-token attribution for the prompt — either
# the RenderedTokens computed here via renderer.render(...) or
# the one threaded in by the caller alongside prompt_ids (the
# bridge path). Lets downstream consumers (verifiers
# RendererClient → prime-rl) build SFT-on-tool-body and other
# selective loss masks without a second render pass. ``None``
# when the caller passed prompt_ids without attribution.
"prompt_attribution": prompt_attr,
}
@@ -225,6 +360,7 @@ def _build_mm_features(
to change. Don't pre-build the abstraction with one engine in tree.
"""
from renderers.qwen3_vl import Qwen3VLRenderer
from renderers.qwen35 import Qwen35Renderer
# Type dispatch only needs the renderer class. Pools expose
# ``renderer_cls`` as a snapshot attribute, so we don't have to check
@@ -233,7 +369,10 @@ def _build_mm_features(
renderer.renderer_cls if isinstance(renderer, RendererPool) else type(renderer)
)
if issubclass(renderer_cls, Qwen3VLRenderer):
# Qwen3-VL and Qwen3.5 both ship ``pixel_values`` + ``image_grid_thw``
# via the shared Qwen2-VL field factory. ``spatial_merge_size=2`` is
# the family default and matches every Qwen-VL processor in tree.
if issubclass(renderer_cls, (Qwen3VLRenderer, Qwen35Renderer)):
return _build_qwen_vl_features(mm_data, spatial_merge_size=2)
raise NotImplementedError(
@@ -305,44 +444,3 @@ def _build_qwen_vl_features(
out["kwargs_data"] = None
return out
def _log_overlong_prompt_diagnostic(
*,
prompt_ids: list[int],
messages: list[Message],
max_tokens: int | None,
exc: BadRequestError,
) -> None:
"""Log a structured snapshot when vLLM rejects with 4xx — usually overlong.
Captures total prompt length, per-message role + character count, and
the first chunk of the response body.
"""
body_text = ""
response = getattr(exc, "response", None)
if response is not None:
body_text = (response.text or "")[:500].replace("\n", " ")
msg_summary = []
for i, m in enumerate(messages):
role = m.get("role", "?")
content = m.get("content")
if isinstance(content, str):
content_len = len(content)
elif isinstance(content, list):
content_len = sum(
len(p.get("text", "")) if isinstance(p, dict) else 0 for p in content
)
else:
content_len = 0
tool_calls = m.get("tool_calls")
tc_count = len(tool_calls) if tool_calls else 0
msg_summary.append(f"[{i}]{role}(c={content_len},tc={tc_count})")
_request_logger.warning(
"vllm 4xx prompt_len=%d messages=%d max_tokens=%s per_msg=%s response_body=%s",
len(prompt_ids),
len(messages),
max_tokens,
" ".join(msg_summary),
body_text,
)
+547
View File
@@ -0,0 +1,547 @@
"""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 ``preserve_*`` flags live on ``BaseRendererConfig``
and OR-compose with template-level toggles (e.g. GLM-5
``clear_thinking``) inside each renderer — they extend retention, never
override the template into a drop.
``AutoRendererConfig`` is a placeholder variant: ``create_renderer``
resolves it via ``MODEL_RENDERER_MAP`` and constructs the matching
typed config with the auto config's ``preserve_*`` fields carried over.
``DefaultRendererConfig`` uses ``extra="allow"`` to accept arbitrary
Jinja kwargs as ``model_extra`` — ``DefaultRenderer`` doesn't know which
keys its tokenizer's template will honour, so it can't enumerate them.
"""
from __future__ import annotations
from typing import Annotated, ClassVar, Literal, Union
from pydantic import ConfigDict, Field
from pydantic_config import BaseConfig
class BaseRendererConfig(BaseConfig):
"""Shared fields and config for every renderer config variant.
Inherits from ``pydantic_config.BaseConfig`` so the typed-config
surface stays uniform with prime-rl / verifiers config bases. The
BaseConfig contract includes ``extra="forbid"`` (preserved here);
this class adds ``frozen=True`` so configs are hashable value
objects.
``preserve_all_thinking`` and ``preserve_thinking_between_tool_calls``
are renderer-internal behaviour flags — they don't map to any Jinja
chat-template kwarg. They OR-compose with template-level toggles on
renderers that expose one (GLM-5 ``clear_thinking``, Nemotron-3
``truncate_history_thinking``): either flag saying "keep this
thinking" wins. preserve_* can only ever extend retention; setting
``preserve_all_thinking=True`` always keeps past thinking, regardless
of the template kwarg. See ``renderers.base.should_preserve_past_thinking``.
"""
model_config = ConfigDict(frozen=True)
preserve_all_thinking: bool = False
"""Restore ``reasoning_content`` on every past assistant turn, even
when the chat template would drop it. Strict superset of
``preserve_thinking_between_tool_calls``."""
preserve_thinking_between_tool_calls: bool = False
"""Restore ``reasoning_content`` only inside the in-flight tool cycle:
the contiguous A-T-...-A block after the most recent ``user`` turn,
and only if it contains at least one ``tool`` response. A new user
turn closes the block and drops its thinking (template default)."""
# Fields that are renderer-internal — not forwarded to (or mirrored
# by) ``apply_chat_template``. Override in subclasses that hold
# non-template config (e.g. ``image_cache_max``, GptOss's
# ``use_system_prompt`` / ``knowledge_cutoff`` / ``model_identity``,
# or fields that exist as renderer conventions without a Jinja
# analogue like DeepSeek V3 / Kimi K2 ``enable_thinking``).
#
# Used by parity tests to compute the field subset that, when
# changed, must produce token streams matching
# ``apply_chat_template`` — see :meth:`template_field_names`. The
# renderer is the only end-to-end consumer of these fields, so this
# is a renderer-side bookkeeping concern rather than a public API.
_internal_fields: ClassVar[frozenset[str]] = frozenset()
@classmethod
def template_field_names(cls) -> frozenset[str]:
"""Subset of fields that mirror Jinja chat-template kwargs.
Default: every non-base field except ``name`` and any field
listed in ``_internal_fields``. Used by the parity test matrix
(``tests/test_renderer_config_parity.py``) to discover the
cells that must agree with ``apply_chat_template``.
"""
base = frozenset(BaseRendererConfig.model_fields)
return frozenset(cls.model_fields) - base - {"name"} - cls._internal_fields
class AutoRendererConfig(BaseRendererConfig):
"""Resolve the renderer from ``tokenizer.name_or_path`` at construction
time via ``MODEL_RENDERER_MAP``. Carries only the shared ``preserve_*``
fields; template kwargs require an explicit renderer choice so that
template-dependent behaviour stays visible at the call site."""
name: Literal["auto"] = "auto"
class DefaultRendererConfig(BaseRendererConfig):
"""Config for ``DefaultRenderer`` — the fallback wrapping
``tokenizer.apply_chat_template``. Accepts arbitrary extra fields
via ``extra="allow"`` because the underlying Jinja template's kwargs
are unknown to us. ``DefaultRenderer`` forwards ``model_extra`` to
``apply_chat_template`` verbatim.
"""
model_config = ConfigDict(frozen=True, extra="allow")
name: Literal["default"] = "default"
tool_parser: str | None = None
"""Name of a tool parser registered in ``renderers.parsers`` (e.g.
``"qwen3"``, ``"glm"``). Consumed only by ``DefaultRenderer``."""
reasoning_parser: str | None = None
"""Name of a reasoning parser registered in ``renderers.parsers``
(e.g. ``"think"``). Consumed only by ``DefaultRenderer``."""
# tool_parser / reasoning_parser are renderer-internal — they configure
# DefaultRenderer's parsing pipeline, not the underlying Jinja
# template. Jinja kwargs live in ``model_extra`` (extra="allow").
_internal_fields = frozenset({"tool_parser", "reasoning_parser"})
class Qwen3RendererConfig(BaseRendererConfig):
"""Qwen3 (text-only) renderer config."""
name: Literal["qwen3"] = "qwen3"
enable_thinking: bool = True
"""When ``True``, the generation prompt includes ``<think>`` so the
model continues into a thinking block. Mirrors the chat template's
``enable_thinking`` kwarg."""
class Qwen35RendererConfig(BaseRendererConfig):
"""Qwen3.5 renderer config."""
name: Literal["qwen3.5"] = "qwen3.5"
enable_thinking: bool | None = None
"""When ``True``, the generation prompt includes ``<think>``. ``None``
auto-detects from the tokenizer's chat-template default — Instruct
checkpoints default off, Thinking checkpoints default on. Mirrors
the chat template's ``enable_thinking`` kwarg."""
add_vision_id: bool = False
"""When ``True``, prefix each ``<|vision_start|>`` placeholder with
``"Picture N: "`` / ``"Video N: "`` where N is a 1-indexed counter
running across the entire conversation. Mirrors the chat template's
``add_vision_id`` toggle."""
image_cache_max: int = 256
"""FIFO bound on the per-renderer image processor cache. Renderer-
internal — not a Jinja chat-template kwarg."""
_internal_fields = frozenset({"image_cache_max"})
class Qwen36RendererConfig(BaseRendererConfig):
"""Qwen3.6 renderer config. Inherits Qwen3.5's template surface."""
name: Literal["qwen3.6"] = "qwen3.6"
enable_thinking: bool | None = None
"""See :class:`Qwen35RendererConfig.enable_thinking`."""
add_vision_id: bool = False
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
image_cache_max: int = 256
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
_internal_fields = frozenset({"image_cache_max"})
class Qwen3VLRendererConfig(BaseRendererConfig):
"""Qwen3-VL renderer config."""
name: Literal["qwen3-vl"] = "qwen3-vl"
add_vision_id: bool = False
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
image_cache_max: int = 256
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
_internal_fields = frozenset({"image_cache_max"})
class GLM5RendererConfig(BaseRendererConfig):
"""GLM-5 renderer config."""
name: Literal["glm-5"] = "glm-5"
enable_thinking: bool = True
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
the chat template's ``enable_thinking`` kwarg."""
clear_thinking: bool = True
"""When ``False``, the renderer keeps ``<think>{reasoning}</think>``
on past-cycle assistant turns instead of dropping them. Mirrors the
chat template's ``clear_thinking`` toggle. OR-composes with
``preserve_all_thinking`` / ``preserve_thinking_between_tool_calls``
— see :class:`BaseRendererConfig` for the contract."""
class GLM51RendererConfig(BaseRendererConfig):
"""GLM-5.1 renderer config — same template surface as GLM-5, distinct
discriminator so the registry can route to ``GLM51Renderer``."""
name: Literal["glm-5.1"] = "glm-5.1"
enable_thinking: bool = True
"""See :class:`GLM5RendererConfig.enable_thinking`."""
clear_thinking: bool = True
"""See :class:`GLM5RendererConfig.clear_thinking`."""
class GLM45RendererConfig(BaseRendererConfig):
"""GLM-4.5 Air renderer config."""
name: Literal["glm-4.5"] = "glm-4.5"
enable_thinking: bool = True
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
the chat template's ``enable_thinking`` kwarg."""
class GptOssRendererConfig(BaseRendererConfig):
"""OpenAI gpt-oss (harmony) renderer config.
Several fields here are renderer-internal: ``use_system_prompt``,
``knowledge_cutoff``, and ``model_identity`` control how the renderer
builds the harmony ``SystemContent`` preamble and don't have direct
Jinja-kwarg analogues. They're typed config rather than Jinja kwargs
because users still want to set them — the distinction only matters
for downstream tooling that synthesises a Jinja-kwargs view (none
today, since vLLM is invoked via the token-in endpoint).
"""
name: Literal["gpt-oss"] = "gpt-oss"
reasoning_effort: Literal["low", "medium", "high"] = "medium"
"""Harmony reasoning-effort tag. Mirrors the ``apply_chat_template``
``reasoning_effort`` kwarg."""
conversation_start_date: str | None = None
"""ISO date string for the harmony preamble. ``None`` defers to
today's date at render time."""
use_system_prompt: bool = True
"""Prepend the canonical harmony ``SystemContent`` preamble. Matches
HF's ``apply_chat_template`` behaviour."""
knowledge_cutoff: str | None = None
"""Override the model's knowledge-cutoff string in the preamble.
``None`` uses harmony's built-in default."""
model_identity: str | None = None
"""Override the model-identity line in the preamble. ``None`` uses
harmony's built-in default."""
_internal_fields = frozenset(
{"use_system_prompt", "knowledge_cutoff", "model_identity"}
)
class KimiK2RendererConfig(BaseRendererConfig):
"""Kimi K2 renderer config.
``enable_thinking`` is renderer-internal here — Kimi K2's chat
template doesn't reference any thinking variable, so it's a no-op
against ``apply_chat_template`` parity. The field is kept for
protocol uniformity with the rest of the renderer family.
"""
name: Literal["kimi-k2"] = "kimi-k2"
enable_thinking: bool = True
"""No-op for Kimi K2 (template doesn't gate on it). Stored for
introspection / cross-renderer uniformity."""
_internal_fields = frozenset({"enable_thinking"})
class KimiK25RendererConfig(BaseRendererConfig):
"""Kimi K2.5 renderer config."""
name: Literal["kimi-k2.5"] = "kimi-k2.5"
thinking: bool = True
"""When ``True``, the generation prompt prefills ``<think>``; when
``False`` it prefills ``<think></think>``. The kwarg is named
``thinking`` (not ``enable_thinking``) to match the upstream chat
template's native variable name."""
image_cache_max: int = 256
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
_internal_fields = frozenset({"image_cache_max"})
class LagunaXS2RendererConfig(BaseRendererConfig):
"""Laguna XS.2 renderer config."""
name: Literal["laguna-xs.2"] = "laguna-xs.2"
enable_thinking: bool = False
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
the chat template's ``enable_thinking`` kwarg. Default ``False``
matches the upstream Jinja default for Laguna XS.2."""
render_assistant_messages_raw: bool = False
"""When ``True``, assistant messages render as a passthrough: the
content bytes are emitted verbatim (no reasoning extraction, no
tool-call XML synthesis), and the ``<think>``/``</think>`` prefix
and ``</assistant>`` suffix are only added when missing. Mirrors the
chat template's ``render_assistant_messages_raw`` gate."""
class Llama3RendererConfig(BaseRendererConfig):
"""Llama-3.x Instruct renderer config.
Llama-3 ships no reasoning channel, so the base ``preserve_*_thinking``
flags don't apply: ``Llama3Renderer`` raises ``NotImplementedError``
if either is set (matching ``DefaultRenderer``'s contract for the
same case). Both fields below mirror real ``apply_chat_template``
kwargs.
"""
name: Literal["llama-3"] = "llama-3"
date_string: str = "26 Jul 2024"
"""``Today Date`` value injected into the system preamble. Pinned to
the chat template's ``strftime`` fallback by default so output stays
deterministic; override per instance for production runs that want
today's date. Mirrors the chat template's ``date_string`` kwarg."""
tools_in_user_message: bool = True
"""When ``True`` (default), tool descriptions + JSON signatures inject
into the first user message; ``False`` routes them into the system
block instead. Mirrors the chat template's ``tools_in_user_message``
kwarg."""
class MiniMaxM2RendererConfig(BaseRendererConfig):
"""MiniMax M2 / M2.5 renderer config."""
name: Literal["minimax-m2"] = "minimax-m2"
model_identity: str = "You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax."
"""Fallback persona used when no system message is supplied. Mirrors
the chat template's ``model_identity`` Jinja variable."""
class Nemotron3RendererConfig(BaseRendererConfig):
"""Nemotron-3 **Nano / Super** renderer config.
Nano and Super share one chat-template variant; the renderer routes both
through :class:`renderers.nemotron3.Nemotron3Renderer`. The Ultra variant
has its own template (different reasoning-block glue) and config —
:class:`Nemotron3UltraRendererConfig` — and is reached via the
``nemotron-3-ultra`` discriminator.
"""
name: Literal["nemotron-3"] = "nemotron-3"
enable_thinking: bool = True
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
the chat template's ``enable_thinking`` kwarg."""
truncate_history_thinking: bool = True
"""When ``False``, keep ``<think>{reasoning}</think>`` on past-cycle
assistant turns instead of dropping them. Mirrors the chat
template's ``truncate_history_thinking`` toggle. OR-composes with
``preserve_all_thinking`` / ``preserve_thinking_between_tool_calls``
— see :class:`BaseRendererConfig` for the contract."""
low_effort: bool = False
"""When ``True``, append ``\\n\\n{reasoning effort: low}`` to the last user
message, nudging the model toward shorter reasoning. Mirrors the **Super**
chat template's ``low_effort`` kwarg. A no-op on **Nano** (its template
doesn't define it) — exactly as ``apply_chat_template`` ignores an undefined
template variable; the renderer distinguishes the two by model name (see
``renderers.nemotron3._is_super``)."""
class Nemotron3UltraRendererConfig(BaseRendererConfig):
"""Nemotron-3 **Ultra** renderer config — distinct discriminator so the
registry routes Ultra checkpoints to the Ultra template variant.
Ultra's template differs from Nano/Super: the reasoning block is glued as
``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around ``</think>``)
and truncated historical turns collapse to ``<think></think>{content}``
(no ``\\n``). It shares the :class:`renderers.nemotron3.Nemotron3Renderer`
implementation, which selects the variant from ``config.name``.
"""
name: Literal["nemotron-3-ultra"] = "nemotron-3-ultra"
enable_thinking: bool = True
"""See :class:`Nemotron3RendererConfig.enable_thinking`."""
truncate_history_thinking: bool = True
"""See :class:`Nemotron3RendererConfig.truncate_history_thinking`."""
medium_effort: bool = False
"""When ``True``, append ``\\n\\n{reasoning effort: efficient}`` to the last
user message. Mirrors the Ultra chat template's ``medium_effort`` kwarg."""
class DeepSeekV3RendererConfig(BaseRendererConfig):
"""DeepSeek-V3 renderer config (non-reasoning).
DeepSeek-V3 has no thinking concept: the generation prompt is a bare
``<|Assistant|>`` and assistant content is emitted verbatim. For the
reasoning variant use :class:`DeepSeekR1RendererConfig`.
"""
name: Literal["deepseek-v3"] = "deepseek-v3"
class DeepSeekR1RendererConfig(BaseRendererConfig):
"""DeepSeek-R1 renderer config (reasoning).
R1 always reasons — its chat template unconditionally prefills
``<think>\\n`` at the generation prompt and strips ``</think>`` from
historical assistant turns. There is therefore no ``enable_thinking``
knob (thinking is not optional), and ``preserve_*`` flags are no-ops
(history reasoning is always dropped); both stored for protocol
uniformity. Applies to full ``deepseek-ai/DeepSeek-R1`` / ``-R1-0528``
— NOT the R1-Distill-Qwen/Llama models, which use those base
tokenizers and route to the Qwen3 / Llama-3 renderers.
"""
name: Literal["deepseek-r1"] = "deepseek-r1"
RendererConfig = Annotated[
Union[
AutoRendererConfig,
DefaultRendererConfig,
Qwen3RendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen3VLRendererConfig,
GLM5RendererConfig,
GLM51RendererConfig,
GLM45RendererConfig,
GptOssRendererConfig,
KimiK2RendererConfig,
KimiK25RendererConfig,
LagunaXS2RendererConfig,
Llama3RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
DeepSeekV3RendererConfig,
DeepSeekR1RendererConfig,
],
Field(discriminator="name"),
]
"""Discriminated union over every renderer config variant.
Downstream pydantic configs (prime-rl orchestrator, verifiers
``ClientConfig``) can hold a single field typed as ``RendererConfig``;
deserialization dispatches on ``name`` and exposes strictly the kwargs
that renderer supports. Bogus combinations (e.g. ``add_vision_id`` under
``name="qwen3"``) raise ``ValidationError`` at config-load time.
"""
# Map discriminator → config class. Used by ``create_renderer`` when
# resolving ``AutoRendererConfig`` against ``MODEL_RENDERER_MAP``: the
# resolved renderer name picks the corresponding typed config, and the
# auto config's ``preserve_*`` fields are carried over.
_CONFIG_BY_NAME: dict[str, type[BaseRendererConfig]] = {
"auto": AutoRendererConfig,
"default": DefaultRendererConfig,
"qwen3": Qwen3RendererConfig,
"qwen3.5": Qwen35RendererConfig,
"qwen3.6": Qwen36RendererConfig,
"qwen3-vl": Qwen3VLRendererConfig,
"glm-5": GLM5RendererConfig,
"glm-5.1": GLM51RendererConfig,
"glm-4.5": GLM45RendererConfig,
"gpt-oss": GptOssRendererConfig,
"kimi-k2": KimiK2RendererConfig,
"kimi-k2.5": KimiK25RendererConfig,
"laguna-xs.2": LagunaXS2RendererConfig,
"llama-3": Llama3RendererConfig,
"minimax-m2": MiniMaxM2RendererConfig,
"nemotron-3": Nemotron3RendererConfig,
"nemotron-3-ultra": Nemotron3UltraRendererConfig,
"deepseek-v3": DeepSeekV3RendererConfig,
"deepseek-r1": DeepSeekR1RendererConfig,
}
def _config_class_for(name: str) -> type[BaseRendererConfig]:
cls = _CONFIG_BY_NAME.get(name)
if cls is None:
raise ValueError(
f"No renderer config registered for name={name!r}. "
f"Known: {sorted(_CONFIG_BY_NAME)}"
)
return cls
def config_from_name(name: str) -> BaseRendererConfig | None:
"""Construct a default-valued config for the given renderer name.
Convenience for callers that hold a renderer name as a string and
want the matching typed config. ``"auto"`` returns ``None`` —
:func:`renderers.create_renderer` interprets that as "run auto
resolution against ``MODEL_RENDERER_MAP``", which is what callers
expect from a bare-string name.
"""
if name == "auto":
return None
return _config_class_for(name)()
__all__ = [
"AutoRendererConfig",
"BaseRendererConfig",
"DefaultRendererConfig",
"DeepSeekR1RendererConfig",
"DeepSeekV3RendererConfig",
"GLM45RendererConfig",
"GLM51RendererConfig",
"GLM5RendererConfig",
"GptOssRendererConfig",
"KimiK25RendererConfig",
"KimiK2RendererConfig",
"LagunaXS2RendererConfig",
"Llama3RendererConfig",
"MiniMaxM2RendererConfig",
"Nemotron3RendererConfig",
"Nemotron3UltraRendererConfig",
"Qwen35RendererConfig",
"Qwen36RendererConfig",
"Qwen3RendererConfig",
"Qwen3VLRendererConfig",
"RendererConfig",
"config_from_name",
]
+58
View File
@@ -0,0 +1,58 @@
"""DeepSeek-R1 Renderer — the reasoning variant of the DeepSeek format.
R1 shares DeepSeek-V3's special tokens, message structure, and tool-call
wire format, so it subclasses :class:`renderers.deepseek_v3.DeepSeekV3Renderer`
and overrides only the two places its chat template diverges:
1. Generation prompt — R1 unconditionally prefills ``<think>\\n``
(``<|Assistant|><think>\\n``) to trigger reasoning, where V3 emits a bare
``<|Assistant|>``. Handled by ``_GEN_THINK_PREFILL``.
2. Historical assistant turns — R1 strips the reasoning trace, keeping only
the text after ``</think>`` (``content.split('</think>')[-1]``), where V3
emits content verbatim. Handled by ``_prepare_assistant_content``.
Everything else — system handling, tool-call / tool-output rendering,
special-token resolution, and ``parse_response`` (``parse_deepseek_v3``,
shared) — is inherited unchanged.
Scope: full ``deepseek-ai/DeepSeek-R1`` and ``-R1-0528``. The R1-Distill
models (``DeepSeek-R1-Distill-Qwen/Llama``) use their base models'
tokenizers and route to the Qwen3 / Llama-3 renderers, not this one.
"""
from __future__ import annotations
from renderers.base import Message
from renderers.configs import DeepSeekR1RendererConfig
from renderers.deepseek_v3 import DeepSeekV3Renderer
class DeepSeekR1Renderer(DeepSeekV3Renderer):
"""Deterministic message → token renderer for DeepSeek-R1 models."""
_config_cls: type = DeepSeekR1RendererConfig
_GEN_THINK_PREFILL: str = "<think>\n"
def _prepare_assistant_content(self, msg: Message) -> str:
"""Assistant content with the reasoning trace stripped, mirroring the
R1 template's ``content.split('</think>')[-1]`` on historical turns.
Structured ``thinking``/``text`` parts are reconstructed inline first
so the same ``</think>`` split applies. The separate
``reasoning_content`` field is ignored — the R1 chat template never
reads it, and history reasoning is dropped regardless.
"""
content = msg.get("content") or ""
if isinstance(content, list):
parts: list[str] = []
for p in content:
if not isinstance(p, dict):
continue
if p.get("type") == "thinking":
parts.append(f"<think>{p.get('thinking', '')}</think>")
elif p.get("type") == "text":
parts.append(p.get("text", ""))
content = "".join(parts)
if "</think>" in content:
content = content.split("</think>")[-1]
return content
+175 -78
View File
@@ -21,9 +21,12 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.configs import DeepSeekV3RendererConfig
from renderers.parsing import parse_deepseek_v3
# Fullwidth vertical bar used in DeepSeek special token names.
@@ -38,25 +41,30 @@ def _ds_token(name: str) -> str:
class DeepSeekV3Renderer:
"""Deterministic message → token renderer for DeepSeek V3 models."""
"""Deterministic message → token renderer for DeepSeek-V3 models.
DeepSeek-V3 is non-reasoning: its chat template has no ``<think>``
concept — the generation prompt is a bare ``<|Assistant|>`` and past
assistant content is emitted verbatim. The reasoning variant
(``<think>``-prefilled prompt, history reasoning stripped) lives in
:class:`renderers.deepseek_r1.DeepSeekR1Renderer`, which subclasses
this one. ``preserve_*`` flags are no-ops here (no reasoning channel),
stored for protocol uniformity.
"""
#: Default typed config; the R1 subclass overrides this.
_config_cls: type = DeepSeekV3RendererConfig
#: Generation-prompt reasoning prefill. Empty for V3 (bare
#: ``<|Assistant|>``); the R1 subclass overrides to ``"<think>\n"``.
_GEN_THINK_PREFILL: str = ""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: DeepSeekV3RendererConfig | None = None,
):
# DeepSeek-V3's chat template always emits ``<think>{reasoning}</think>``
# when ``reasoning_content`` is provided — no drop, so the override
# flags are no-ops. Stored for introspection / Protocol parity only.
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or type(self)._config_cls()
# ── BOS / EOS ────────────────────────────────────────────────
self._bos = self._get_special_token(f"begin{_US}of{_US}sentence")
@@ -114,22 +122,47 @@ class DeepSeekV3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
def emit_ids(
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
emit_ids(
self._encode(text),
msg_idx,
is_sampled=is_sampled,
is_content=is_content,
)
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
# ── 1. BOS token ─────────────────────────────────────────────
emit_special(self._bos, -1, is_sampled=False)
emit_special(self._bos, -1, is_sampled=False, is_content=False)
# ── 2. Collect system messages at the start ───────────────────
# All leading system messages are concatenated with "\n\n" and emitted
@@ -151,7 +184,8 @@ class DeepSeekV3Renderer:
if sys_parts:
# Attribute the concatenated system text to the first system message (index 0).
emit_text("\n\n".join(sys_parts), 0, is_sampled=False)
# The system content is the caller's body — mark is_content=True.
emit_text("\n\n".join(sys_parts), 0, is_sampled=False, is_content=True)
# ── 3. Render non-system messages ─────────────────────────────
num_messages = len(messages)
@@ -166,8 +200,8 @@ class DeepSeekV3Renderer:
content = "".join(
p.get("text", "") for p in content if isinstance(p, dict)
)
emit_special(self._user_token, i, is_sampled=False)
emit_text(str(content), i, is_sampled=False)
emit_special(self._user_token, i, is_sampled=False, is_content=False)
emit_text(str(content), i, is_sampled=False, is_content=True)
elif role == "user":
content = msg.get("content") or ""
@@ -180,8 +214,8 @@ class DeepSeekV3Renderer:
else ""
for p in content
)
emit_special(self._user_token, i, is_sampled=False)
emit_text(str(content), i, is_sampled=False)
emit_special(self._user_token, i, is_sampled=False, is_content=False)
emit_text(str(content), i, is_sampled=False, is_content=True)
elif role == "assistant":
self._render_assistant(
@@ -190,6 +224,7 @@ class DeepSeekV3Renderer:
messages,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
@@ -198,6 +233,7 @@ class DeepSeekV3Renderer:
i,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
# ── 4. Generation prompt ──────────────────────────────────────
@@ -205,12 +241,21 @@ class DeepSeekV3Renderer:
# Don't add <|Assistant|> after tool outputs — content flows directly.
last_role = messages[-1]["role"] if messages else None
if last_role != "tool":
emit_special(self._assistant_token, -1, is_sampled=False)
if self._enable_thinking:
emit_text("<think>\n", -1, is_sampled=False)
emit_special(
self._assistant_token, -1, is_sampled=False, is_content=False
)
if self._GEN_THINK_PREFILL:
emit_text(
self._GEN_THINK_PREFILL, -1, is_sampled=False, is_content=False
)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -271,22 +316,40 @@ class DeepSeekV3Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
ext_content: list[bool] = []
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.extend(self._encode(text))
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([is_content] * len(ids))
for i, msg in enumerate(new_messages):
role = msg.get("role")
@@ -299,11 +362,11 @@ class DeepSeekV3Renderer:
if role == "user":
emit_special(self._user_token, i)
emit_text(content, i)
emit_text(content, i, is_content=True)
elif role == "system":
# Post-initial system messages render as user turns.
emit_special(self._user_token, i)
emit_text(content, i)
emit_text(content, i, is_content=True)
elif role == "tool":
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
next_is_tool = (
@@ -313,7 +376,7 @@ class DeepSeekV3Renderer:
if not prev_is_tool:
emit_special(self._tool_outputs_begin, i)
emit_special(self._tool_output_begin, i)
emit_text(content, i)
emit_text(content, i, is_content=True)
emit_special(self._tool_output_end, i)
if not next_is_tool:
emit_special(self._tool_outputs_end, i)
@@ -326,15 +389,40 @@ class DeepSeekV3Renderer:
last_role = new_messages[-1].get("role") if new_messages else None
if last_role != "tool":
emit_special(self._assistant_token, -1)
if self._enable_thinking:
emit_text("<think>\n", -1)
if self._GEN_THINK_PREFILL:
emit_text(self._GEN_THINK_PREFILL, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
# ------------------------------------------------------------------
# Assistant rendering
# ------------------------------------------------------------------
def _prepare_assistant_content(self, msg: Message) -> str:
"""Assistant content as the V3 template would emit it: verbatim.
V3 is non-reasoning — its template emits ``message['content']`` as-is
and never reads ``reasoning_content``. A structured content list is
flattened to its ``text`` parts. The R1 subclass overrides this to
strip ``</think>`` from history.
"""
content = msg.get("content") or ""
if isinstance(content, list):
content = "".join(
p.get("text", "")
for p in content
if isinstance(p, dict) and p.get("type") == "text"
)
return content
def _render_assistant(
self,
msg: Message,
@@ -343,30 +431,14 @@ class DeepSeekV3Renderer:
*,
emit_special,
emit_text,
emit_text_segments,
) -> None:
# Determine whether this message follows a tool output sequence.
# The HF template emits <|tool▁outputs▁end|> before the assistant content
# without a new <|Assistant|> token in that case.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
content = msg.get("content") or ""
# Support structured content (ThinkingPart / TextPart list).
if isinstance(content, list):
parts_text: list[str] = []
for p in content:
if not isinstance(p, dict):
continue
if p.get("type") == "thinking":
thinking = p.get("thinking", "")
parts_text.append(f"<think>{thinking}</think>")
elif p.get("type") == "text":
parts_text.append(p.get("text", ""))
content = "".join(parts_text)
# Also accept reasoning_content stored separately (OpenAI-style).
elif isinstance(msg.get("reasoning_content"), str) and msg["reasoning_content"]:
reasoning = msg["reasoning_content"]
content = f"<think>{reasoning}</think>{content}"
content = self._prepare_assistant_content(msg)
tool_calls = msg.get("tool_calls") or []
# ``<|Assistant|>`` is template-injected scaffolding — at
@@ -375,18 +447,23 @@ class DeepSeekV3Renderer:
# keeps the SFT loss mask aligned with what the model would
# actually have produced. When the previous message is a tool
# response, the template skips this token entirely (content
# flows directly out of ``<|tool▁outputs▁end|>``).
# flows directly out of ``<|tool▁outputs▁end|>``). On assistant
# the invariant ``is_content == sampled_mask`` holds.
if not prev_is_tool:
emit_special(self._assistant_token, msg_idx, is_sampled=False)
emit_special(
self._assistant_token, msg_idx, is_sampled=False, is_content=False
)
if not tool_calls:
emit_text(content, msg_idx, is_sampled=True)
emit_text(content, msg_idx, is_sampled=True, is_content=True)
else:
# Emit any pre-tool-call content first.
emit_text(content, msg_idx, is_sampled=True)
emit_text(content, msg_idx, is_sampled=True, is_content=True)
# Tool call section.
emit_special(self._tool_calls_begin, msg_idx, is_sampled=True)
emit_special(
self._tool_calls_begin, msg_idx, is_sampled=True, is_content=True
)
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
@@ -398,17 +475,28 @@ class DeepSeekV3Renderer:
)
# Format: <|tool▁call▁begin|>function<|tool▁sep|>{name}\n```json\n{args}\n```<|tool▁call▁end|>
# tool_sep is a special token; type ("function") and name+args are plain text.
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text("function", msg_idx, is_sampled=True)
emit_special(self._tool_sep, msg_idx, is_sampled=True)
emit_text(f"{name}\n```json\n{args_str}\n```", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_end, msg_idx, is_sampled=True)
emit_special(
self._tool_call_begin, msg_idx, is_sampled=True, is_content=True
)
emit_text("function", msg_idx, is_sampled=True, is_content=True)
emit_special(self._tool_sep, msg_idx, is_sampled=True, is_content=True)
emit_text(
f"{name}\n```json\n{args_str}\n```",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
)
emit_special(
self._tool_calls_end, msg_idx, is_sampled=True, is_content=True
)
# ``<|end▁of▁sentence|>`` is the model's stop signal — it
# samples this to end its turn, so it is part of the sampled
# stream.
emit_special(self._eos, msg_idx, is_sampled=True)
emit_special(self._eos, msg_idx, is_sampled=True, is_content=True)
# ------------------------------------------------------------------
# Tool (tool-response) rendering
@@ -421,10 +509,13 @@ class DeepSeekV3Renderer:
*,
emit_special,
emit_text,
emit_text_segments,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
# tokens, so every emission is is_sampled=False. The ``content``
# body bytes get ``is_content=True``; the surrounding section
# specials are scaffold.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
@@ -435,11 +526,17 @@ class DeepSeekV3Renderer:
content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
if not prev_is_tool:
emit_special(self._tool_outputs_begin, msg_idx, is_sampled=False)
emit_special(
self._tool_outputs_begin, msg_idx, is_sampled=False, is_content=False
)
emit_special(self._tool_output_begin, msg_idx, is_sampled=False)
emit_text(str(content), msg_idx, is_sampled=False)
emit_special(self._tool_output_end, msg_idx, is_sampled=False)
emit_special(
self._tool_output_begin, msg_idx, is_sampled=False, is_content=False
)
emit_text(str(content), msg_idx, is_sampled=False, is_content=True)
emit_special(self._tool_output_end, msg_idx, is_sampled=False, is_content=False)
if not next_is_tool:
emit_special(self._tool_outputs_end, msg_idx, is_sampled=False)
emit_special(
self._tool_outputs_end, msg_idx, is_sampled=False, is_content=False
)
+21 -21
View File
@@ -18,10 +18,10 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
extract_message_tool_names,
)
from renderers.configs import DefaultRendererConfig
from renderers.parsers import (
ReasoningParser,
ToolParser,
get_reasoning_parser,
get_tool_parser,
)
@@ -82,36 +82,30 @@ def _decode_tool_call_arguments(messages: list) -> list:
class DefaultRenderer:
"""Fallback renderer using tokenizer.apply_chat_template().
Works with any model. Pass ``tool_parser`` and/or ``reasoning_parser``
(by name, resolved against the registries in ``renderers.parsers``) to
enable structured output extraction.
Works with any model. The config can carry ``tool_parser`` and/or
``reasoning_parser`` (resolved against ``renderers.parsers``) to
enable structured output extraction, plus arbitrary additional Jinja
template kwargs captured as ``model_extra`` (``extra="allow"`` on
:class:`renderers.DefaultRendererConfig`).
"""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
tool_parser: str | ToolParser | None = None,
reasoning_parser: str | ReasoningParser | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
**chat_template_kwargs,
config: DefaultRendererConfig | None = None,
):
if preserve_all_thinking or preserve_thinking_between_tool_calls:
cfg = config or DefaultRendererConfig()
if cfg.preserve_all_thinking or cfg.preserve_thinking_between_tool_calls:
raise NotImplementedError(
"DefaultRenderer falls back to apply_chat_template and can't "
"selectively re-emit dropped reasoning_content. Configure a "
"model-specific renderer if you need preserve_*_thinking."
)
self._tokenizer = tokenizer
self._chat_template_kwargs = chat_template_kwargs
self._tool_parser = _resolve_parser(tool_parser, tokenizer, get_tool_parser)
self.config = cfg
self._tool_parser = _resolve_parser(cfg.tool_parser, tokenizer, get_tool_parser)
self._reasoning_parser = _resolve_parser(
reasoning_parser, tokenizer, get_reasoning_parser
)
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
cfg.reasoning_parser, tokenizer, get_reasoning_parser
)
@property
@@ -143,10 +137,16 @@ class DefaultRenderer:
token_ids = full_ids
message_indices.extend([-1] * len(gen_tokens))
return RenderedTokens(token_ids=token_ids, message_indices=message_indices)
message_roles = [m.get("role") or "" for m in messages]
return RenderedTokens(
token_ids=token_ids,
message_indices=message_indices,
message_roles=message_roles,
message_tool_names=extract_message_tool_names(messages),
)
def _apply(self, messages, *, tools=None, add_generation_prompt=False) -> list[int]:
kwargs = dict(self._chat_template_kwargs)
kwargs = dict(self.config.model_extra or {})
kwargs["add_generation_prompt"] = add_generation_prompt
kwargs["tokenize"] = True
if tools is not None:
+243 -77
View File
@@ -20,9 +20,12 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
)
from renderers.configs import GLM45RendererConfig
from renderers.parsing import parse_glm
_TOOLS_HEADER = (
@@ -52,17 +55,10 @@ class GLM45Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: GLM45RendererConfig | None = None,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or GLM45RendererConfig()
self._gmask = self._token_id("[gMASK]")
self._sop = self._token_id("<sop>")
@@ -128,30 +124,58 @@ class GLM45Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
"""Tokenize concatenated segments as one BPE pass; per-token
``is_content`` follows each token's source segment.
Lets call sites express "this wrap + this body, joined the
same way as the chat template, but attributed separately"
without splitting the encode call (which could shift BPE
merges at the boundary)."""
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
# ── Prefix ──────────────────────────────────────────────────
emit_special(self._gmask, -1, is_sampled=False)
emit_special(self._sop, -1, is_sampled=False)
emit_special(self._gmask, -1, is_sampled=False, is_content=False)
emit_special(self._sop, -1, is_sampled=False, is_content=False)
# ── Tools in system prompt ──────────────────────────────────
# The tools-header block is all scaffold by design — the tools
# dict is recoverable from the ``tools`` argument; don't
# re-attribute the embedded JSON specs as message body.
if tools:
emit_special(self._system, -1, is_sampled=False)
emit_special(self._system, -1, is_sampled=False, is_content=False)
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
tool_text += _TOOLS_FOOTER
emit_text(tool_text, -1, is_sampled=False)
emit_text(tool_text, -1, is_sampled=False, is_content=False)
# ── Compute last_user_index ─────────────────────────────────
last_ui = self._last_user_index(messages)
@@ -161,23 +185,51 @@ class GLM45Renderer:
role = msg["role"]
content = self._visible_text(msg.get("content"))
# When the previous message is an assistant, this message's
# role-opening token (``<|user|>`` / ``<|observation|>``) is
# the inference-time stop signal that closes the assistant's
# turn (see ``get_stop_token_ids``). Mark it
# ``is_sampled=True`` so the loss-mask pipeline trains the
# model to emit it after ``</tool_call>`` (instead of
# continuing with another ``<tool_call>`` block). The token
# stays attributed to this message (msg_idx=i) and remains
# ``is_content=False`` — it's a role-marker / scaffold, not
# body bytes, so ``content_mask_for_roles({"tool"})`` and
# ``content_token_spans_by_role()`` correctly exclude it
# from "tool body" views. Byte stream is unchanged.
# ``system`` only appears at the start of a GLM conversation,
# so its opener is never the closer of an assistant turn.
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
if role == "system":
emit_special(self._system, i, is_sampled=False)
emit_text("\n" + content, i, is_sampled=False)
emit_special(self._system, i, is_sampled=False, is_content=False)
# ``\n`` is the scaffold separator after the role tag;
# the body proper is the caller-provided content.
emit_text_segments(
[("\n", False), (content, True)], i, is_sampled=False
)
elif role == "user":
emit_special(self._user, i, is_sampled=False)
user_text = "\n" + content
if not self._enable_thinking and not content.endswith("/nothink"):
user_text += "/nothink"
emit_text(user_text, i, is_sampled=False)
emit_special(
self._user,
i,
is_sampled=closes_assistant_turn,
is_content=False,
)
# ``\n`` is scaffold; ``content`` is body; the optional
# ``/nothink`` suffix is scaffold the renderer injects
# when ``enable_thinking=False``.
user_segments: list[tuple[str, bool]] = [("\n", False), (content, True)]
if not self.config.enable_thinking and not content.endswith("/nothink"):
user_segments.append(("/nothink", False))
emit_text_segments(user_segments, i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
messages,
i,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
self._render_assistant(
msg,
@@ -187,23 +239,34 @@ class GLM45Renderer:
preserve_thinking=preserve_thinking,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
self._render_tool(
messages, i, content, emit_special=emit_special, emit_text=emit_text
messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._assistant, -1, is_sampled=False)
if not self._enable_thinking:
emit_text("\n", -1, is_sampled=False)
emit_special(self._think, -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
if not self.config.enable_thinking:
emit_text("\n", -1, is_sampled=False, is_content=False)
emit_special(self._think, -1, is_sampled=False, is_content=False)
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -271,54 +334,121 @@ class GLM45Renderer:
last_prev = previous_ids[-1]
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
ext_content: list[bool] = []
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask. Downstream consumers can
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
# output to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.extend(self._encode(text))
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]],
msg_idx: int = -1,
*,
is_sampled: bool = False,
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
# The opener-token of the first new_message may also serve as
# the close of the previous assistant turn (when the model
# failed to sample the stop token itself and the bridge has to
# synthesize the boundary above). Unlike :meth:`render`, the
# bridge emits these with ``is_sampled=False, is_content=False``
# — they are template scaffolding for the *next* step's prompt,
# not tokens the model produced *in this* step. The RL loss
# operates on ``previous_completion_ids`` (what the model
# actually sampled this round); bridge tokens belong to the
# subsequent prompt and must not be counted as "model output"
# by downstream mask consumers. This deliberate disagreement
# with ``render()`` reflects the SFT vs RL semantics: render's
# masks describe what the model *should* produce given a
# complete conversation; bridge's masks describe what it
# *actually* produced this step.
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
if role == "user":
if not (i == 0 and last_prev == self._user):
emit_special(self._user, i)
user_text = "\n" + content
if not self._enable_thinking and not content.endswith("/nothink"):
user_text += "/nothink"
emit_text(user_text, i)
user_segments: list[tuple[str, bool]] = [
("\n", False),
(content, True),
]
if not self.config.enable_thinking and not content.endswith("/nothink"):
user_segments.append(("/nothink", False))
emit_text_segments(user_segments, i)
elif role == "system":
emit_special(self._system, i)
emit_text("\n" + content, i)
emit_text_segments([("\n", False), (content, True)], i)
elif role == "tool":
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
if i == 0 and last_prev == self._observation:
pass
elif not prev_is_tool:
emit_special(self._observation, i)
emit_text("\n<tool_response>\n" + content + "\n</tool_response>", i)
emit_text_segments(
[
("\n<tool_response>\n", False),
(content, True),
("\n</tool_response>", False),
],
i,
)
else:
return None
# Generation prompt.
emit_special(self._assistant, -1)
if not self._enable_thinking:
if not self.config.enable_thinking:
emit_text("\n", -1)
emit_special(self._think, -1)
emit_special(self._think_end, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
self,
@@ -330,6 +460,7 @@ class GLM45Renderer:
preserve_thinking: bool = False,
emit_special,
emit_text,
emit_text_segments,
):
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
@@ -357,23 +488,31 @@ class GLM45Renderer:
# turn). So no sampled stop-signal token lives inside this
# assistant span — content / think / tool_calls carry the
# is_sampled=True signal.
emit_special(self._assistant, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
#
# Invariant on assistant tokens: ``is_content == sampled_mask``.
# Every scaffold token here gets ``is_sampled=False/is_content=False``;
# every model-sampled emit gets both True.
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
if (msg_idx > last_user_index or preserve_thinking) and reasoning_content:
emit_special(self._think, msg_idx, is_sampled=True)
emit_text(reasoning_content.strip(), msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
emit_text(
reasoning_content.strip(), msg_idx, is_sampled=True, is_content=True
)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
else:
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
# Tool calls — keep content + \n contiguous to preserve BPE merges
tool_calls = msg.get("tool_calls") or []
if content.strip() and tool_calls:
emit_text("\n" + content.strip() + "\n", msg_idx, is_sampled=True)
emit_text(
"\n" + content.strip() + "\n", msg_idx, is_sampled=True, is_content=True
)
elif content.strip():
emit_text("\n" + content.strip(), msg_idx, is_sampled=True)
emit_text("\n" + content.strip(), msg_idx, is_sampled=True, is_content=True)
for tc in tool_calls:
func = tc.get("function") or tc
@@ -381,9 +520,9 @@ class GLM45Renderer:
arguments = func.get("arguments", {})
if not content.strip():
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_tok, msg_idx, is_sampled=True)
emit_text(name + "\n", msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
emit_special(self._tool_call_tok, msg_idx, is_sampled=True, is_content=True)
emit_text(name + "\n", msg_idx, is_sampled=True, is_content=True)
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
@@ -393,22 +532,33 @@ class GLM45Renderer:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
emit_special(self._arg_key, msg_idx, is_sampled=True)
emit_text(arg_name, msg_idx, is_sampled=True)
emit_special(self._arg_key_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._arg_value, msg_idx, is_sampled=True)
emit_special(
self._arg_key, msg_idx, is_sampled=True, is_content=True
)
emit_text(arg_name, msg_idx, is_sampled=True, is_content=True)
emit_special(
self._arg_key_end, msg_idx, is_sampled=True, is_content=True
)
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
emit_special(
self._arg_value, msg_idx, is_sampled=True, is_content=True
)
if isinstance(arg_value, str):
emit_text(arg_value, msg_idx, is_sampled=True)
emit_text(arg_value, msg_idx, is_sampled=True, is_content=True)
else:
emit_text(
json.dumps(arg_value, ensure_ascii=False),
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._arg_value_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, msg_idx, is_sampled=True)
emit_special(
self._arg_value_end, msg_idx, is_sampled=True, is_content=True
)
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_end_tok, msg_idx, is_sampled=True, is_content=True
)
def _render_tool(
self,
@@ -418,17 +568,33 @@ class GLM45Renderer:
*,
emit_special,
emit_text,
emit_text_segments,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
# Tool body bytes get ``is_content=True``; the wraps are
# scaffold. The ``<|observation|>`` role tag is scaffold too
# (``is_content=False`` so ``content_mask_for_roles({"tool"})``
# excludes it). When the previous message is an assistant it
# doubles as the inference stop signal for that assistant's
# turn — mark it ``is_sampled=True`` so SFT trains the model to
# emit it after ``</tool_call>``. The token stays attributed to
# this tool message; byte stream is unchanged.
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
closes_assistant_turn = prev_role == "assistant"
if not prev_is_tool:
emit_special(self._observation, msg_idx, is_sampled=False)
if prev_role != "tool":
emit_special(
self._observation,
msg_idx,
is_sampled=closes_assistant_turn,
is_content=False,
)
emit_text(
"\n<tool_response>\n" + content + "\n</tool_response>",
emit_text_segments(
[
("\n<tool_response>\n", False),
(content, True),
("\n</tool_response>", False),
],
msg_idx,
is_sampled=False,
)
+244 -73
View File
@@ -21,9 +21,12 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
)
from renderers.configs import GLM5RendererConfig, GLM51RendererConfig
from renderers.parsing import parse_glm
_TOOLS_HEADER = (
@@ -53,20 +56,18 @@ class GLM5Renderer:
# GLM51Renderer; GLM-5 proper keeps this off.
empty_think_on_last_assistant: bool = False
# GLM-5.1 uses the same template surface and binds the same kwargs.
# Subclassed in ``GLM51Renderer`` so the registry can dispatch on the
# ``glm-5.1`` discriminator while sharing this implementation.
_config_cls: type = GLM5RendererConfig
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: GLM5RendererConfig | GLM51RendererConfig | None = None,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or type(self)._config_cls()
self._gmask = self._token_id("[gMASK]")
self._sop = self._token_id("<sop>")
@@ -143,32 +144,61 @@ class GLM5Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
"""Tokenize concatenated segments as one BPE pass; per-token
``is_content`` follows each token's source segment.
Lets call sites express "this wrap + this body, joined the
same way as the chat template, but attributed separately"
without splitting the encode call (which could shift BPE
merges at the boundary)."""
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
# ── Prefix ──────────────────────────────────────────────────
# ``[gMASK]<sop>`` is unconditional template scaffolding at the
# very start of the stream — the model never samples these.
emit_special(self._gmask, -1, is_sampled=False)
emit_special(self._sop, -1, is_sampled=False)
# very start of the stream — the model never samples these and
# they are not part of any message body.
emit_special(self._gmask, -1, is_sampled=False, is_content=False)
emit_special(self._sop, -1, is_sampled=False, is_content=False)
# ── Tools in system prompt ──────────────────────────────────
# The tools-header block is all scaffold by design — the tools
# dict is recoverable from the ``tools`` argument; don't
# re-attribute the embedded JSON specs as message body.
if tools:
emit_special(self._system, -1, is_sampled=False)
emit_special(self._system, -1, is_sampled=False, is_content=False)
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += self._format_tool_spec(tool) + "\n"
tool_text += _TOOLS_FOOTER
emit_text(tool_text, -1, is_sampled=False)
emit_text(tool_text, -1, is_sampled=False, is_content=False)
# ── Compute last_user_index ─────────────────────────────────
last_ui = self._last_user_index(messages)
@@ -178,20 +208,41 @@ class GLM5Renderer:
role = msg["role"]
content = self._visible_text(msg.get("content"))
# When the previous message is an assistant, this message's
# role-opening token (``<|user|>`` / ``<|observation|>``) is
# the inference-time stop signal that closes the assistant's
# turn (see ``get_stop_token_ids``). Mark it
# ``is_sampled=True`` so the loss-mask pipeline trains the
# model to emit it after ``</tool_call>`` (instead of
# continuing with another ``<tool_call>`` block). The token
# stays attributed to this message (msg_idx=i) and remains
# ``is_content=False`` — it's a role-marker / scaffold, not
# body bytes, so ``content_mask_for_roles({"tool"})`` and
# ``content_token_spans_by_role()`` correctly exclude it
# from "tool body" views. Byte stream is unchanged.
# ``system`` only appears at the start of a GLM conversation,
# so its opener is never the closer of an assistant turn.
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
if role == "system":
emit_special(self._system, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
emit_special(self._system, i, is_sampled=False, is_content=False)
emit_text(content, i, is_sampled=False, is_content=True)
elif role == "user":
emit_special(self._user, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
emit_special(
self._user,
i,
is_sampled=closes_assistant_turn,
is_content=False,
)
emit_text(content, i, is_sampled=False, is_content=True)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
messages,
i,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
self._render_assistant(
msg,
@@ -201,26 +252,37 @@ class GLM5Renderer:
preserve_thinking=preserve_thinking,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
self._render_tool(
messages, i, content, emit_special=emit_special, emit_text=emit_text
messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
# ── Generation prompt ───────────────────────────────────────
# Gen prompt tokens are what the chat template prepends before
# sampling starts — the model continues from these, never emits
# them. Always is_sampled=False.
# them. Always is_sampled=False / is_content=False.
if add_generation_prompt:
emit_special(self._assistant, -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1, is_sampled=False)
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
if self.config.enable_thinking:
emit_special(self._think, -1, is_sampled=False, is_content=False)
else:
emit_special(self._think_end, -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -292,23 +354,72 @@ class GLM5Renderer:
last_prev = previous_ids[-1]
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
ext_content: list[bool] = []
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_assistant`` /
# ``_render_tool`` and ignore it; the returned ``RenderedTokens``
# leaves ``sampled_mask`` empty.
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask. Downstream consumers can
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
# output to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.extend(self._encode(text))
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]],
msg_idx: int = -1,
*,
is_sampled: bool = False,
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
# The opener-token of the first new_message may also serve as
# the close of the previous assistant turn (when the model
# failed to sample the stop token itself and the bridge has to
# synthesize the boundary above). Unlike :meth:`render`, the
# bridge emits these with ``is_sampled=False, is_content=False``
# — they are template scaffolding for the *next* step's prompt,
# not tokens the model produced *in this* step. The RL loss
# operates on ``previous_completion_ids`` (what the model
# actually sampled this round); bridge tokens belong to the
# subsequent prompt and must not be counted as "model output"
# by downstream mask consumers. This deliberate disagreement
# with ``render()`` reflects the SFT vs RL semantics: render's
# masks describe what the model *should* produce given a
# complete conversation; bridge's masks describe what it
# *actually* produced this step.
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
@@ -316,10 +427,10 @@ class GLM5Renderer:
# Dedup: model already emitted <|user|> as its stop token.
if not (i == 0 and last_prev == self._user):
emit_special(self._user, i)
emit_text(content, i)
emit_text(content, i, is_content=True)
elif role == "system":
emit_special(self._system, i)
emit_text(content, i)
emit_text(content, i, is_content=True)
elif role == "tool":
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
if i == 0 and last_prev == self._observation:
@@ -328,19 +439,27 @@ class GLM5Renderer:
elif not prev_is_tool:
emit_special(self._observation, i)
emit_special(self._tool_response_tok, i)
emit_text(content, i)
emit_text(content, i, is_content=True)
emit_special(self._tool_response_end_tok, i)
else:
return None
# Generation prompt — match the gen-prompt branch of ``render()``.
emit_special(self._assistant, -1)
if self._enable_thinking:
if self.config.enable_thinking:
emit_special(self._think, -1)
else:
emit_special(self._think_end, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
self,
@@ -352,6 +471,7 @@ class GLM5Renderer:
preserve_thinking: bool = False,
emit_special,
emit_text,
emit_text_segments,
):
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
@@ -370,16 +490,25 @@ class GLM5Renderer:
# samples it. Same for the ``<think>`` open / standalone
# ``</think>`` separator that the template wraps around the
# assistant body — see the per-branch comments below.
emit_special(self._assistant, msg_idx, is_sampled=False)
#
# Invariant on assistant tokens: ``is_content == sampled_mask``.
# Every scaffold token here gets ``is_sampled=False/is_content=False``;
# every model-sampled emit gets both True.
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
# Chat-template default: keep ``<think>`` only on the in-flight cycle
# (post-last-user). Past-cycle assistants drop their reasoning.
# ``preserve_thinking`` is the override output of
# ``should_preserve_past_thinking`` — it adds historical assistants
# back when the renderer was constructed with
# ``preserve_all_thinking=True``.
# ``preserve_all_thinking=True``. ``clear_thinking=False`` mirrors
# the template's per-call ``clear_thinking is defined and not
# clear_thinking`` gate: a chat_template_kwarg surface for the
# same behaviour, gated explicitly by the caller per render.
include_thinking = (
msg_idx > last_user_index or preserve_thinking
msg_idx > last_user_index
or preserve_thinking
or not self.config.clear_thinking
) and reasoning_content
if include_thinking:
@@ -387,36 +516,50 @@ class GLM5Renderer:
# inference (gen prompt = ``<|assistant|><think>``), so it's
# template-injected scaffolding. The reasoning text and the
# closing ``</think>`` are what the model actually samples.
emit_special(self._think, msg_idx, is_sampled=False)
emit_text(reasoning_content.strip(), msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
elif self.empty_think_on_last_assistant and msg_idx > last_user_index:
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
emit_text(
reasoning_content.strip(), msg_idx, is_sampled=True, is_content=True
)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
elif (
self.empty_think_on_last_assistant
and msg_idx > last_user_index
and self.config.enable_thinking
):
# GLM-5.1: wrap the last assistant with an empty <think></think>
# even without reasoning, matching the Jinja template. With
# ``enable_thinking=True`` the gen prompt already includes
# ``<think>``; the model then samples ``</think>`` to close an
# empty think block. So ``<think>`` is scaffolding,
# ``</think>`` is sampled.
emit_special(self._think, msg_idx, is_sampled=False)
emit_special(self._think_end, msg_idx, is_sampled=True)
#
# When ``enable_thinking=False`` the GLM-5.1 template skips
# the opening ``<think>`` for the most-recent assistant too
# — it emits only the lone ``</think>`` separator (and the
# gen prompt likewise switches to ``</think>``). Fall
# through to the else branch below so we match.
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
else:
# Lone ``</think>`` separator the template injects when no
# reasoning is rendered (historical assistants, GLM-5 default
# with no thinking). Not sampled.
emit_special(self._think_end, msg_idx, is_sampled=False)
emit_special(self._think_end, msg_idx, is_sampled=False, is_content=False)
if content.strip():
emit_text(content.strip(), msg_idx, is_sampled=True)
emit_text(content.strip(), msg_idx, is_sampled=True, is_content=True)
# Tool calls (directly after content, no newlines)
# Tool calls (directly after content, no newlines). All of these
# are the model's sampled output — both is_sampled and is_content
# are True across the entire tool-call span.
tool_calls = msg.get("tool_calls") or []
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
emit_special(self._tool_call_tok, msg_idx, is_sampled=True)
emit_text(name, msg_idx, is_sampled=True)
emit_special(self._tool_call_tok, msg_idx, is_sampled=True, is_content=True)
emit_text(name, msg_idx, is_sampled=True, is_content=True)
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
@@ -426,20 +569,31 @@ class GLM5Renderer:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
emit_special(self._arg_key, msg_idx, is_sampled=True)
emit_text(arg_name, msg_idx, is_sampled=True)
emit_special(self._arg_key_end, msg_idx, is_sampled=True)
emit_special(self._arg_value, msg_idx, is_sampled=True)
emit_special(
self._arg_key, msg_idx, is_sampled=True, is_content=True
)
emit_text(arg_name, msg_idx, is_sampled=True, is_content=True)
emit_special(
self._arg_key_end, msg_idx, is_sampled=True, is_content=True
)
emit_special(
self._arg_value, msg_idx, is_sampled=True, is_content=True
)
if isinstance(arg_value, str):
emit_text(arg_value, msg_idx, is_sampled=True)
emit_text(arg_value, msg_idx, is_sampled=True, is_content=True)
else:
emit_text(
json.dumps(arg_value, ensure_ascii=False),
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._arg_value_end, msg_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, msg_idx, is_sampled=True)
emit_special(
self._arg_value_end, msg_idx, is_sampled=True, is_content=True
)
emit_special(
self._tool_call_end_tok, msg_idx, is_sampled=True, is_content=True
)
def _render_tool(
self,
@@ -449,18 +603,34 @@ class GLM5Renderer:
*,
emit_special,
emit_text,
emit_text_segments,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
# Tool body bytes get ``is_content=True``; the wraps are
# scaffold. The ``<|observation|>`` role tag is scaffold too
# (``is_content=False`` so ``content_mask_for_roles({"tool"})``
# excludes it). When the previous message is an assistant it
# doubles as the inference stop signal for that assistant's
# turn — mark it ``is_sampled=True`` so SFT trains the model to
# emit it after ``</tool_call>``. The token stays attributed to
# this tool message; byte stream is unchanged.
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
closes_assistant_turn = prev_role == "assistant"
if not prev_is_tool:
emit_special(self._observation, msg_idx, is_sampled=False)
if prev_role != "tool":
emit_special(
self._observation,
msg_idx,
is_sampled=closes_assistant_turn,
is_content=False,
)
emit_special(self._tool_response_tok, msg_idx, is_sampled=False)
emit_text(content, msg_idx, is_sampled=False)
emit_special(self._tool_response_end_tok, msg_idx, is_sampled=False)
emit_special(
self._tool_response_tok, msg_idx, is_sampled=False, is_content=False
)
emit_text(content, msg_idx, is_sampled=False, is_content=True)
emit_special(
self._tool_response_end_tok, msg_idx, is_sampled=False, is_content=False
)
class GLM51Renderer(GLM5Renderer):
@@ -478,6 +648,7 @@ class GLM51Renderer(GLM5Renderer):
"""
empty_think_on_last_assistant = True
_config_cls = GLM51RendererConfig
@staticmethod
def _format_tool_spec(tool: ToolSpec) -> str:
+233 -51
View File
@@ -56,10 +56,12 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import GptOssRendererConfig
from renderers.parsing import parse_gpt_oss
@@ -121,44 +123,27 @@ class GptOssRenderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
use_system_prompt: bool = True,
reasoning_effort: str | None = "medium",
conversation_start_date: str | None = None,
knowledge_cutoff: str | None = None,
model_identity: str | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: GptOssRendererConfig | None = None,
):
"""Initialise the renderer.
Args:
tokenizer: HuggingFace tokenizer.
use_system_prompt: When True (default), prepend the canonical
harmony SystemContent preamble. Matches HF's
apply_chat_template behaviour.
reasoning_effort: ``"low" | "medium" | "high"``. Default
``"medium"`` (matches apply_chat_template).
conversation_start_date: Optional ISO date for the preamble.
Defaults to today's date in YYYY-MM-DD form.
knowledge_cutoff: Optional knowledge cutoff string. Harmony's
default is built into ``SystemContent.new()``.
model_identity: Optional override for the model identity line.
config: Typed renderer config (see
:class:`renderers.GptOssRendererConfig`).
"""
self._tokenizer = tokenizer
self.config = config or GptOssRendererConfig()
self._enc: HarmonyEncoding = load_harmony_encoding(
HarmonyEncodingName.HARMONY_GPT_OSS
)
self._use_system_prompt = use_system_prompt
self._reasoning_effort = _reasoning_effort(reasoning_effort)
self._conversation_start_date = (
conversation_start_date or datetime.now().strftime("%Y-%m-%d")
)
self._knowledge_cutoff = knowledge_cutoff
self._model_identity = model_identity
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
# Materialised harmony-enum form of reasoning_effort.
self._reasoning_effort_enum = _reasoning_effort(self.config.reasoning_effort)
# ``conversation_start_date=None`` defers to today's date —
# materialise once at construction so renders within the same
# instance use a stable date.
self._conversation_start_date_resolved = (
self.config.conversation_start_date or datetime.now().strftime("%Y-%m-%d")
)
# Cache special-token IDs for the bridge / generation-prompt path.
@@ -184,6 +169,90 @@ class GptOssRenderer:
return []
return self._tokenizer.encode(text, add_special_tokens=False)
def _prefix_content_mask(
self,
prefix_tokens: list[int],
first_system_idx: int | None,
messages: list[Message],
tools: list[ToolSpec] | None,
) -> list[bool]:
"""Per-token is_content mask over the rendered system+developer prefix.
Harmony's prefix is one opaque block. The caller's system content
lands inside the developer message as ``# Instructions\\n\\n{content}``.
To attribute body bytes back, we render the same prefix with empty
instructions and diff: the unique-to-with-instructions span is the
body region. Falls back to all-False (whole prefix scaffold) if
the caller didn't supply a system message — there's no body to
attribute in that case.
"""
n = len(prefix_tokens)
mask = [False] * n
if first_system_idx is None:
return mask
instructions = _content_text(messages[first_system_idx].get("content"))
if not instructions:
return mask
# Build the same prefix with empty instructions.
empty_prefix_msgs: list[HarmonyMessage] = []
if self.config.use_system_prompt:
sys_content = SystemContent.new().with_reasoning_effort(
self._reasoning_effort_enum
)
sys_content = sys_content.with_conversation_start_date(
self._conversation_start_date_resolved
)
if self.config.knowledge_cutoff is not None:
sys_content = sys_content.with_knowledge_cutoff(
self.config.knowledge_cutoff
)
if self.config.model_identity is not None:
sys_content = sys_content.with_model_identity(
self.config.model_identity
)
empty_prefix_msgs.append(
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
)
dev = DeveloperContent.new()
if tools:
dev = dev.with_function_tools([_tool_to_description(t) for t in tools])
empty_prefix_msgs.append(
HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev)
)
try:
empty_tokens = self._enc.render_conversation(
Conversation.from_messages(empty_prefix_msgs)
)
except Exception:
return mask
# Longest common prefix.
i_start = 0
n_empty = len(empty_tokens)
while (
i_start < min(n, n_empty)
and prefix_tokens[i_start] == empty_tokens[i_start]
):
i_start += 1
# Longest common suffix.
j_full = n
j_empty = n_empty
while (
j_full > i_start
and j_empty > i_start
and prefix_tokens[j_full - 1] == empty_tokens[j_empty - 1]
):
j_full -= 1
j_empty -= 1
# Tokens [i_start:j_full] in prefix_tokens are unique to the
# with-instructions render — that's the body span (includes the
# ``# Instructions\n\n`` scaffolding header, which the substring
# match in the body-decode test ignores).
for k in range(i_start, j_full):
mask[k] = True
return mask
# ── public interface ─────────────────────────────────────────────────────
def render(
@@ -199,11 +268,15 @@ class GptOssRenderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
def emit(
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_harmony_message(
hm_ids: list[int], msg_idx: int, *, is_assistant: bool
@@ -225,18 +298,53 @@ class GptOssRenderer:
developer, tool) the whole message is conversation history
the model never samples — every token is
``is_sampled=False``.
``is_content`` further splits the body: the trailing
terminator (``<|end|>`` / ``<|return|>`` / ``<|call|>``) is
scaffold on non-assistant turns; on assistant turns it's the
model's stop signal, so ``is_content=True`` mirrors
``sampled_mask`` as the invariant on assistant requires.
The body bytes between ``<|message|>`` and the terminator
are body (``is_content=True``) on every role — that's the
caller-provided content (or, for assistant, the model's
sampled emission). The header (``<|start|>`` ... ``<|message|>``)
— including any ``functions.{name}`` recipient text on tool
results, which comes from a prior assistant's tool_calls
rather than this tool message's own content — is scaffold.
"""
try:
msg_marker = hm_ids.index(self._message)
except ValueError:
# Defensive: a harmony message without <|message|> is
# malformed. Treat the whole thing as scaffolding.
emit(hm_ids, msg_idx, is_sampled=False)
emit(hm_ids, msg_idx, is_sampled=False, is_content=False)
return
header = hm_ids[: msg_marker + 1]
body = hm_ids[msg_marker + 1 :]
emit(header, msg_idx, is_sampled=False)
emit(body, msg_idx, is_sampled=is_assistant)
emit(header, msg_idx, is_sampled=False, is_content=False)
# Split body into content + terminator. The terminator (if
# present) is the last token of the body and is one of the
# three harmony stop tokens.
terminator_ids = {self._end, self._return, self._call}
if body and body[-1] in terminator_ids:
body_content = body[:-1]
terminator = body[-1:]
else:
body_content = body
terminator = []
emit(
body_content,
msg_idx,
is_sampled=is_assistant,
is_content=True,
)
if terminator:
emit(
terminator,
msg_idx,
is_sampled=is_assistant,
is_content=is_assistant,
)
# ── Build harmony prefix (system + developer) ───────────────────
# When tools are present, harmony's conversation-level renderer
@@ -250,17 +358,21 @@ class GptOssRenderer:
None,
)
prefix_msgs: list[HarmonyMessage] = []
if self._use_system_prompt:
if self.config.use_system_prompt:
sys_content = SystemContent.new().with_reasoning_effort(
self._reasoning_effort
self._reasoning_effort_enum
)
sys_content = sys_content.with_conversation_start_date(
self._conversation_start_date
self._conversation_start_date_resolved
)
if self._knowledge_cutoff is not None:
sys_content = sys_content.with_knowledge_cutoff(self._knowledge_cutoff)
if self._model_identity is not None:
sys_content = sys_content.with_model_identity(self._model_identity)
if self.config.knowledge_cutoff is not None:
sys_content = sys_content.with_knowledge_cutoff(
self.config.knowledge_cutoff
)
if self.config.model_identity is not None:
sys_content = sys_content.with_model_identity(
self.config.model_identity
)
prefix_msgs.append(
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
)
@@ -285,7 +397,23 @@ class GptOssRenderer:
# caller-relative attribution); otherwise to -1 (pure scaffolding).
# The whole prefix is pure template scaffolding — never sampled.
prefix_origin = first_system_idx if first_system_idx is not None else -1
emit(prefix_tokens, prefix_origin, is_sampled=False)
# Compute the body-token span inside the prefix by diffing
# against the same render with empty developer instructions.
# Tokens unique to the with-instructions render are the body
# span (``# Instructions\n\n{caller_system_content}``). Marking
# those is_content=True so the caller's system text is
# recoverable from ``content_token_spans_by_role()["system"]``.
# The scaffolding ``# Instructions\n\n`` prefix bleeds into
# the body run; consumers reading the body do a substring
# check rather than expecting an exact match.
prefix_content_mask = self._prefix_content_mask(
prefix_tokens, first_system_idx, messages, tools
)
for tid, is_content in zip(prefix_tokens, prefix_content_mask):
tokens.append(tid)
indices.append(prefix_origin)
sampled.append(False)
content_mask.append(is_content)
# ── Iterate the rest of the messages ────────────────────────────
last_idx = len(messages) - 1
@@ -297,8 +425,8 @@ class GptOssRenderer:
should_preserve_past_thinking(
messages,
i,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
)
for hm in self._to_harmony_messages(
@@ -326,14 +454,19 @@ class GptOssRenderer:
# ── Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
# Pure template scaffolding the model continues from — never sampled.
if add_generation_prompt:
emit([self._start], -1, is_sampled=False)
emit(self._encode("assistant"), -1, is_sampled=False)
emit([self._channel], -1, is_sampled=False)
emit(self._encode("analysis"), -1, is_sampled=False)
emit([self._message], -1, is_sampled=False)
emit([self._start], -1, is_sampled=False, is_content=False)
emit(self._encode("assistant"), -1, is_sampled=False, is_content=False)
emit([self._channel], -1, is_sampled=False, is_content=False)
emit(self._encode("analysis"), -1, is_sampled=False, is_content=False)
emit([self._message], -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -400,22 +533,71 @@ class GptOssRenderer:
if previous_ids is None:
return None
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False``). The harmony encoder
# renders each ``new_messages[i]`` as a single block, so every
# token in that block carries index ``i``; the trailing
# generation prompt uses ``-1``. ``is_content`` follows the same
# rules as :meth:`render`'s ``emit_harmony_message``: header is
# scaffold, body bytes are body, terminator scaffold (the bridge
# never carries assistant turns, so terminators are always
# scaffold on the non-assistant roles the bridge accepts).
terminator_ids = {self._end, self._return, self._call}
ext: list[int] = []
for msg in new_messages:
ext_indices: list[int] = []
ext_content: list[bool] = []
for i, msg in enumerate(new_messages):
role = msg.get("role")
if role not in ("tool", "user", "system", "developer"):
return None
for hm in self._to_harmony_messages(msg):
ext.extend(self._enc.render(hm))
ids = self._enc.render(hm)
try:
msg_marker = ids.index(self._message)
except ValueError:
# Defensive: treat as scaffolding.
ext.extend(ids)
ext_indices.extend([i] * len(ids))
ext_content.extend([False] * len(ids))
continue
header = ids[: msg_marker + 1]
body = ids[msg_marker + 1 :]
ext.extend(header)
ext_indices.extend([i] * len(header))
ext_content.extend([False] * len(header))
if body and body[-1] in terminator_ids:
body_content = body[:-1]
terminator = body[-1:]
else:
body_content = body
terminator = []
ext.extend(body_content)
ext_indices.extend([i] * len(body_content))
ext_content.extend([True] * len(body_content))
if terminator:
ext.extend(terminator)
ext_indices.extend([i] * len(terminator))
ext_content.extend([False] * len(terminator))
# Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
gen_before = len(ext)
ext.append(self._start)
ext.extend(self._encode("assistant"))
ext.append(self._channel)
ext.extend(self._encode("analysis"))
ext.append(self._message)
ext_indices.extend([-1] * (len(ext) - gen_before))
ext_content.extend([False] * (len(ext) - gen_before))
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
# ── message conversion ───────────────────────────────────────────────────
+202 -88
View File
@@ -23,34 +23,33 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
extract_message_tool_names,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.configs import KimiK2RendererConfig
from renderers.parsing import parse_kimi_k2
_DEFAULT_SYSTEM = "You are Kimi, an AI assistant created by Moonshot AI."
class KimiK2Renderer:
"""Deterministic message → token renderer for Kimi K2 models."""
"""Deterministic message → token renderer for Kimi K2 models.
Kimi K2's chat template doesn't read any thinking-related variable —
``content`` renders verbatim with no reasoning branch. The
``enable_thinking`` / ``preserve_*`` fields on the config are stored
for protocol uniformity with the rest of the renderer family but
have no effect on the byte-level output.
"""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: KimiK2RendererConfig | None = None,
):
# Kimi-K2's chat template doesn't read ``reasoning_content`` for
# past assistant turns, so the override flags are no-ops. Stored
# for introspection / Protocol parity only.
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or KimiK2RendererConfig()
self._im_user = self._token_id("<|im_user|>")
self._im_assistant = self._token_id("<|im_assistant|>")
@@ -118,6 +117,11 @@ class KimiK2Renderer:
if not messages:
raise ValueError("No messages provided.")
# Preserve the caller's list — ``message_roles`` and per-token
# attribution refer to this frame (not the post-normalisation
# list that includes auto-injected system / tool_declare).
caller_messages = list(messages)
# Inject tools as tool_declare message + ensure system message.
# The Jinja template emits the tools list directly (no
# ``{"type":"function","function":...}`` wrapper) using
@@ -166,19 +170,33 @@ class KimiK2Renderer:
token_ids: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
def emit_ids(
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
token_ids.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
token_ids.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
emit_ids(
self._encode(text),
msg_idx,
is_sampled=is_sampled,
is_content=is_content,
)
# Compute last non-tool-call assistant index to determine thinking preservation
last_plain_assistant_idx = -1
@@ -206,31 +224,40 @@ class KimiK2Renderer:
content = "".join(parts)
oi = orig_idx(i)
# Auto-injected system / tool_declare messages have ``oi == -1``.
# Their text isn't from the caller's input, so we treat the
# whole emission as scaffold (``is_content=False`` everywhere).
# The test contract is that ``msg_idx == -1`` runs are
# template-only and ``is_content=False``.
body_is_content = oi >= 0
if role == "system":
emit_special(self._im_system, oi, is_sampled=False)
emit_text("system", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
emit_special(self._im_system, oi, is_sampled=False, is_content=False)
emit_text("system", oi, is_sampled=False, is_content=False)
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
# Jinja emits a literal newline only after the auto-injected
# system's <|im_end|> (see _ensure_system_message's contract).
if i == auto_system_idx:
emit_text("\n", oi, is_sampled=False)
emit_text("\n", oi, is_sampled=False, is_content=False)
elif role == "tool_declare":
emit_special(self._im_system, oi, is_sampled=False)
emit_text("tool_declare", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
# The tool_declare body is the tools JSON — recoverable
# from the caller's ``tools`` argument, so we treat it as
# scaffold (consistent with Qwen3's tools-header block).
emit_special(self._im_system, oi, is_sampled=False, is_content=False)
emit_text("tool_declare", oi, is_sampled=False, is_content=False)
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
emit_text(content, oi, is_sampled=False, is_content=False)
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
elif role == "user":
emit_special(self._im_user, oi, is_sampled=False)
emit_text("user", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
emit_special(self._im_user, oi, is_sampled=False, is_content=False)
emit_text("user", oi, is_sampled=False, is_content=False)
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
elif role == "assistant":
# Kimi strips reasoning from historical assistant turns and
@@ -250,27 +277,36 @@ class KimiK2Renderer:
elif role == "tool":
self._render_tool(
msg, oi, content, emit_special=emit_special, emit_text=emit_text
msg,
oi,
content,
emit_special=emit_special,
emit_text=emit_text,
)
else:
# Unknown role: use system-style formatting. Not a sampled
# assistant turn — every token is template-injected from the
# caller's POV, so is_sampled=False across the whole emission.
emit_special(self._im_system, oi, is_sampled=False)
emit_text(role, oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
emit_special(self._im_system, oi, is_sampled=False, is_content=False)
emit_text(role, oi, is_sampled=False, is_content=False)
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
# Generation prompt
if add_generation_prompt:
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
emit_special(self._im_assistant, -1, is_sampled=False, is_content=False)
emit_text("assistant", -1, is_sampled=False, is_content=False)
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=token_ids, message_indices=indices, sampled_mask=sampled
token_ids=token_ids,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in caller_messages],
message_tool_names=extract_message_tool_names(caller_messages),
)
def render_ids(
@@ -331,21 +367,42 @@ class KimiK2Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
ext_content: list[bool] = []
# Bridge output is consumed as the next turn's prompt — the caller
# blanket-masks it via ``prompt_mask=[False]*N``, so we don't track
# sampled_mask here. Local helpers accept the kwarg for signature
# compatibility with ``_render_tool`` and ignore it; the returned
# ``RenderedTokens`` leaves ``sampled_mask`` empty.
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask. Downstream consumers can
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
# output to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.extend(self._encode(text))
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([is_content] * len(ids))
for i, msg in enumerate(new_messages):
role = msg.get("role")
@@ -365,30 +422,42 @@ class KimiK2Renderer:
content = "".join(parts)
if role == "user":
emit_special(self._im_user, i, is_sampled=False)
emit_text("user", i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_special(self._im_user, i)
emit_text("user", i)
emit_special(self._im_middle, i)
emit_text(content, i, is_content=True)
emit_special(self._im_end, i)
elif role == "system":
emit_special(self._im_system, i, is_sampled=False)
emit_text("system", i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_special(self._im_system, i)
emit_text("system", i)
emit_special(self._im_middle, i)
emit_text(content, i, is_content=True)
emit_special(self._im_end, i)
elif role == "tool":
self._render_tool(
msg, i, content, emit_special=emit_special, emit_text=emit_text
msg,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
)
else:
return None
# Generation prompt.
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
self,
@@ -404,23 +473,32 @@ class KimiK2Renderer:
# scaffolding — at inference the chat template emits these as the
# generation prompt and the model never samples them. Marking the
# role tag as ``is_sampled=False`` keeps the SFT loss mask aligned
# with what the model would actually have produced.
emit_special(self._im_assistant, msg_idx, is_sampled=False)
emit_text("assistant", msg_idx, is_sampled=False)
emit_special(self._im_middle, msg_idx, is_sampled=False)
# with what the model would actually have produced. ``is_content``
# is also False here — the role tag isn't part of any message's
# body, on any role.
emit_special(self._im_assistant, msg_idx, is_sampled=False, is_content=False)
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
emit_special(self._im_middle, msg_idx, is_sampled=False, is_content=False)
# Kimi K2's Jinja template has no reasoning-content support: the
# assistant turn renders its ``content`` verbatim, including any
# inline ``<think>...</think>`` tags. The separate
# ``reasoning_content`` field is dropped (the template never reads
# it). ``is_last_turn`` is unused here for the same reason.
# On assistant tokens, ``is_content == sampled_mask`` by construction
# — every sampled token is body, every scaffold token isn't.
_ = is_last_turn
emit_text(content, msg_idx, is_sampled=True)
emit_text(content, msg_idx, is_sampled=True, is_content=True)
# Tool calls
# Tool calls — model-sampled markup carrying caller / model body.
tool_calls = msg.get("tool_calls") or []
if tool_calls:
emit_special(self._tool_calls_section_begin, msg_idx, is_sampled=True)
emit_special(
self._tool_calls_section_begin,
msg_idx,
is_sampled=True,
is_content=True,
)
for tc in tool_calls:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
@@ -434,16 +512,37 @@ class KimiK2Renderer:
# caller to provide an id in ``functions.{name}:{idx}`` form
# (that's where the Kimi parser recovers the function name).
tc_id = tc.get("id") or ""
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text(tc_id, msg_idx, is_sampled=True)
emit_special(self._tool_call_argument_begin, msg_idx, is_sampled=True)
emit_text(args_str, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_section_end, msg_idx, is_sampled=True)
emit_special(
self._tool_call_begin,
msg_idx,
is_sampled=True,
is_content=True,
)
emit_text(tc_id, msg_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_argument_begin,
msg_idx,
is_sampled=True,
is_content=True,
)
emit_text(args_str, msg_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_end,
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(
self._tool_calls_section_end,
msg_idx,
is_sampled=True,
is_content=True,
)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream.
emit_special(self._im_end, msg_idx, is_sampled=True)
# end its turn, so it is part of the sampled stream (and the
# assistant's body).
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
def _render_tool(
self,
@@ -456,13 +555,28 @@ class KimiK2Renderer:
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
# tokens, so every emission is is_sampled=False. The ``content``
# field's body bytes get ``is_content=True``; everything else —
# the ``<|im_system|>name<|im_middle|>`` wrap, the ``## Return of
# …\n`` header (template-synthesised, not part of the body) —
# is scaffold so the SFT mask for tool body never trains the
# model to emit them.
#
# We keep the original kimi_k2 emit boundaries — the header and
# the content are encoded separately, which preserves the
# template's byte-identity since the original code also emitted
# them as separate ``encode`` calls.
name = msg.get("name") or "tool"
tool_call_id = msg.get("tool_call_id") or ""
emit_special(self._im_system, msg_idx, is_sampled=False)
emit_text(name, msg_idx, is_sampled=False)
emit_special(self._im_middle, msg_idx, is_sampled=False)
emit_text(f"## Return of {tool_call_id}\n", msg_idx, is_sampled=False)
emit_text(content, msg_idx, is_sampled=False)
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_special(self._im_system, msg_idx, is_sampled=False, is_content=False)
emit_text(name, msg_idx, is_sampled=False, is_content=False)
emit_special(self._im_middle, msg_idx, is_sampled=False, is_content=False)
emit_text(
f"## Return of {tool_call_id}\n",
msg_idx,
is_sampled=False,
is_content=False,
)
emit_text(content, msg_idx, is_sampled=False, is_content=True)
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
+250 -95
View File
@@ -36,11 +36,13 @@ from renderers.base import (
RenderedTokens,
ToolCallParseStatus,
ToolSpec,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.parsing import parse_kimi_k2_section
from renderers.configs import KimiK25RendererConfig
from renderers.parsing import _reasoning_end_token_index, parse_kimi_k2_section
from renderers.qwen3_vl import (
_image_hash,
_is_image_part,
@@ -213,7 +215,9 @@ class _EnumType(_BaseType):
self.enum = schema["enum"]
def to_typescript_style(self, indent: str = "") -> str:
return " | ".join(f'"{e}"' if isinstance(e, str) else str(e) for e in self.enum)
return " | ".join(
f'"{e}"' if isinstance(e, str) else json.dumps(e) for e in self.enum
)
class _AnyOfType(_BaseType):
@@ -283,11 +287,7 @@ class _TypedParam:
def to_typescript_style(self, indent: str = "") -> str:
comments = self.type_.format_docstring(indent)
if self.default is not None:
default_repr = (
json.dumps(self.default, ensure_ascii=False)
if not isinstance(self.default, (int, float, bool))
else repr(self.default)
)
default_repr = json.dumps(self.default, ensure_ascii=False)
comments += f"{indent}// Default: {default_repr}\n"
opt = "?" if self.optional else ""
return (
@@ -452,6 +452,13 @@ def _parse_kimi_k2_response(
ids = ids[:i]
break
# Reasoning first: a tool-call section the model drafts *inside* its
# <think> trace must not be parsed as a real call (regression #78 — cf.
# parse_qwen3). K2.5 renders </think> as text, so locate the boundary by
# decoding; the section scan then starts past it. content_ids still begins
# at 0, so the </think> text-split below recovers reasoning unchanged.
reasoning_end = _reasoning_end_token_index(tokenizer, ids)
# Token-ID path — produces spans. Only run if every relevant special
# token resolved at init (i.e. is in the tokenizer's vocab).
tool_calls: list[ParsedToolCall] = []
@@ -471,6 +478,7 @@ def _parse_kimi_k2_response(
tool_call_begin_id=tool_call_begin_id,
tool_call_argument_begin_id=tool_call_argument_begin_id,
tool_call_end_id=tool_call_end_id,
scan_start=reasoning_end,
)
text = (
tokenizer.decode(content_ids, skip_special_tokens=False)
@@ -481,9 +489,13 @@ def _parse_kimi_k2_response(
text = tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
# Fallback path: model emitted literal-text section delimiters (singular
# variant) rather than special tokens. Spans unavailable here.
# variant) rather than special tokens. Spans unavailable here. Start the
# search past the first </think> so a literal section drafted inside the
# reasoning trace isn't matched as a real call (regression #78).
if not tool_calls:
tc_match = _TOOL_CALLS_SECTION_RE.search(text)
think_close = text.find("</think>")
search_from = think_close + len("</think>") if think_close != -1 else 0
tc_match = _TOOL_CALLS_SECTION_RE.search(text, search_from)
if tc_match:
text = text[: tc_match.start()]
tool_section = (
@@ -564,8 +576,13 @@ class KimiK25Renderer:
"""Deterministic message → token renderer for Kimi K2.5 models.
Renders to the same ``<|im_*|>`` format as Kimi K2 but adds:
- Generation prompt prefills ``<think>`` (enable_thinking=True, default) or
``<think></think>`` (enable_thinking=False) to control thinking mode.
- Generation prompt prefills ``<think>`` (thinking=True, default) or
``<think></think>`` (thinking=False) to control thinking mode. The
template's native kwarg name is ``thinking`` (not the more common
``enable_thinking``); we mirror it on
:class:`renderers.KimiK25RendererConfig` so
``KimiK25RendererConfig(thinking=False)`` produces the same tokens
as ``apply_chat_template(..., thinking=False)``.
- Image content rendering via ``<|media_begin|>image<|media_content|>...<|media_end|>``.
- TypeScript-style tool declarations instead of JSON.
@@ -575,20 +592,13 @@ class KimiK25Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: KimiK25RendererConfig | None = None,
*,
processor: Any = None,
enable_thinking: bool = True,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
image_cache_max: int = 256,
):
self._tokenizer = tokenizer
self._processor = processor
self._enable_thinking = enable_thinking
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or KimiK25RendererConfig()
# Core structural tokens — all must be single special tokens in the vocab
self._im_user = self._token_id("<|im_user|>")
@@ -629,7 +639,6 @@ class KimiK25Renderer:
# for Kimi (we emit a single placeholder regardless), but kept for
# consistency / debugging.
self._image_cache: dict[str, tuple[Any, int]] = {}
self._image_cache_max = image_cache_max
@property
def mm_token_type_id_map(self) -> dict[int, int]:
@@ -681,7 +690,7 @@ class KimiK25Renderer:
# Patch count via the processor's own calculator (matches the
# model's per-patch attention count); kept for debugging.
num_patches = int(img_proc.media_tokens_calculator(media_item))
if len(self._image_cache) >= self._image_cache_max:
if len(self._image_cache) >= self.config.image_cache_max:
self._image_cache.pop(next(iter(self._image_cache)))
self._image_cache[h] = (out, num_patches)
return pil, out, num_patches, h
@@ -749,24 +758,44 @@ class KimiK25Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
mm_hashes: dict[str, list[str]] = {}
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
mm_items: dict[str, list[dict[str, Any]]] = {}
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
def emit_ids(
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
emit_ids(
self._encode(text),
msg_idx,
is_sampled=is_sampled,
is_content=is_content,
)
def emit_image(part: dict[str, Any], msg_idx: int, *, is_sampled: bool) -> None:
def emit_image(
part: dict[str, Any],
msg_idx: int,
*,
is_sampled: bool,
is_content: bool,
) -> None:
"""Emit Kimi K2.5's image wrap and accumulate ``mm_data``.
Template-equivalent expansion per image:
@@ -779,15 +808,32 @@ class KimiK25Renderer:
Kimi's chat template after every image — kept here verbatim
for byte-parity, regardless of what follows (more images,
text, or the ``<|im_end|>`` close).
``is_content`` attribution: ``<|media_pad|>`` represents
caller-provided image data — body. The wrap tokens
(``<|media_begin|>``, the literal ``"image"`` prose,
``<|media_content|>``, ``<|media_end|>``, the trailing
``\\n``) are template-injected scaffold.
"""
_, out, _num_patches, h = self._process_image(part)
emit_special(self._media_begin, msg_idx, is_sampled=is_sampled)
emit_text("image", msg_idx, is_sampled=is_sampled)
emit_special(self._media_content, msg_idx, is_sampled=is_sampled)
emit_special(
self._media_begin, msg_idx, is_sampled=is_sampled, is_content=False
)
emit_text("image", msg_idx, is_sampled=is_sampled, is_content=False)
emit_special(
self._media_content, msg_idx, is_sampled=is_sampled, is_content=False
)
offset = len(tokens)
emit_special(self._media_pad, msg_idx, is_sampled=is_sampled)
emit_special(self._media_end, msg_idx, is_sampled=is_sampled)
emit_text("\n", msg_idx, is_sampled=is_sampled)
emit_special(
self._media_pad,
msg_idx,
is_sampled=is_sampled,
is_content=is_content,
)
emit_special(
self._media_end, msg_idx, is_sampled=is_sampled, is_content=False
)
emit_text("\n", msg_idx, is_sampled=is_sampled, is_content=False)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=1)
@@ -807,13 +853,16 @@ class KimiK25Renderer:
# K2.5/K2.6's tokenizer auto-computes ``tools_ts_str`` and threads
# it into apply_chat_template, so the template's TS branch always
# fires when tools are present. Match that with our own TS encoder.
# The tools-TS body is recoverable from the ``tools`` argument, so
# we attribute the entire tool_declare emission as scaffold —
# consistent with Qwen3's tools-header treatment.
if tools:
tools_ts = _encode_tools_typescript(tools)
emit_special(self._im_system, -1, is_sampled=False)
emit_text("tool_declare", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
emit_text(tools_ts, -1, is_sampled=False)
emit_special(self._im_end, -1, is_sampled=False)
emit_special(self._im_system, -1, is_sampled=False, is_content=False)
emit_text("tool_declare", -1, is_sampled=False, is_content=False)
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
emit_text(tools_ts, -1, is_sampled=False, is_content=False)
emit_special(self._im_end, -1, is_sampled=False, is_content=False)
# ── Iterate messages ─────────────────────────────────────────
for i, msg in enumerate(messages):
@@ -824,14 +873,14 @@ class KimiK25Renderer:
# generation prompt emits them at inference for assistants;
# user / system / tool roles are conversation history).
if role == "user":
emit_special(self._im_user, i, is_sampled=False)
emit_special(self._im_user, i, is_sampled=False, is_content=False)
elif role == "assistant":
emit_special(self._im_assistant, i, is_sampled=False)
emit_special(self._im_assistant, i, is_sampled=False, is_content=False)
else:
emit_special(self._im_system, i, is_sampled=False)
emit_special(self._im_system, i, is_sampled=False, is_content=False)
role_name = msg.get("name") or role
emit_text(role_name, i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
emit_text(role_name, i, is_sampled=False, is_content=False)
emit_special(self._im_middle, i, is_sampled=False, is_content=False)
# Body
if role == "assistant":
@@ -839,8 +888,8 @@ class KimiK25Renderer:
preserve_thinking = should_preserve_past_thinking(
messages,
i,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
self._render_assistant_body(
msg,
@@ -852,10 +901,10 @@ class KimiK25Renderer:
)
# ``<|im_end|>`` is the model's stop signal — it samples
# this to end its turn, so it is part of the sampled
# stream. Kimi K2.5 has no inter-turn ``\n`` separator
# (unlike Qwen3), so the turn-close token is the last
# sampled token.
emit_special(self._im_end, i, is_sampled=True)
# stream (and the assistant's body). Kimi K2.5 has no
# inter-turn ``\n`` separator (unlike Qwen3), so the
# turn-close token is the last sampled token.
emit_special(self._im_end, i, is_sampled=True, is_content=True)
continue
elif role == "tool":
self._render_tool_body(
@@ -869,7 +918,8 @@ class KimiK25Renderer:
elif msg.get("content") is not None:
# User / other content branches — images allowed. All
# non-assistant content is conversation history, never
# sampled by the model.
# sampled by the model. The body is caller-provided, so
# ``is_content=True`` over the content emit.
self._emit_content(
msg.get("content"),
i,
@@ -878,21 +928,22 @@ class KimiK25Renderer:
emit_ids,
emit_image=emit_image,
is_sampled=False,
is_content=True,
)
emit_special(self._im_end, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False, is_content=False)
# ── Generation prompt ────────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._im_assistant, -1, is_sampled=False, is_content=False)
emit_text("assistant", -1, is_sampled=False, is_content=False)
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
if self.config.thinking:
# Prefill open <think> tag to trigger thinking mode
emit_text("<think>", -1, is_sampled=False)
emit_text("<think>", -1, is_sampled=False, is_content=False)
else:
# Empty <think></think> to disable thinking
emit_text("<think></think>", -1, is_sampled=False)
emit_text("<think></think>", -1, is_sampled=False, is_content=False)
mm_data: MultiModalData | None = None
if mm_hashes or mm_placeholders or mm_items:
@@ -906,6 +957,9 @@ class KimiK25Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
multi_modal_data=mm_data,
)
@@ -995,44 +1049,77 @@ class KimiK25Renderer:
return None
# Seed combined-token list with prior turn so placeholder offsets
# are absolute in the bridged sequence.
# are absolute in the bridged sequence. Parallel
# ``indices``/``sampled``/``content_mask`` are seeded with
# ``-1``/``False``/``False`` for the prior portion — the bridge
# has no attribution info for ``previous_ids``. Bridge-added
# tokens get proper ``msg_idx`` (relative to ``new_messages``)
# and uniformly ``False`` ``sampled``: nothing the bridge emits
# was model-sampled. ``is_content`` follows the same rules as in
# :meth:`render` so consumers can walk the trajectory and read
# each step's own body mask.
tokens: list[int] = list(previous_ids)
indices: list[int] = [-1] * len(previous_ids)
sampled: list[bool] = [False] * len(previous_ids)
content_mask: list[bool] = [False] * len(previous_ids)
new_hashes: dict[str, list[str]] = {}
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
# Bridge output is consumed as the next turn's prompt — the caller
# blanket-masks it via ``prompt_mask=[False]*N``, so we don't track
# sampled_mask here. Local helpers accept the kwarg for signature
# compatibility with ``_render_tool_body`` / ``_emit_content`` and
# ignore it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
tokens.extend(self._encode(text))
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_ids(
ids: list[int], _msg_idx: int = -1, *, is_sampled: bool = False
ids: list[int],
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_image(
part: dict[str, Any], _msg_idx: int = -1, *, is_sampled: bool = False
part: dict[str, Any],
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
_, out, _num_patches, h = self._process_image(part)
emit_special(self._media_begin)
emit_text("image")
emit_special(self._media_content)
emit_special(self._media_begin, msg_idx)
emit_text("image", msg_idx)
emit_special(self._media_content, msg_idx)
offset = len(tokens)
emit_special(self._media_pad)
emit_special(self._media_end)
emit_text("\n")
# ``<|media_pad|>`` stands in for caller-provided image data —
# mark it as body when the surrounding content is body.
emit_special(self._media_pad, msg_idx, is_content=is_content)
emit_special(self._media_end, msg_idx)
emit_text("\n", msg_idx)
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=1)
@@ -1077,6 +1164,7 @@ class KimiK25Renderer:
emit_ids,
emit_image=emit_image,
is_sampled=False,
is_content=True,
)
emit_special(self._im_end, i)
@@ -1085,7 +1173,7 @@ class KimiK25Renderer:
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
if self._enable_thinking:
if self.config.thinking:
emit_text("<think>", -1)
else:
emit_text("<think></think>", -1)
@@ -1113,8 +1201,17 @@ class KimiK25Renderer:
for modality, vals in new_items.items():
merged_items.setdefault(modality, []).extend(vals)
bridge_roles = [m.get("role") or "" for m in new_messages]
bridge_tool_names = extract_message_tool_names(new_messages)
if not (merged_hashes or merged_placeholders or merged_items):
return RenderedTokens(token_ids=tokens)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
)
mm_data = MultiModalData(
mm_hashes=merged_hashes,
@@ -1123,7 +1220,11 @@ class KimiK25Renderer:
)
return RenderedTokens(
token_ids=tokens,
message_indices=[-1] * len(tokens),
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
multi_modal_data=mm_data,
)
@@ -1141,6 +1242,7 @@ class KimiK25Renderer:
*,
emit_image=None,
is_sampled: bool,
is_content: bool = True,
) -> None:
"""Emit message content, handling strings, multipart lists, and (when
``emit_image`` is supplied) image parts.
@@ -1155,11 +1257,15 @@ class KimiK25Renderer:
``bridge_to_next_turn``), so consecutive images naturally
produce the template's ``...<|media_end|>\\n<|media_begin|>...``
pattern without an inter-image separator here.
``is_content`` propagates to text emits and to the
``<|media_pad|>`` body token of each image; the surrounding
media wrap tokens are always scaffold (handled by ``emit_image``).
"""
if content is None:
return
if isinstance(content, str):
emit_text(content, msg_idx, is_sampled=is_sampled)
emit_text(content, msg_idx, is_sampled=is_sampled, is_content=is_content)
return
if isinstance(content, list):
for part in content:
@@ -1172,20 +1278,30 @@ class KimiK25Renderer:
if emit_image is None:
# Silently drop — caller didn't opt into multimodal.
continue
emit_image(part, msg_idx, is_sampled=is_sampled)
emit_image(
part, msg_idx, is_sampled=is_sampled, is_content=is_content
)
continue
if is_video:
raise NotImplementedError(
"Video parts are not yet supported by KimiK25Renderer."
)
if ptype == "text":
emit_text(part.get("text", ""), msg_idx, is_sampled=is_sampled)
emit_text(
part.get("text", ""),
msg_idx,
is_sampled=is_sampled,
is_content=is_content,
)
elif ptype == "thinking":
# Thinking parts in non-assistant roles are rendered as text
thinking = part.get("thinking", "")
if thinking:
emit_text(
f"<think>{thinking}</think>", msg_idx, is_sampled=is_sampled
f"<think>{thinking}</think>",
msg_idx,
is_sampled=is_sampled,
is_content=is_content,
)
# Other part types are silently skipped
@@ -1248,16 +1364,27 @@ class KimiK25Renderer:
# block, text content, and any tool_calls section all live in
# the sampled stream. The closing ``<|im_end|>`` is emitted by
# ``render`` (also is_sampled=True; it's the model's stop
# signal).
# signal). On assistant tokens ``is_content == sampled_mask`` by
# construction.
if is_suffix or (preserve_thinking and reasoning_content):
emit_text(f"<think>{reasoning_content}</think>", msg_idx, is_sampled=True)
emit_text(
f"<think>{reasoning_content}</think>",
msg_idx,
is_sampled=True,
is_content=True,
)
else:
emit_text("<think></think>", msg_idx, is_sampled=True)
emit_text(text_content, msg_idx, is_sampled=True)
emit_text("<think></think>", msg_idx, is_sampled=True, is_content=True)
emit_text(text_content, msg_idx, is_sampled=True, is_content=True)
tool_calls = msg.get("tool_calls") or []
if tool_calls:
emit_special(self._tool_calls_section_begin, msg_idx, is_sampled=True)
emit_special(
self._tool_calls_section_begin,
msg_idx,
is_sampled=True,
is_content=True,
)
for tc in tool_calls:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
@@ -1271,12 +1398,32 @@ class KimiK25Renderer:
# ``functions.{name}:{idx}`` form (Kimi's parser recovers
# the function name from that field).
tool_id = tc.get("id") or ""
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text(tool_id, msg_idx, is_sampled=True)
emit_special(self._tool_call_argument_begin, msg_idx, is_sampled=True)
emit_text(args_str, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_section_end, msg_idx, is_sampled=True)
emit_special(
self._tool_call_begin,
msg_idx,
is_sampled=True,
is_content=True,
)
emit_text(tool_id, msg_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_argument_begin,
msg_idx,
is_sampled=True,
is_content=True,
)
emit_text(args_str, msg_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_end,
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(
self._tool_calls_section_end,
msg_idx,
is_sampled=True,
is_content=True,
)
def _render_tool_body(
self,
@@ -1302,9 +1449,16 @@ class KimiK25Renderer:
"""
# Tool messages are conversation-history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
# tokens, so every emission is is_sampled=False. The ``## Return
# of …\n`` header is template-synthesised scaffold; the
# ``content`` body bytes get ``is_content=True``.
tool_call_id = msg.get("tool_call_id") or ""
emit_text(f"## Return of {tool_call_id}\n", msg_idx, is_sampled=False)
emit_text(
f"## Return of {tool_call_id}\n",
msg_idx,
is_sampled=False,
is_content=False,
)
content = msg.get("content")
if content is not None:
self._emit_content(
@@ -1315,6 +1469,7 @@ class KimiK25Renderer:
emit_ids,
emit_image=emit_image,
is_sampled=False,
is_content=True,
)
def _normalize_response_tokens(self, response: list[int]) -> list[int]:
+229 -68
View File
@@ -35,8 +35,11 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
)
from renderers.configs import LagunaXS2RendererConfig
from renderers.parsing import parse_laguna_xs2
_DEFAULT_SYSTEM_MESSAGE = (
@@ -78,20 +81,10 @@ class LagunaXS2Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = False,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: LagunaXS2RendererConfig | None = None,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
# Accepted for protocol uniformity. The chat template renders
# reasoning on every assistant message regardless, so flipping
# these flags has no effect on the byte-level output.
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or LagunaXS2RendererConfig()
self._eos = self._token_id("〈|EOS|〉")
self._think = self._token_id("<think>")
@@ -154,24 +147,43 @@ class LagunaXS2Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
emit_special(self._eos, -1, is_sampled=False)
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
emit_special(self._eos, -1, is_sampled=False, is_content=False)
# ── System header (absorbs messages[0] if it's a system message) ──
system_content = _DEFAULT_SYSTEM_MESSAGE
system_msg_idx = -1
if messages and messages[0].get("role") == "system":
caller_has_system = bool(messages and messages[0].get("role") == "system")
if caller_has_system:
system_content = self._visible_text(messages[0].get("content"))
system_msg_idx = 0
@@ -187,20 +199,29 @@ class LagunaXS2Renderer:
"<system>\n\n" if has_sys_content else "<system>\n",
-1,
is_sampled=False,
is_content=False,
)
if has_sys_content:
emit_text(system_content.rstrip(), system_msg_idx, is_sampled=False)
# If the caller provided system content, it's body bytes;
# otherwise this is the default system prompt (scaffold).
sys_is_content = caller_has_system
emit_text(
system_content.rstrip(),
system_msg_idx,
is_sampled=False,
is_content=sys_is_content,
)
if tools:
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
tool_text += (
_TOOLS_FOOTER_THINKING
if self._enable_thinking
if self.config.enable_thinking
else _TOOLS_FOOTER_NO_THINKING
)
emit_text(tool_text, -1, is_sampled=False)
emit_text("\n</system>\n", -1, is_sampled=False)
emit_text(tool_text, -1, is_sampled=False, is_content=False)
emit_text("\n</system>\n", -1, is_sampled=False, is_content=False)
# ── Per-message loop ──────────────────────────────────────────
for i, msg in enumerate(messages):
@@ -211,33 +232,51 @@ class LagunaXS2Renderer:
# Already consumed in the header block.
if i == 0:
continue
emit_text(
"<system>\n" + content + "\n</system>\n", i, is_sampled=False
)
# Body = caller's content; the ``<system>...</system>``
# wrap and surrounding ``\n``s are scaffold.
sys_segs: list[tuple[str, bool]] = [("<system>\n", False)]
if content:
sys_segs.append((content, True))
sys_segs.append(("\n</system>\n", False))
emit_text_segments(sys_segs, i, is_sampled=False)
case "user":
emit_text("<user>\n" + content + "\n</user>\n", i, is_sampled=False)
user_segs: list[tuple[str, bool]] = [("<user>\n", False)]
if content:
user_segs.append((content, True))
user_segs.append(("\n</user>\n", False))
emit_text_segments(user_segs, i, is_sampled=False)
case "assistant":
self._render_assistant(
msg, i, content, emit_special=emit_special, emit_text=emit_text
msg,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
case "tool":
emit_text(
"<tool_response>\n" + content + "\n</tool_response>\n",
i,
is_sampled=False,
)
tool_segs: list[tuple[str, bool]] = [("<tool_response>\n", False)]
if content:
tool_segs.append((content, True))
tool_segs.append(("\n</tool_response>\n", False))
emit_text_segments(tool_segs, i, is_sampled=False)
# ── Generation prompt ─────────────────────────────────────────
if add_generation_prompt:
emit_special(self._assistant, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1, is_sampled=False)
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
emit_text("\n", -1, is_sampled=False, is_content=False)
if self.config.enable_thinking:
emit_special(self._think, -1, is_sampled=False, is_content=False)
else:
emit_special(self._think_end, -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -302,42 +341,95 @@ class LagunaXS2Renderer:
previous_ids.extend(self._encode("\n"))
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
ext_content: list[bool] = []
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility and ignore it; the returned
# ``RenderedTokens`` leaves ``sampled_mask`` empty.
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.extend(self._encode(text))
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([is_content] * len(ids))
for msg in new_messages:
def emit_text_segments(
segments: list[tuple[str, bool]],
msg_idx: int = -1,
*,
is_sampled: bool = False,
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
if role == "user":
emit_text("<user>\n" + content + "\n</user>\n")
segs: list[tuple[str, bool]] = [("<user>\n", False)]
if content:
segs.append((content, True))
segs.append(("\n</user>\n", False))
emit_text_segments(segs, i)
elif role == "system":
emit_text("<system>\n" + content + "\n</system>\n")
segs = [("<system>\n", False)]
if content:
segs.append((content, True))
segs.append(("\n</system>\n", False))
emit_text_segments(segs, i)
elif role == "tool":
emit_text("<tool_response>\n" + content + "\n</tool_response>\n")
segs = [("<tool_response>\n", False)]
if content:
segs.append((content, True))
segs.append(("\n</tool_response>\n", False))
emit_text_segments(segs, i)
else:
return None
emit_special(self._assistant)
emit_text("\n")
if self._enable_thinking:
emit_special(self._think)
emit_special(self._assistant, -1)
emit_text("\n", -1)
if self.config.enable_thinking:
emit_special(self._think, -1)
else:
emit_special(self._think_end)
emit_special(self._think_end, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
self,
@@ -347,7 +439,17 @@ class LagunaXS2Renderer:
*,
emit_special,
emit_text,
emit_text_segments,
) -> None:
if self.config.render_assistant_messages_raw:
self._render_assistant_raw(
msg_idx,
content,
emit_special=emit_special,
emit_text=emit_text,
)
return
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
@@ -363,23 +465,30 @@ class LagunaXS2Renderer:
# template emits these as the generation prompt at inference and
# the model never samples them. Marking the role tag as
# ``is_sampled=False`` keeps the SFT loss mask aligned with what
# the model would actually have produced.
emit_special(self._assistant, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
# the model would actually have produced. ``is_content`` is also
# False on the role tag. On assistant the invariant
# ``is_content == sampled_mask`` holds.
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
if reasoning_content:
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content.strip() + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
emit_text(
"\n" + reasoning_content.strip() + "\n",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
else:
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
# Combined newline-after-</think> with optional content. Bundling
# preserves BPE merges across the boundary.
post_think_text = "\n"
if content.strip():
post_think_text += content.strip() + "\n"
emit_text(post_think_text, msg_idx, is_sampled=True)
emit_text(post_think_text, msg_idx, is_sampled=True, is_content=True)
tool_calls = msg.get("tool_calls") or []
for tc in tool_calls:
@@ -392,7 +501,7 @@ class LagunaXS2Renderer:
except json.JSONDecodeError:
arguments = {}
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
inner = name + "\n"
if isinstance(arguments, dict):
for k, v in arguments.items():
@@ -402,13 +511,65 @@ class LagunaXS2Renderer:
else:
val_text = json.dumps(v, ensure_ascii=False)
inner += "<arg_value>" + val_text + "</arg_value>\n"
emit_text(inner, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
emit_text(inner, msg_idx, is_sampled=True, is_content=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True, is_content=True)
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
# ``</assistant>`` is the model's stop signal (alongside
# ``〈|EOS|〉``) — it samples this to end its turn, so it's part of
# the sampled stream. The trailing ``\n`` is template-appended
# between turns and never sampled.
emit_special(self._assistant_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
def _render_assistant_raw(
self,
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
) -> None:
"""Passthrough assistant rendering matching the Jinja template's
``render_assistant_messages_raw`` branch.
Three pieces, each conditional on the content's own bytes:
- Open the assistant turn (``<assistant>\\n``) — always.
- Prepend the gen-prompt prefix (``<think>`` if
``enable_thinking``, else ``</think>``) only when ``content``
doesn't already start with it. This lets callers ship content
that already includes the prefix (e.g. raw rollouts) without
duplicating it.
- Emit ``content`` verbatim. ``</think>`` and ``</assistant>``
land inside the content as added-vocab specials via the
tokenizer's default ``split_special_tokens=False`` behaviour,
matching what ``apply_chat_template`` does when it tokenises
the rendered string.
- Append ``\\n</assistant>`` only when ``content`` doesn't end
with ``</assistant>`` (or ``</assistant>\\n``), then always
emit the inter-turn ``\\n``.
Tool calls are deliberately ignored in raw mode — the template
also ignores ``message.tool_calls`` here. Callers shipping raw
content are expected to embed any tool-call payload in the
content string themselves.
"""
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
if self.config.enable_thinking:
if not content.startswith("<think>"):
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
else:
if not content.startswith("</think>"):
emit_special(
self._think_end, msg_idx, is_sampled=False, is_content=False
)
emit_text(content, msg_idx, is_sampled=True, is_content=True)
if not (content.endswith("</assistant>\n") or content.endswith("</assistant>")):
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
+516
View File
@@ -0,0 +1,516 @@
"""Llama-3 Renderer — hard-coded Python mirroring Meta's Llama-3 chat template.
Initial scope: Llama-3.2-1B-Instruct and Llama-3.2-3B-Instruct (and the
unrestricted ``unsloth/Llama-3.2-{1B,3B}-Instruct`` mirror, which ships a
byte-identical chat template). Other Llama-3.x sizes ship slightly
different templates and are NOT covered by this renderer until parity is
verified.
Notable differences from the Qwen / GLM family renderers:
* No ``<think>`` / reasoning channel — Llama-3 doesn't ship a
reasoning-content concept, so ``preserve_*_thinking`` flags don't
apply.
* ``<|begin_of_text|>`` (BOS) is emitted at the very start of every
render. The chat template never omits it.
* The system block is emitted **unconditionally** with a fixed
``Cutting Knowledge Date: December 2023\\nToday Date: <date>\\n\\n``
preamble — even when no system message is supplied. Empty system
message → block ends with ``\\n\\n<|eot_id|>``.
* Tools default to "first-user-message" mode (matching the chat
template's default ``tools_in_user_message=True``): tool descriptions
+ JSON signatures are injected into the first user message rather
than the system block. Set ``Llama3RendererConfig.tools_in_user_message
= False`` to flip to system-block mode.
* ``Llama3RendererConfig.date_string`` is pinned at ``"26 Jul 2024"`` by
default to match the chat template's ``strftime`` fallback (and keep
output deterministic). Override per instance for production runs that
want today's date.
* Tool calls: a single ``{"name": "...", "parameters": ...}`` JSON blob
inside the assistant body. The chat template explicitly raises if
``message.tool_calls | length != 1``; this renderer matches that.
* Tool responses: rendered with role ``ipython`` regardless of whether
the source message used ``role: "tool"`` or ``role: "ipython"``. The
chat template runs ``content | tojson`` on any mapping/iterable
content — and Jinja considers strings iterable, so plain string
contents get JSON-quoted. We mirror that exactly.
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.configs import Llama3RendererConfig
from renderers.parsing import parse_llama_3
# ---------------------------------------------------------------------------
# Constants — must match the Jinja chat template's literal strings exactly.
# ---------------------------------------------------------------------------
_CUTTING_KNOWLEDGE_DATE = "December 2023"
# Tools-in-system intro: emitted into the system block when tools is set
# AND tools_in_user_message=False. Note: the chat template puts these
# three string literals back-to-back with NO newline between the second
# and third, so there's no space before "Do not use variables.".
_TOOLS_IN_SYSTEM_INTRO = (
"You have access to the following functions. To call a function, "
"please respond with JSON for a function call."
'Respond in the format {"name": function name, "parameters": '
"dictionary of argument name and its value}."
"Do not use variables.\n\n"
)
# Tools-in-user intro: emitted into the first user message when tools is
# set AND tools_in_user_message=True (the default).
_TOOLS_IN_USER_INTRO = (
"Given the following functions, please respond with a JSON for a "
"function call with its proper arguments that best answers the given "
"prompt.\n\n"
'Respond in the format {"name": function name, "parameters": '
"dictionary of argument name and its value}."
"Do not use variables.\n\n"
)
class Llama3Renderer:
"""Deterministic message → token renderer for Llama-3.x Instruct models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: Llama3RendererConfig | None = None,
):
# ``preserve_*_thinking`` are accepted but no-ops: Llama-3 ships no
# reasoning_content channel, so there's never any past-assistant
# thinking to retain or drop. The flags are stored on ``self.config``
# for cross-renderer uniformity but never change the token stream —
# the same contract as Kimi-K2 / Qwen3-VL (see the never-preserves
# renderers in tests/test_preserve_thinking.py).
self._tokenizer = tokenizer
self.config = config or Llama3RendererConfig()
self._bos = self._token_id("<|begin_of_text|>")
self._start_header = self._token_id("<|start_header_id|>")
self._end_header = self._token_id("<|end_header_id|>")
self._eot = self._token_id("<|eot_id|>")
self._end_of_text = self._token_id("<|end_of_text|>")
# ``<|eom_id|>`` shows up in some Llama-3 tool-calling traces (the
# "ipython" / python-tag flow) but the standard 3.2 chat template
# closes turns with ``<|eot_id|>``. We still treat eom as a stop
# token so models that emit it terminate cleanly.
self._eom = self._token_id("<|eom_id|>")
def _token_id(self, token: str) -> int:
tid = self._tokenizer.convert_tokens_to_ids(token)
assert isinstance(tid, int) and tid != self._tokenizer.unk_token_id, (
f"Special token {token!r} not found in tokenizer vocabulary"
)
return tid
def _encode(self, text: str) -> list[int]:
if not text:
return []
return self._tokenizer.encode(text, add_special_tokens=False)
@staticmethod
def _content_str(content: Any) -> str:
"""Render content to a plain string. Handles ``str``, list-of-text-parts,
and ``None``. Matches the chat template's ``message.content | trim``
callers, which expect a string in."""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict) and "text" in item:
parts.append(item["text"])
else:
raise ValueError(f"Unexpected content item: {item}")
return "".join(parts)
raise TypeError(f"Unexpected content type: {type(content)}")
@staticmethod
def _tool_response_str(content: Any) -> str:
"""Mirror the chat template's tool-response branch:
``{% if message.content is mapping or message.content is iterable %}
{{ message.content | tojson }} {% else %} {{ message.content }}``.
In Jinja, **strings are iterable** — so plain-string tool contents
also go through ``tojson`` (i.e. ``json.dumps``), wrapping them in
quotes and escaping. Non-iterable scalars (numbers, bools, None)
fall through to literal stringification.
"""
if content is None:
return ""
if isinstance(content, (dict, list, str)):
return json.dumps(content, ensure_ascii=False)
return str(content)
# ------------------------------------------------------------------
# render
# ------------------------------------------------------------------
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> RenderedTokens:
if not messages:
raise ValueError("No messages provided.")
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
"""Tokenize concatenated wrap + body as one BPE pass; per-token
``is_content`` follows each token's source segment. Lets the
scaffold/body split stay attributed without splitting the
encode call (which could shift BPE merges at the boundary)."""
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
# ── 0. BOS ──────────────────────────────────────────────────
emit_special(self._bos, -1, is_sampled=False, is_content=False)
# ── 1. System block (always emitted) ────────────────────────
first_is_system = messages[0].get("role") == "system"
sys_idx = 0 if first_is_system else -1
sys_text = (
self._content_str(messages[0].get("content")).strip()
if first_is_system
else ""
)
emit_special(self._start_header, sys_idx, is_sampled=False, is_content=False)
emit_text("system", sys_idx, is_sampled=False, is_content=False)
emit_special(self._end_header, sys_idx, is_sampled=False, is_content=False)
# The Cutting Knowledge / Today Date preamble (and any tools-in-system
# block) is template scaffold; only the caller's system content is
# body. Route both through one BPE pass so the wrap/body boundary
# can't shift merges.
preamble = "\n\n"
if tools is not None:
preamble += "Environment: ipython\n"
preamble += f"Cutting Knowledge Date: {_CUTTING_KNOWLEDGE_DATE}\n"
preamble += f"Today Date: {self.config.date_string}\n\n"
if tools is not None and not self.config.tools_in_user_message:
preamble += _TOOLS_IN_SYSTEM_INTRO
for t in tools:
preamble += json.dumps(t, indent=4, ensure_ascii=False) + "\n\n"
sys_segments: list[tuple[str, bool]] = [(preamble, False)]
if sys_text:
sys_segments.append((sys_text, True))
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
emit_special(self._eot, sys_idx, is_sampled=False, is_content=False)
# ── 2. Body messages ────────────────────────────────────────
body_messages = messages[1:] if first_is_system else messages
offset = 1 if first_is_system else 0
i = 0
# 2a. tools_in_user_message mode pulls the first user message
# into a special block with the tools description prepended.
if tools is not None and self.config.tools_in_user_message:
if i >= len(body_messages):
raise ValueError(
"Cannot place tools in the first user message — no user "
"message was provided."
)
first_user = body_messages[i]
if first_user.get("role") != "user":
raise ValueError(
"tools_in_user_message=True requires the first non-system "
f"message to be 'user'; got {first_user.get('role')!r}."
)
user_idx = i + offset
emit_special(
self._start_header, user_idx, is_sampled=False, is_content=False
)
emit_text("user", user_idx, is_sampled=False, is_content=False)
emit_special(self._end_header, user_idx, is_sampled=False, is_content=False)
user_preamble = "\n\n" + _TOOLS_IN_USER_INTRO
for t in tools:
user_preamble += json.dumps(t, indent=4, ensure_ascii=False) + "\n\n"
user_content = self._content_str(first_user.get("content")).strip()
user_segments: list[tuple[str, bool]] = [(user_preamble, False)]
if user_content:
user_segments.append((user_content, True))
emit_text_segments(user_segments, user_idx, is_sampled=False)
emit_special(self._eot, user_idx, is_sampled=False, is_content=False)
i += 1
# 2b. Remaining messages — plain user/assistant/tool/assistant-with-tool-calls.
for j in range(i, len(body_messages)):
msg = body_messages[j]
msg_idx = j + offset
role = msg.get("role")
tool_calls = msg.get("tool_calls")
if role in ("tool", "ipython"):
# Tool responses are conversation history the model never
# samples; the response body is caller content, the wrap is
# scaffold.
emit_special(
self._start_header, msg_idx, is_sampled=False, is_content=False
)
emit_text("ipython", msg_idx, is_sampled=False, is_content=False)
emit_special(
self._end_header, msg_idx, is_sampled=False, is_content=False
)
tool_body = self._tool_response_str(msg.get("content"))
tool_segments: list[tuple[str, bool]] = [("\n\n", False)]
if tool_body:
tool_segments.append((tool_body, True))
emit_text_segments(tool_segments, msg_idx, is_sampled=False)
emit_special(self._eot, msg_idx, is_sampled=False, is_content=False)
elif tool_calls:
if len(tool_calls) != 1:
raise ValueError(
"Llama-3 chat template only supports a single tool call "
"per assistant message."
)
tc = tool_calls[0]
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
if isinstance(arguments, str):
args_str = arguments
else:
args_str = json.dumps(arguments, ensure_ascii=False)
emit_special(
self._start_header, msg_idx, is_sampled=False, is_content=False
)
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
emit_special(
self._end_header, msg_idx, is_sampled=False, is_content=False
)
# The ``\n\n`` after the header is gen-prompt scaffold the
# model never samples; the JSON tool-call body and the
# closing ``<|eot_id|>`` are the model's sampled emission.
emit_text("\n\n", msg_idx, is_sampled=False, is_content=False)
emit_text(
'{"name": "' + name + '", "parameters": ' + args_str + "}",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._eot, msg_idx, is_sampled=True, is_content=True)
elif role == "assistant":
content = self._content_str(msg.get("content")).strip()
emit_special(
self._start_header, msg_idx, is_sampled=False, is_content=False
)
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
emit_special(
self._end_header, msg_idx, is_sampled=False, is_content=False
)
# ``\n\n`` separator is scaffold (it's the generation prompt);
# the body and the closing ``<|eot_id|>`` are model-sampled.
emit_text("\n\n", msg_idx, is_sampled=False, is_content=False)
if content:
emit_text(content, msg_idx, is_sampled=True, is_content=True)
emit_special(self._eot, msg_idx, is_sampled=True, is_content=True)
else:
# user / non-leading system: caller content, never sampled.
content = self._content_str(msg.get("content")).strip()
emit_special(
self._start_header, msg_idx, is_sampled=False, is_content=False
)
emit_text(role or "", msg_idx, is_sampled=False, is_content=False)
emit_special(
self._end_header, msg_idx, is_sampled=False, is_content=False
)
segments: list[tuple[str, bool]] = [("\n\n", False)]
if content:
segments.append((content, True))
emit_text_segments(segments, msg_idx, is_sampled=False)
emit_special(self._eot, msg_idx, is_sampled=False, is_content=False)
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._start_header, -1, is_sampled=False, is_content=False)
emit_text("assistant", -1, is_sampled=False, is_content=False)
emit_special(self._end_header, -1, is_sampled=False, is_content=False)
emit_text("\n\n", -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> list[int]:
return self.render(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
return parse_llama_3(
self._tokenizer,
token_ids,
stop_ids={self._eot, self._end_of_text, self._eom},
)
def get_stop_token_ids(self) -> list[int]:
return [self._eot, self._end_of_text, self._eom]
# ------------------------------------------------------------------
# bridge_to_next_turn
# ------------------------------------------------------------------
def bridge_to_next_turn(
self,
previous_prompt_ids: list[int],
previous_completion_ids: list[int],
new_messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
) -> RenderedTokens | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._eot, self._end_of_text, self._eom},
synthesize_close=self._eot,
)
if previous_ids is None:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_content: list[bool] = []
# Every token the bridge emits is template scaffolding for the next
# prompt — none of it is model-sampled — so ``sampled_mask`` is
# uniformly ``False`` (applied over the whole sequence at return).
# ``is_content`` follows the same rules as :meth:`render` so a
# consumer can walk the trajectory and read each step's body mask.
def emit_special(token_id: int, msg_idx: int = -1) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_content.append(False)
def emit_text(text: str, msg_idx: int = -1) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_content.extend([False] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int = -1
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_content.append(is_content)
for i, msg in enumerate(new_messages):
role = msg.get("role")
if role in ("system", "user"):
content = self._content_str(msg.get("content")).strip()
emit_special(self._start_header, i)
emit_text(role, i)
emit_special(self._end_header, i)
segs: list[tuple[str, bool]] = [("\n\n", False)]
if content:
segs.append((content, True))
emit_text_segments(segs, i)
emit_special(self._eot, i)
elif role in ("tool", "ipython"):
tool_body = self._tool_response_str(msg.get("content"))
emit_special(self._start_header, i)
emit_text("ipython", i)
emit_special(self._end_header, i)
tool_segs: list[tuple[str, bool]] = [("\n\n", False)]
if tool_body:
tool_segs.append((tool_body, True))
emit_text_segments(tool_segs, i)
emit_special(self._eot, i)
else:
return None
# Generation prompt — matches the gen-prompt branch of ``render()``.
emit_special(self._start_header, -1)
emit_text("assistant", -1)
emit_special(self._end_header, -1)
emit_text("\n\n", -1)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
+258 -80
View File
@@ -21,16 +21,15 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import MiniMaxM2RendererConfig
from renderers.parsing import parse_minimax
_DEFAULT_SYSTEM = (
"You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax."
)
_TOOLS_HEADER = (
"\n\n# Tools\n"
"You may call one or more tools to assist with the user query.\n"
@@ -58,17 +57,10 @@ class MiniMaxM2Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
default_system: str = _DEFAULT_SYSTEM,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: MiniMaxM2RendererConfig | None = None,
):
self._tokenizer = tokenizer
self._default_system = default_system
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or MiniMaxM2RendererConfig()
self._bos = self._token_id("]~!b[")
self._role = self._token_id("]~b]")
@@ -119,17 +111,69 @@ class MiniMaxM2Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_token_overlap_body(
full_text: str,
body_start: int,
body_end: int,
msg_idx: int,
*,
is_sampled: bool,
) -> None:
"""Tokenize ``full_text`` and mark tokens that overlap the body
char span as ``is_content=True``.
Differs from :func:`attribute_text_segments` only in the
boundary-token rule: a token straddling scaffold→body gets
``True`` if any of its bytes are body bytes (overlap rule),
rather than being attributed to whichever segment its first
char belongs to. The body's first byte is preserved even when
BPE merges it with the wrap's trailing byte (``>The`` →
single token).
"""
from renderers.base import _get_offset_tokenizer
offset_tok = _get_offset_tokenizer(self._tokenizer)
encoding = offset_tok(
full_text, add_special_tokens=False, return_offsets_mapping=True
)
for tok_id, (start, end) in zip(
encoding["input_ids"], encoding["offset_mapping"]
):
overlaps = start < body_end and end > body_start
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(overlaps)
# ── Extract system message ──────────────────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -137,27 +181,38 @@ class MiniMaxM2Renderer:
conversation: list[Message] = messages[1:] if first_is_system else messages
# ── System block (always present) ───────────────────────────
emit_special(self._bos, sys_idx, is_sampled=False)
emit_special(self._role, sys_idx, is_sampled=False)
emit_special(self._bos, sys_idx, is_sampled=False, is_content=False)
emit_special(self._role, sys_idx, is_sampled=False, is_content=False)
sys_content = (
self._visible_text(messages[0].get("content")) if first_is_system else ""
)
system_text = "system\n" + (sys_content or self._default_system)
# Body = caller's system content (if any). Default system message
# is template-injected scaffold; tools header / per-tool JSON /
# footer / instructions are scaffold too (the tools dict is
# recoverable from the ``tools`` arg).
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if sys_content:
sys_segments.append((sys_content, True))
else:
sys_segments.append((self.config.model_identity, False))
if tools:
system_text += _TOOLS_HEADER
sys_segments.append((_TOOLS_HEADER, False))
for tool in tools:
func = tool.get("function", tool)
system_text += (
"<tool>" + json.dumps(func, ensure_ascii=False) + "</tool>\n"
sys_segments.append(
(
"<tool>" + json.dumps(func, ensure_ascii=False) + "</tool>\n",
False,
)
)
system_text += _TOOLS_FOOTER_PREFIX
system_text += _TOOLS_INSTRUCTIONS
sys_segments.append((_TOOLS_FOOTER_PREFIX, False))
sys_segments.append((_TOOLS_INSTRUCTIONS, False))
emit_text(system_text, sys_idx, is_sampled=False)
emit_special(self._eos, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
emit_special(self._eos, sys_idx, is_sampled=False, is_content=False)
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
# ── Compute last_user_index (relative to conversation) ──────
last_ui = -1
@@ -172,21 +227,21 @@ class MiniMaxM2Renderer:
orig_idx = ci + (1 if first_is_system else 0)
if role == "user":
emit_special(self._role, orig_idx, is_sampled=False)
emit_text(
"user\n" + self._visible_text(msg.get("content")),
orig_idx,
is_sampled=False,
)
emit_special(self._eos, orig_idx, is_sampled=False)
emit_text("\n", orig_idx, is_sampled=False)
emit_special(self._role, orig_idx, is_sampled=False, is_content=False)
user_content = self._visible_text(msg.get("content"))
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if user_content:
user_segments.append((user_content, True))
emit_text_segments(user_segments, orig_idx, is_sampled=False)
emit_special(self._eos, orig_idx, is_sampled=False, is_content=False)
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
messages,
orig_idx,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
self._render_assistant(
msg,
@@ -196,6 +251,7 @@ class MiniMaxM2Renderer:
preserve_thinking=preserve_thinking,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
@@ -206,17 +262,24 @@ class MiniMaxM2Renderer:
msg,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
emit_token_overlap_body=emit_token_overlap_body,
)
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._role, -1, is_sampled=False)
emit_text("ai\n", -1, is_sampled=False)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
emit_special(self._role, -1, is_sampled=False, is_content=False)
emit_text("ai\n", -1, is_sampled=False, is_content=False)
emit_special(self._think, -1, is_sampled=False, is_content=False)
emit_text("\n", -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -277,22 +340,77 @@ class MiniMaxM2Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
ext_content: list[bool] = []
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.extend(self._encode(text))
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]],
msg_idx: int = -1,
*,
is_sampled: bool = False,
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_token_overlap_body(
full_text: str,
body_start: int,
body_end: int,
msg_idx: int,
*,
is_sampled: bool,
) -> None:
from renderers.base import _get_offset_tokenizer
offset_tok = _get_offset_tokenizer(self._tokenizer)
encoding = offset_tok(
full_text, add_special_tokens=False, return_offsets_mapping=True
)
for tok_id, (start, end) in zip(
encoding["input_ids"], encoding["offset_mapping"]
):
overlaps = start < body_end and end > body_start
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(overlaps)
# Trailing ``\n`` after the ``[e~[`` turn close — see ``render()``.
emit_text("\n", -1)
@@ -302,12 +420,18 @@ class MiniMaxM2Renderer:
content = self._visible_text(msg.get("content"))
if role == "user":
emit_special(self._role, i)
emit_text("user\n" + content, i)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if content:
user_segments.append((content, True))
emit_text_segments(user_segments, i)
emit_special(self._eos, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._role, i)
emit_text("system\n" + content, i)
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if content:
sys_segments.append((content, True))
emit_text_segments(sys_segments, i)
emit_special(self._eos, i)
emit_text("\n", i)
elif role == "tool":
@@ -318,6 +442,8 @@ class MiniMaxM2Renderer:
msg,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
emit_token_overlap_body=emit_token_overlap_body,
)
else:
return None
@@ -328,7 +454,15 @@ class MiniMaxM2Renderer:
emit_special(self._think, -1)
emit_text("\n", -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
self,
@@ -340,6 +474,7 @@ class MiniMaxM2Renderer:
preserve_thinking: bool = False,
emit_special,
emit_text,
emit_text_segments,
):
content = self._visible_text(msg.get("content"))
@@ -358,12 +493,14 @@ class MiniMaxM2Renderer:
# the chat template emits these as the generation prompt and the
# model never samples them. Marking the role marker and tag as
# ``is_sampled=False`` keeps the SFT loss mask aligned with what
# the model would actually have produced.
emit_special(self._role, orig_idx, is_sampled=False)
# the model would actually have produced. ``is_content`` is also
# False here — the role tag isn't part of any message's body.
emit_special(self._role, orig_idx, is_sampled=False, is_content=False)
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges.
# calls). For assistant messages the invariant
# ``is_content == sampled_mask`` holds — every sampled token is
# body, every scaffold token isn't.
tool_calls = msg.get("tool_calls") or []
emit_thinking = reasoning_content and (
conv_idx > last_user_index or preserve_thinking
@@ -374,10 +511,15 @@ class MiniMaxM2Renderer:
# immediately after ``ai\n``, which forces a tokenizer
# boundary — splitting ``ai\n`` (not_sampled) from the
# ``<think>``-led body (sampled) is BPE-safe.
emit_text("ai\n", orig_idx, is_sampled=False)
emit_special(self._think, orig_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", orig_idx, is_sampled=True)
emit_special(self._think_end, orig_idx, is_sampled=True)
emit_text("ai\n", orig_idx, is_sampled=False, is_content=False)
emit_special(self._think, orig_idx, is_sampled=True, is_content=True)
emit_text(
"\n" + reasoning_content + "\n",
orig_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._think_end, orig_idx, is_sampled=True, is_content=True)
# \n\n + content must be contiguous for BPE
body = "\n\n" + content if content else "\n\n"
else:
@@ -390,17 +532,19 @@ class MiniMaxM2Renderer:
# choice for SFT (don't train on a token whose first byte
# is template scaffolding).
if tool_calls and not body:
emit_text("ai\n\n", orig_idx, is_sampled=False)
emit_text("ai\n\n", orig_idx, is_sampled=False, is_content=False)
else:
emit_text("ai\n", orig_idx, is_sampled=False)
emit_text("ai\n", orig_idx, is_sampled=False, is_content=False)
if tool_calls:
# \n before <minimax:tool_call> must be contiguous with preceding text.
# The empty-body / non-thinking case folded the leading \n
# into the role-tag emission above; skip it here.
if emit_thinking or body:
emit_text(body + "\n", orig_idx, is_sampled=True)
emit_special(self._tool_call_tok, orig_idx, is_sampled=True)
emit_text(body + "\n", orig_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_tok, orig_idx, is_sampled=True, is_content=True
)
invoke_block = "\n"
for tc in tool_calls:
@@ -432,16 +576,18 @@ class MiniMaxM2Renderer:
)
invoke_block += "</invoke>\n"
emit_text(invoke_block, orig_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, orig_idx, is_sampled=True)
emit_text(invoke_block, orig_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_end_tok, orig_idx, is_sampled=True, is_content=True
)
elif body:
emit_text(body, orig_idx, is_sampled=True)
emit_text(body, orig_idx, is_sampled=True, is_content=True)
# ``[e~[`` is the model's stop signal — it samples this to end
# its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
emit_special(self._eos, orig_idx, is_sampled=True)
emit_text("\n", orig_idx, is_sampled=False)
emit_special(self._eos, orig_idx, is_sampled=True, is_content=True)
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
def _render_tool(
self,
@@ -452,10 +598,15 @@ class MiniMaxM2Renderer:
*,
emit_special,
emit_text,
emit_text_segments,
emit_token_overlap_body=None,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
# tokens, so every emission is is_sampled=False. The ``content``
# body bytes get ``is_content=True``; the surrounding ``<response>``
# wrap, role tag and separators are scaffold so an SFT mask over
# tool body never trains the model to emit those.
prev_is_tool = conv_idx > 0 and conversation[conv_idx - 1]["role"] == "tool"
next_is_tool = (
conv_idx + 1 < len(conversation)
@@ -463,8 +614,8 @@ class MiniMaxM2Renderer:
)
if not prev_is_tool:
emit_special(self._role, orig_idx, is_sampled=False)
emit_text("tool", orig_idx, is_sampled=False)
emit_special(self._role, orig_idx, is_sampled=False, is_content=False)
emit_text("tool", orig_idx, is_sampled=False, is_content=False)
content = self._visible_text(msg.get("content"))
# Leading ``\n`` before ``<response>`` only on the first of a
@@ -473,12 +624,39 @@ class MiniMaxM2Renderer:
# through a single emit_text call instead of splitting the merge.
prefix = "" if prev_is_tool else "\n"
suffix = "\n" if next_is_tool else ""
emit_text(
prefix + "<response>" + content + "</response>" + suffix,
orig_idx,
is_sampled=False,
)
# ``<response>`` is plain text with no separator between the
# closing ``>`` and ``content``'s first byte, so BPE can merge
# them into a single token (e.g., ``>The``). The shared
# ``attribute_text_segments`` helper picks the segment of a
# boundary-spanning token by its *first* char (here scaffold),
# which would drop the body's leading letter out of the body
# run. We instead use an "intersects body" rule: any token whose
# ``[start, end)`` char range overlaps the body span gets
# ``is_content=True``. A few scaffold bytes (the leading ``>``
# or trailing ``<``) bleed into the body run, but body bytes are
# recoverable as a substring of the decoded body span.
body_text = prefix + "<response>" + content + "</response>" + suffix
body_start = len(prefix) + len("<response>")
body_end = body_start + len(content)
if content and emit_token_overlap_body is not None:
emit_token_overlap_body(
body_text, body_start, body_end, orig_idx, is_sampled=False
)
else:
# Empty body or no overlap-aware emitter available — fall back
# to the standard segments path.
tool_segments: list[tuple[str, bool]] = []
if prefix:
tool_segments.append((prefix, False))
tool_segments.append(("<response>", False))
if content:
tool_segments.append((content, True))
tool_segments.append(("</response>", False))
if suffix:
tool_segments.append((suffix, False))
emit_text_segments(tool_segments, orig_idx, is_sampled=False)
if not next_is_tool:
emit_special(self._eos, orig_idx, is_sampled=False)
emit_text("\n", orig_idx, is_sampled=False)
emit_special(self._eos, orig_idx, is_sampled=False, is_content=False)
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
+362 -172
View File
@@ -24,10 +24,13 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import Nemotron3RendererConfig, Nemotron3UltraRendererConfig
from renderers.parsing import parse_qwen35
# ---------------------------------------------------------------------------
@@ -72,23 +75,64 @@ def _render_extra_keys(obj: dict[str, Any], handled_keys: set[str]) -> list[str]
return lines
# The Nemotron-3 family ships two chat-template variants. Nano / Super share
# one (renderer ``Nemotron3Renderer`` / config ``name="nemotron-3"``); Ultra
# differs in the reasoning-block glue — no ``\n`` around ``</think>`` — and is
# the ``Nemotron3UltraRenderer`` subclass (``name="nemotron-3-ultra"``). Which
# variant a checkpoint uses is carried by ``MODEL_RENDERER_MAP``, so the right
# renderer class is constructed and the variant is encoded by the class itself.
def _is_super(tokenizer) -> bool:
"""Does this checkpoint use the **Super** flavour of the shared Nano/Super
template — i.e. the one whose Jinja defines the ``low_effort`` kwarg?
Nano and Super share one config (``nemotron-3``), so the model name is the
only signal that separates them. Detected by substring; unknown / fine-tuned
checkpoints default to ``False`` so ``low_effort`` is a no-op there —
matching how the Nano template silently ignores it.
"""
return "super" in (getattr(tokenizer, "name_or_path", "") or "").lower()
class Nemotron3Renderer:
"""Deterministic message → token renderer for Nemotron 3 models."""
"""Deterministic message → token renderer for Nemotron-3 Nano / Super.
The Ultra variant (distinct ``</think>`` glue) is the
:class:`Nemotron3UltraRenderer` subclass below; both are registered under
their own discriminator and differ only by the class-level hooks here.
"""
# Variant hooks (overridden by ``Nemotron3UltraRenderer``): the default
# config to build when none is passed, and whether to use Ultra's
# reasoning-block glue.
_config_cls: type = Nemotron3RendererConfig
_ultra: bool = False
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: Nemotron3RendererConfig | Nemotron3UltraRendererConfig | None = None,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
cfg = config or type(self)._config_cls()
self.config = cfg
# Resolve the per-variant reasoning-effort hint appended to the last
# user message. Ultra honours ``medium_effort``; Super honours
# ``low_effort``; Nano honours neither. The non-matching kwarg is
# silently ignored (empty hint), exactly as ``apply_chat_template``
# ignores a template variable the variant's Jinja never defines.
if self._ultra:
self._effort_hint = (
"\n\n{reasoning effort: efficient}"
if getattr(cfg, "medium_effort", False)
else ""
)
elif getattr(cfg, "low_effort", False) and _is_super(tokenizer):
self._effort_hint = "\n\n{reasoning effort: low}"
else:
self._effort_hint = ""
# Look up special token IDs from the tokenizer (not hardcoded).
# <|endoftext|> is optional: Nemotron-3 Nano / Super tokenizers ship
@@ -241,19 +285,44 @@ class Nemotron3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
def emit_ids(
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
emit_ids(
self._encode(text),
msg_idx,
is_sampled=is_sampled,
is_content=is_content,
)
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -262,12 +331,14 @@ class Nemotron3Renderer:
# Nemotron 3: system prompt BEFORE tools block
sys_idx = orig_idx(0) if first_is_system else -1
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n", sys_idx, is_sampled=False)
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
# Build system content: user's system text first, then tools
# Build system content: user's system text first, then tools.
# The template emits ``system_message`` verbatim (no trim) and
# gates the ``\n\n`` separator on its raw length, so keep the
# caller's content unstripped.
if first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
sys_content = self._render_content(messages[0].get("content"))
else:
sys_content = ""
@@ -282,38 +353,48 @@ class Nemotron3Renderer:
+ _TOOLS_INSTRUCTIONS
)
# Body = caller's system text only; tools block (header, per-
# tool XML, footer, instructions) is scaffold.
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if sys_content:
full_sys = sys_content + "\n\n" + tools_block
else:
full_sys = tools_block
emit_text(full_sys, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
sys_segments.append((sys_content, True))
sys_segments.append(("\n\n", False))
sys_segments.append((tools_block, False))
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
elif first_is_system:
sys_idx = orig_idx(0)
sys_content = self._render_content(messages[0].get("content")).strip()
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n" + sys_content, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
sys_content = self._render_content(messages[0].get("content"))
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
sys_segments2: list[tuple[str, bool]] = [("system\n", False)]
if sys_content:
sys_segments2.append((sys_content, True))
emit_text_segments(sys_segments2, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
# Track the most-recent plain (non-tool-call) assistant so we can
# preserve its reasoning while stripping reasoning from earlier
# assistants — the Nemotron-3 template matches this pattern.
last_plain_assistant_idx = -1
# All Nemotron-3 variants (Nano / Super / Ultra) truncate historical
# thinking on every assistant turn *before the last user message* —
# the template rule ``truncate_history_thinking and loop.index0 <
# last_user_idx`` is byte-identical across the three chat templates.
# Compute the last-user index over the normalized ``messages`` list (a
# leading system never holds a user, so the relative comparison is
# unaffected).
last_user_idx_norm = -1
for j in range(len(messages) - 1, -1, -1):
if messages[j].get("role") == "assistant" and not messages[j].get(
"tool_calls"
):
last_plain_assistant_idx = j
if messages[j].get("role") == "user":
last_user_idx_norm = j
break
# ── 2. Iterate messages ─────────────────────────────────────
for i, msg in enumerate(messages):
role = msg["role"]
content = self._render_content(msg.get("content")).strip()
# Keep content unstripped: the template emits user / system / tool
# content verbatim, and assistant trimming happens inside
# ``_assistant_body`` exactly where the template applies it.
content = self._render_content(msg.get("content"))
msg_orig_idx = orig_idx(i)
if role == "system":
@@ -322,28 +403,48 @@ class Nemotron3Renderer:
continue # Already handled above
elif role == "user":
emit_special(self._im_start, msg_orig_idx, is_sampled=False)
emit_text("user\n" + content, msg_orig_idx, is_sampled=False)
emit_special(self._im_end, msg_orig_idx, is_sampled=False)
emit_text("\n", msg_orig_idx, is_sampled=False)
emit_special(
self._im_start, msg_orig_idx, is_sampled=False, is_content=False
)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if content:
user_segments.append((content, True))
# Reasoning-effort hint rides on the LAST user message only,
# glued to the content so BPE sees them as one chunk (matching
# the template's ``content + '\n\n{reasoning effort: …}'``). It
# is template scaffold, not caller content → is_content=False.
if self._effort_hint and i == last_user_idx_norm:
user_segments.append((self._effort_hint, False))
emit_text_segments(user_segments, msg_orig_idx, is_sampled=False)
emit_special(
self._im_end, msg_orig_idx, is_sampled=False, is_content=False
)
emit_text("\n", msg_orig_idx, is_sampled=False, is_content=False)
elif role == "assistant":
is_last_turn = i >= last_plain_assistant_idx
# Template: ``include_content = not (truncate_history_thinking
# and loop.index0 < last_user_idx)``. The renderer-internal
# preserve_* overrides only ever *extend* retention, so OR them
# in (a preserved turn keeps its thinking even when the
# template default would drop it).
preserve_thinking = msg_orig_idx >= 0 and should_preserve_past_thinking(
original_messages,
msg_orig_idx,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
include_content = (
not self.config.truncate_history_thinking
or i >= last_user_idx_norm
or preserve_thinking
)
self._render_assistant(
msg,
msg_orig_idx,
content,
is_last_turn=is_last_turn,
preserve_thinking=preserve_thinking,
include_content=include_content,
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
)
elif role == "tool":
@@ -355,6 +456,7 @@ class Nemotron3Renderer:
auto_system_injected=auto_system_injected,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
else:
@@ -362,18 +464,23 @@ class Nemotron3Renderer:
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
if self.config.enable_thinking:
emit_special(self._think, -1, is_sampled=False, is_content=False)
emit_text("\n", -1, is_sampled=False, is_content=False)
else:
# Disable-thinking suffix: <think></think> with no trailing newlines
emit_special(self._think, -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
emit_special(self._think, -1, is_sampled=False, is_content=False)
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in original_messages],
message_tool_names=extract_message_tool_names(original_messages),
)
def render_ids(
@@ -393,7 +500,7 @@ class Nemotron3Renderer:
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — args land in a JSON object, schema not needed
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
stop_ids = {self._im_end}
if self._endoftext is not None:
@@ -406,6 +513,7 @@ class Nemotron3Renderer:
think_end_id=self._think_end,
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
tools=tools,
)
def get_stop_token_ids(self) -> list[int]:
@@ -426,6 +534,11 @@ class Nemotron3Renderer:
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
# An active effort hint rides on the *last* user message. Appending
# a new turn can move which user is last, which would strand the
# hint on the frozen previous prompt — the append-only bridge can't
# rewrite it. Bail so the caller does a full, correct re-render.
or self._effort_hint
):
return None
@@ -442,36 +555,76 @@ class Nemotron3Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
ext_content: list[bool] = []
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.extend(self._encode(text))
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]],
msg_idx: int = -1,
*,
is_sampled: bool = False,
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
emit_text("\n", -1)
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._render_content(msg.get("content")).strip()
# Unstripped — the template emits user / system / tool content
# verbatim (see :meth:`render`).
content = self._render_content(msg.get("content"))
if role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if content:
user_segments.append((content, True))
emit_text_segments(user_segments, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._im_start, i)
emit_text("system\n" + content, i)
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if content:
sys_segments.append((content, True))
emit_text_segments(sys_segments, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "tool":
@@ -483,6 +636,7 @@ class Nemotron3Renderer:
auto_system_injected=False,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
else:
return None
@@ -490,14 +644,22 @@ class Nemotron3Renderer:
# Generation prompt.
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if self._enable_thinking:
if self.config.enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
else:
emit_special(self._think, -1)
emit_special(self._think_end, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
# ------------------------------------------------------------------
# Assistant message rendering
@@ -509,112 +671,121 @@ class Nemotron3Renderer:
msg_idx: int,
content: str,
*,
is_last_turn: bool,
preserve_thinking: bool = False,
include_content: bool,
emit_special,
emit_text,
emit_ids,
) -> None:
# Extract reasoning_content
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
before_think_end, after_think_end = content.split("</think>", 1)
if "<think>" in before_think_end:
reasoning_content = before_think_end.split("<think>")[-1].lstrip("\n")
else:
reasoning_content = before_think_end.lstrip("\n")
reasoning_content = reasoning_content.rstrip("\n")
content = after_think_end.lstrip("\n")
reasoning_content = reasoning_content.strip()
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
# at inference the chat template emits these as the generation
# prompt and the model never samples them. Marking the role tag
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced.
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# what the model would actually have produced. On assistant the
# invariant ``is_content == sampled_mask`` holds.
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
# Nemotron 3 keeps reasoning on the most-recent plain assistant but
# strips it from historical turns, which collapse to an empty
# <think></think> block. Empty <think></think> is also emitted when
# the turn has no reasoning at all. The trailing ``\n`` (when
# tool_calls follow) is glued to ``content`` in a single emit_text
# so BPE sees ``content\n`` as one chunk, matching how
# apply_chat_template tokenises the concatenated template string.
tool_calls = msg.get("tool_calls") or []
# A \n is always required between the text/think block and the first
# <tool_call>, whether the content is empty or not.
content_suffix = "\n" if tool_calls else ""
# Build the body (everything between ``assistant\n`` and ``<|im_end|>``)
# as a single string mirroring the chat template's own string algebra,
# then tokenise it in one pass. The ``<think>`` / ``</think>`` /
# ``<tool_call>`` / ``</tool_call>`` markers are added tokens, so the
# tokenizer isolates them — encoding the assembled body yields the same
# ids as ``apply_chat_template`` (which likewise encodes a rendered
# string). The whole body is sampled content; ``<|im_end|>`` is the
# model's stop signal (sampled), and the inter-turn ``\n`` is not.
body = self._assistant_body(msg, content, include_content=include_content)
if body:
emit_text(body, msg_idx, is_sampled=True, is_content=True)
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
if reasoning_content and (is_last_turn or preserve_thinking):
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
# Single \n separator (not \n\n like Qwen3.5)
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=True)
elif reasoning_content:
# Historical assistant whose reasoning got stripped — template
# keeps a single \n between the collapsed <think></think> and
# the content as a marker that reasoning existed.
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=True)
def _assistant_body(
self, msg: Message, raw_content: str, *, include_content: bool
) -> str:
"""Assemble the assistant body string exactly as the chat template.
``include_content`` is the template's ``not (truncate_history_thinking
and loop.index0 < last_user_idx)`` (already OR-ed with the preserve_*
overrides by the caller): ``True`` keeps the full think+content block,
``False`` collapses historical thinking to an empty ``<think></think>``.
"""
ultra = self._ultra
# 1. Assemble ``content`` — wrap a ``reasoning_content`` field in
# <think> tags (raw, not stripped: interior whitespace is part of
# the reasoning), else prepend an empty <think></think> only when
# the content carries no inline think tags of its own (which are
# passed through verbatim, like the template).
reasoning = msg.get("reasoning_content")
if isinstance(reasoning, str) and reasoning.strip():
if ultra:
content = "<think>\n" + reasoning + "</think>" + raw_content
else:
content = "<think>\n" + reasoning + "\n</think>\n" + raw_content
else:
# No reasoning ever — <think></think> glued directly to content.
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text(content + content_suffix, msg_idx, is_sampled=True)
content = raw_content
if "<think>" not in content and "</think>" not in content:
content = "<think></think>" + content
tool_calls = msg.get("tool_calls") or []
# Tool calls (leading \n was glued to the content above; each
# iteration's trailing \n after </tool_call> handles the
# separator to the next block).
if tool_calls:
parts: list[str] = []
if content.strip():
if include_content:
parts.append(content.strip() + "\n")
else:
# Drop historical thinking: keep only what follows the last
# </think> (or precedes a dangling <think>), then re-stamp
# an empty block. Nano/Super trim the remainder; Ultra glues
# it raw (its template omits the trailing ``| trim``).
c = content
if "</think>" in c:
c = c.split("</think>")[-1]
elif "<think>" in c:
c = c.split("<think>")[0]
c = "<think></think>" + (c if ultra else c.strip())
if c:
parts.append(c + "\n")
else:
# Non-string / empty content: bare collapsed think block, no \n.
parts.append("<think></think>")
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
parts.append(self._format_tool_call(tc))
return "".join(parts)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_text("\n<function=" + name + ">\n", msg_idx, is_sampled=True)
# No tool calls.
if include_content:
return content.strip()
c = content
if "<think>" in c and "</think>" in c:
c = "<think></think>" + c.split("</think>")[-1]
return c.strip()
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
if isinstance(arg_value, (dict, list)):
value_str = json.dumps(arg_value, ensure_ascii=False)
else:
value_str = str(arg_value)
emit_text(
"<parameter="
+ arg_name
+ ">\n"
+ value_str
+ "\n</parameter>\n",
msg_idx,
is_sampled=True,
)
emit_text("</function>\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
# Trailing \n after </tool_call> (Nemotron 3 specific)
emit_text("\n", msg_idx, is_sampled=True)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
@staticmethod
def _format_tool_call(tc: dict[str, Any]) -> str:
"""Render one tool call as ``<tool_call>…</tool_call>\\n`` XML."""
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
parts = ["<tool_call>\n<function=" + name + ">\n"]
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
if isinstance(arg_value, (dict, list)):
value_str = json.dumps(arg_value, ensure_ascii=False)
else:
value_str = str(arg_value)
parts.append(
"<parameter=" + arg_name + ">\n" + value_str + "\n</parameter>\n"
)
parts.append("</function>\n</tool_call>\n")
return "".join(parts)
# ------------------------------------------------------------------
# Tool message rendering
@@ -630,10 +801,13 @@ class Nemotron3Renderer:
auto_system_injected: bool,
emit_special,
emit_text,
emit_text_segments,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
# tokens, so every emission is is_sampled=False. The ``content``
# body bytes get ``is_content=True``; the surrounding wrap is
# scaffold.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
@@ -641,17 +815,33 @@ class Nemotron3Renderer:
oi = msg_orig_idx
if not prev_is_tool:
emit_special(self._im_start, oi, is_sampled=False)
emit_text("user\n", oi, is_sampled=False)
emit_special(self._im_start, oi, is_sampled=False, is_content=False)
emit_text("user\n", oi, is_sampled=False, is_content=False)
# else: the previous tool's trailing \n already provides the
# separator into this block.
emit_special(self._tool_response, oi, is_sampled=False)
emit_text("\n" + content + "\n", oi, is_sampled=False)
emit_special(self._tool_response_end, oi, is_sampled=False)
emit_special(self._tool_response, oi, is_sampled=False, is_content=False)
emit_text_segments(
[("\n", False), (content, True), ("\n", False)], oi, is_sampled=False
)
emit_special(self._tool_response_end, oi, is_sampled=False, is_content=False)
# Nemotron 3: trailing \n after </tool_response>
emit_text("\n", oi, is_sampled=False)
emit_text("\n", oi, is_sampled=False, is_content=False)
if not next_is_tool:
emit_special(self._im_end, oi, is_sampled=False)
emit_text("\n", oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
emit_text("\n", oi, is_sampled=False, is_content=False)
class Nemotron3UltraRenderer(Nemotron3Renderer):
"""Renderer for Nemotron-3 **Ultra**.
Identical to :class:`Nemotron3Renderer` except the reasoning block is glued
as ``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around
``</think>``) and truncated historical turns collapse to
``<think></think>{content}`` (no ``\\n``) — the difference is carried by the
``_ultra`` class hook. Honours the Ultra-only ``medium_effort`` kwarg.
"""
_config_cls = Nemotron3UltraRendererConfig
_ultra = True
+150 -13
View File
@@ -65,30 +65,36 @@ def _coerce_arg_value(
"""Coerce a raw ``<arg_value>`` body to its declared type.
Returns ``(value, used_json_fallback)``. The boolean is ``True`` only
when ``json.loads`` was attempted and raised, so the caller knows
whether to flag ``INVALID_JSON``. Returning a string verbatim
because the schema declared ``type: "string"`` is NOT a fallback.
when ``json.loads`` was attempted, raised, AND the schema doesn't
permit a string. Returning a string verbatim because the schema
permits strings is NOT a fallback.
Rule (matches vLLM / SGLang reference parsers):
- If the param's declared ``type`` is ``"string"`` (or single-element
``["string"]``), return ``text`` verbatim — never ``json.loads``.
- Anything else (no schema, non-string scalar, object, array, or
union types that include non-string): try ``json.loads`` and fall
back to raw ``text`` on parse failure.
- Otherwise try ``json.loads``. If that fails, return raw ``text``.
The ``used_json_fallback`` flag is ``True`` only when the schema
does NOT permit a string — i.e. the fallback is truly suspect.
Union types that include ``"string"`` alongside other types still
attempt ``json.loads`` first so an explicit integer / bool can
parse; the string branch only wins as the fallback.
Union types (``anyOf``/``oneOf``) that include ``"string"`` alongside
other types still attempt ``json.loads`` first so an explicit
integer / bool can parse; the string branch wins as fallback, and
landing there is expected — not a malformed-JSON signal.
"""
string_is_allowed = False
if param_schema is not None:
declared = param_schema.get("type")
if declared == "string" or declared == ["string"]:
return text, False
for branch in param_schema.get("anyOf") or param_schema.get("oneOf") or []:
if isinstance(branch, dict) and branch.get("type") == "string":
string_is_allowed = True
break
try:
return json.loads(text), False
except (json.JSONDecodeError, ValueError):
return text, True
return text, not string_is_allowed
def _find(ids: list[int], target: int, start: int = 0) -> int:
@@ -127,6 +133,39 @@ def _decode(tokenizer, ids: list[int]) -> str:
return tokenizer.decode(ids, skip_special_tokens=False)
def _reasoning_end_token_index(
tokenizer, ids: list[int], marker: str = "</think>"
) -> int:
"""Token index immediately past the first ``</think>`` in ``ids``.
Returns 0 when ``ids`` has no closed reasoning region — callers treat
that as "scan from the start" (preserves pre-existing behavior for
non-thinking / truncated-reasoning completions).
Used by parsers whose ``</think>`` is *not* a single special token
(DeepSeek-V3, Kimi-K2.5) — where it tokenizes to several pieces and is
context-sensitive (the closing ``>`` merges differently depending on the
next char), so a token-id or fixed-subsequence search isn't reliable. We
instead locate the boundary in decoded text via binary search over prefix
decodes, which holds as long as ``decode(ids[:k])`` is prefix-stable in
``k`` (true for the byte-level BPE tokenizers here; ``</think>`` is clean
ASCII that won't straddle a byte boundary). Single-token ``</think>``
parsers (Qwen3) anchor on the token id directly and don't need this.
"""
if not ids or marker not in _decode(tokenizer, ids):
return 0
# Smallest prefix length (in tokens) whose decode already contains the
# full marker — i.e. the index just past where </think> completes.
lo, hi = 1, len(ids)
while lo < hi:
mid = (lo + hi) // 2
if marker in _decode(tokenizer, ids[:mid]):
hi = mid
else:
lo = mid + 1
return lo
# ── Qwen3: <tool_call> JSON </tool_call> ────────────────────────────
@@ -137,11 +176,26 @@ def parse_qwen3(
stop_ids: set[int],
tool_call_id: int,
tool_call_end_id: int,
reasoning_end_id: int | None = None,
) -> ParsedResponse:
"""Parse Qwen3 completion tokens. Hermes-style JSON tool calls."""
ids = _strip_stop_tokens(token_ids, stop_ids)
tc_start = _find(ids, tool_call_id)
# Reasoning is resolved before tool calls. Thinking models (e.g.
# Qwen3-*-Thinking) routinely draft ``<tool_call>`` blocks *inside* their
# ``<think>...</think>`` trace while planning; those are reasoning, not
# real invocations. Anchoring the tool-call scan after the ``</think>``
# boundary keeps in-think drafts out of ``tool_calls`` (otherwise they
# surface as phantom/duplicate calls) and out of the reasoning/content
# split. Mirrors vLLM's DelegatingParser, which runs the reasoning parser
# first and tool-parses only the post-``</think>`` content.
# ``reasoning_end_id`` is the ``</think>`` token id; when it's absent
# (``None``) or the model never closed its reasoning, the scan falls back
# to the whole stream (prior behavior).
reasoning_end = _find(ids, reasoning_end_id) if reasoning_end_id is not None else -1
scan_start = reasoning_end + 1 if reasoning_end != -1 else 0
tc_start = _find(ids, tool_call_id, scan_start)
tool_calls: list[ParsedToolCall] = []
if tc_start != -1:
content_ids = ids[:tc_start]
@@ -679,7 +733,15 @@ def parse_deepseek_v3(
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
tc_section_start = _find(ids, tool_calls_begin_id)
# Reasoning first: skip past </think> before looking for the tool-call
# section, so a section the model drafts *inside* its <think> trace isn't
# parsed as a real call (regression #78 — cf. parse_qwen3). content_ids
# still starts at 0, so the </think> text-split below recovers reasoning.
# DeepSeek-V3 renders </think> as multi-token text, hence the decode-based
# boundary finder rather than a token-id anchor.
reasoning_end = _reasoning_end_token_index(tokenizer, ids)
tc_section_start = _find(ids, tool_calls_begin_id, reasoning_end)
tool_calls: list[ParsedToolCall] = []
if tc_section_start != -1:
content_ids = ids[:tc_section_start]
@@ -956,6 +1018,7 @@ def parse_kimi_k2_section(
tool_call_begin_id: int,
tool_call_argument_begin_id: int,
tool_call_end_id: int,
scan_start: int = 0,
) -> tuple[list[int], list[ParsedToolCall]]:
"""Split ``ids`` into ``(content_before_section, tool_calls)`` by finding
the Kimi-style tool-call section delimiters.
@@ -967,8 +1030,15 @@ def parse_kimi_k2_section(
of the section and a list of ``ParsedToolCall`` covering every attempted
block inside it; an unclosed section is still walked to whatever the model
emitted before EOS. Returns ``(ids, [])`` when no section is present.
``scan_start`` restricts the section search to ``ids[scan_start:]`` while
keeping ``content_ids = ids[:section_start]`` and all token spans relative
to the full ``ids``. Callers pass the post-``</think>`` index so a section
the model drafts inside its reasoning trace isn't parsed as a real call;
because ``content_ids`` still starts at 0, downstream text-based reasoning
extraction is unaffected (regression #78).
"""
section_start = _find_any(ids, tool_calls_section_begin_ids)
section_start = _find_any(ids, tool_calls_section_begin_ids, scan_start)
if section_start == -1:
return list(ids), []
content_ids = ids[:section_start]
@@ -1264,3 +1334,70 @@ def _gptoss_extract_after_token(
return None
after = _decode(tokenizer, header_ids[pos + 1 :]).strip()
return after.split()[0] if after else None
# ── Llama-3: single JSON tool call {"name": "...", "parameters": {...}} ─
def parse_llama_3(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
) -> ParsedResponse:
"""Parse Llama-3 completion tokens.
The Llama-3 chat template emits tool calls as a single JSON blob in
the assistant body — ``{"name": "...", "parameters": {...}}`` — with
no surrounding XML tags or special tokens. Plain replies are just
text. We detect the tool-call shape with a strict starts-with-``{``
+ parses-as-dict-with-name-key check; anything else is treated as
content. Llama-3 doesn't have a built-in reasoning channel, so
``reasoning_content`` is always ``None``.
Unlike the delimiter-based formats (Qwen/GLM), the tool call has no
special token to anchor on, so a leading assistant role-header
(``<|start_header_id|>assistant<|end_header_id|>\\n\\n``) would defeat
the starts-with-``{`` check. Callers that slice a completion without
dropping the generation prompt include that scaffold; we skip past the
final ``<|end_header_id|>`` so the body is what we parse. The sampled
stream in production carries no header, making this a no-op there.
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
# Skip a leading assistant role-header scaffold if present.
body_start = 0
end_header_id = tokenizer.convert_tokens_to_ids("<|end_header_id|>")
if isinstance(end_header_id, int):
eh_positions = _find_all(ids, end_header_id)
if eh_positions:
body_start = eh_positions[-1] + 1
body_ids = ids[body_start:]
text = _decode(tokenizer, body_ids).strip()
if text.startswith("{") and text.endswith("}"):
try:
parsed = json.loads(text)
except json.JSONDecodeError:
parsed = None
if isinstance(parsed, dict) and parsed.get("name"):
arguments = parsed.get("parameters", parsed.get("arguments", {}))
return ParsedResponse(
content="",
reasoning_content=None,
tool_calls=[
ParsedToolCall(
raw=text,
name=parsed["name"],
arguments=arguments,
token_span=(body_start, len(ids)),
status=ToolCallParseStatus.OK,
)
],
)
# Not a tool-call shape (plain reply, or a ``{...}`` body that didn't
# parse / lacked a name). Llama-3 has no delimiter to anchor a
# "malformed attempt" against, so it falls through to content rather
# than producing a non-OK ParsedToolCall.
return ParsedResponse(content=text, reasoning_content=None)
+209 -83
View File
@@ -18,10 +18,13 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import Qwen3RendererConfig
from renderers.parsing import parse_qwen3
_TOOLS_HEADER = (
@@ -47,17 +50,10 @@ class Qwen3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: Qwen3RendererConfig | None = None,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or Qwen3RendererConfig()
self._im_start = self._token_id("<|im_start|>")
self._im_end = self._token_id("<|im_end|>")
@@ -66,6 +62,7 @@ class Qwen3Renderer:
self._tool_call_end = self._token_id("</tool_call>")
self._tool_response = self._token_id("<tool_response>")
self._tool_response_end = self._token_id("</tool_response>")
self._think_end = self._token_id("</think>")
def _token_id(self, token: str) -> int:
tid = self._tokenizer.convert_tokens_to_ids(token)
@@ -108,43 +105,76 @@ class Qwen3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
"""Tokenize concatenated segments as one BPE pass; per-token
``is_content`` follows each token's source segment.
Lets call sites express "this wrap + this body, joined the
same way as the chat template, but attributed separately"
without splitting the encode call (which could shift BPE
merges at the boundary)."""
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
# ── 1. System + tools ───────────────────────────────────────
first_is_system = messages[0].get("role") == "system"
if tools:
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx, is_sampled=False)
tool_text = "system\n"
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
# Body = system content (if any). Everything else in this
# block — role tag, tools header / footer, the JSON tool
# specs — is scaffold. The tools dict is recoverable from
# the ``tools`` argument; don't re-attribute its embedded
# JSON as message body.
segments: list[tuple[str, bool]] = [("system\n", False)]
if first_is_system:
tool_text += (messages[0].get("content") or "") + "\n\n"
tool_text += _TOOLS_HEADER
sys_content = messages[0].get("content") or ""
if sys_content:
segments.append((sys_content, True))
segments.append(("\n\n", False))
segments.append((_TOOLS_HEADER, False))
for tool in tools:
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
tool_text += _TOOLS_FOOTER
emit_text(tool_text, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
segments.append(("\n" + json.dumps(tool, ensure_ascii=False), False))
segments.append((_TOOLS_FOOTER, False))
emit_text_segments(segments, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
elif first_is_system:
emit_special(self._im_start, 0, is_sampled=False)
emit_text(
"system\n" + (messages[0].get("content") or ""), 0, is_sampled=False
)
emit_special(self._im_end, 0, is_sampled=False)
emit_text("\n", 0, is_sampled=False)
emit_special(self._im_start, 0, is_sampled=False, is_content=False)
sys_content = messages[0].get("content") or ""
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if sys_content:
sys_segments.append((sys_content, True))
emit_text_segments(sys_segments, 0, is_sampled=False)
emit_special(self._im_end, 0, is_sampled=False, is_content=False)
emit_text("\n", 0, is_sampled=False, is_content=False)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
@@ -158,23 +188,29 @@ class Qwen3Renderer:
if role == "system":
if i == 0:
continue
emit_special(self._im_start, i, is_sampled=False)
emit_text(role + "\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
emit_special(self._im_start, i, is_sampled=False, is_content=False)
msg_segments: list[tuple[str, bool]] = [(role + "\n", False)]
if content:
msg_segments.append((content, True))
emit_text_segments(msg_segments, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False, is_content=False)
emit_text("\n", i, is_sampled=False, is_content=False)
elif role == "user":
emit_special(self._im_start, i, is_sampled=False)
emit_text("user\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
emit_special(self._im_start, i, is_sampled=False, is_content=False)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if content:
user_segments.append((content, True))
emit_text_segments(user_segments, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False, is_content=False)
emit_text("\n", i, is_sampled=False, is_content=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
messages,
i,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
self._render_assistant(
msg,
@@ -185,22 +221,35 @@ class Qwen3Renderer:
preserve_thinking=preserve_thinking,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
self._render_tool(
messages, i, content, emit_special=emit_special, emit_text=emit_text
messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
# ── 4. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if not self._enable_thinking:
emit_text("<think>\n\n</think>\n\n", -1, is_sampled=False)
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
if not self.config.enable_thinking:
emit_text(
"<think>\n\n</think>\n\n", -1, is_sampled=False, is_content=False
)
return RenderedTokens(
token_ids=tokens, message_indices=indices, sampled_mask=sampled
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
)
def render_ids(
@@ -228,6 +277,7 @@ class Qwen3Renderer:
stop_ids={self._im_end, self._endoftext},
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
reasoning_end_id=self._think_end,
)
def get_stop_token_ids(self) -> list[int]:
@@ -258,22 +308,56 @@ class Qwen3Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
ext_content: list[bool] = []
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask. Downstream consumers can
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
# output to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
ext.extend(self._encode(text))
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
ext_content.extend([is_content] * len(ids))
def emit_text_segments(
segments: list[tuple[str, bool]],
msg_idx: int = -1,
*,
is_sampled: bool = False,
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
ext.append(tok_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
ext_content.append(is_content)
# Trailing ``\n`` after the turn-close token. ``render()`` emits this
# as part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
@@ -285,12 +369,18 @@ class Qwen3Renderer:
content = msg.get("content") if isinstance(msg.get("content"), str) else ""
if role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if content:
user_segments.append((content, True))
emit_text_segments(user_segments, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._im_start, i)
emit_text("system\n" + content, i)
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if content:
sys_segments.append((content, True))
emit_text_segments(sys_segments, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "tool":
@@ -300,16 +390,25 @@ class Qwen3Renderer:
content,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
else:
return None
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if not self._enable_thinking:
if not self.config.enable_thinking:
emit_text("<think>\n\n</think>\n\n", -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
is_content=[False] * len(previous_ids) + ext_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
)
def _render_assistant(
self,
@@ -322,6 +421,7 @@ class Qwen3Renderer:
preserve_thinking: bool = False,
emit_special,
emit_text,
emit_text_segments,
):
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
@@ -339,16 +439,20 @@ class Qwen3Renderer:
# at inference the chat template emits these as the generation
# prompt and the model never samples them. Marking the role tag
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced.
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# what the model would actually have produced. ``is_content`` is
# also False here — the role tag isn't part of any message's
# body, on any role.
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges (e.g., ".\n" is a single token in
# Qwen3); the only split we introduce here is at ``\n`` after the
# role tag, which the existing renderer already treats as a
# token boundary (cf. ``_render_tool``).
# token boundary (cf. ``_render_tool``). For assistant messages
# the invariant ``is_content == sampled_mask`` holds — every
# sampled token is body, every scaffold token isn't.
tool_calls = msg.get("tool_calls") or []
emit_in_template_window = msg_idx > last_query_index and (
@@ -366,7 +470,7 @@ class Qwen3Renderer:
body = content
if not tool_calls:
emit_text(body, msg_idx, is_sampled=True)
emit_text(body, msg_idx, is_sampled=True, is_content=True)
else:
for tc_idx, tc in enumerate(tool_calls):
func = tc.get("function") or tc
@@ -381,23 +485,29 @@ class Qwen3Renderer:
# Text before this tool_call (includes separator)
if tc_idx == 0:
separator = "\n" if content else ""
emit_text(body + separator, msg_idx, is_sampled=True)
emit_text(
body + separator, msg_idx, is_sampled=True, is_content=True
)
else:
emit_text("\n", msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
emit_text(
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
# end its turn, so it is part of the sampled stream (and the
# assistant's body). The trailing ``\n`` is template-appended
# between turns and never sampled — scaffold for is_content too.
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
def _render_tool(
self,
@@ -407,24 +517,40 @@ class Qwen3Renderer:
*,
emit_special,
emit_text,
emit_text_segments,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
# tokens, so every emission is is_sampled=False. The ``content``
# field's body bytes get ``is_content=True``; everything else —
# the ``<|im_start|>user`` wrap, the inter-section ``\n``s, the
# ``<|tool_response>`` specials — is scaffold so the SFT mask
# for tool body never trains the model to emit them.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
)
if not prev_is_tool:
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("user", msg_idx, is_sampled=False)
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
emit_text("user", msg_idx, is_sampled=False, is_content=False)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._tool_response, msg_idx, is_sampled=False)
emit_text("\n" + content + "\n", msg_idx, is_sampled=False)
emit_special(self._tool_response_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
emit_special(self._tool_response, msg_idx, is_sampled=False, is_content=False)
# ``\n`` + content + ``\n`` — body is the middle segment only.
# Single BPE pass over the joined text preserves boundary
# merges (Qwen3 keeps ``\n`` as its own token, so this is
# mostly a no-op, but we route through segments anyway so the
# attribution doesn't depend on tokenizer-specific behaviour).
emit_text_segments(
[("\n", False), (content, True), ("\n", False)],
msg_idx,
is_sampled=False,
)
emit_special(
self._tool_response_end, msg_idx, is_sampled=False, is_content=False
)
if not next_is_tool:
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
+376 -162
View File
@@ -26,10 +26,13 @@ from renderers.base import (
PlaceholderRange,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import Qwen35RendererConfig
from renderers.parsing import parse_qwen35
from renderers.qwen3_vl import (
_image_hash,
@@ -64,63 +67,70 @@ _TOOLS_INSTRUCTIONS = (
)
def _detect_enable_thinking_default(tokenizer: PreTrainedTokenizer) -> bool:
"""Probe the tokenizer's chat template to learn its ``enable_thinking``
default polarity at the generation-prompt boundary.
# Per-model ``enable_thinking`` default, applied when the renderer config
# leaves it ``None``. The Qwen3.5 family ships two chat-template variants
# that differ only in the polarity of the gated thinking branch:
#
# * Big sizes (4B / 9B / 35B-A3B / 122B-A10B / 397B-A17B) default
# ``enable_thinking=true`` — an open ``<think>\n`` at the gen prompt.
# * Small sizes (0.8B / 2B) flip it — default ``false``, emitting the
# empty ``<think>\n\n</think>\n\n`` block.
#
# These are hard-coded (keyed by ``tokenizer.name_or_path``) rather than
# probed from the live ``chat_template``: probing meant calling
# ``apply_chat_template`` at construction, which pulls ``transformers`` onto
# the hot path and breaks bring-your-own-tokenizer use. The values are the
# ground truth pinned by ``tests/test_qwen35_size_coverage.py`` — both the
# polarity assertions and byte-parity against each size's own
# ``apply_chat_template``.
_ENABLE_THINKING_DEFAULTS: dict[str, bool] = {
"Qwen/Qwen3.5-0.8B": False,
"Qwen/Qwen3.5-2B": False,
"Qwen/Qwen3.5-4B": True,
"Qwen/Qwen3.5-9B": True,
"Qwen/Qwen3.5-35B-A3B": True,
"Qwen/Qwen3.5-122B-A10B": True,
"Qwen/Qwen3.5-397B-A17B": True,
# Qwen3.6 extends the Qwen3.5 template; same big-size polarity.
"Qwen/Qwen3.6-35B-A3B": True,
}
The Qwen3.5 family ships two template variants that differ only in the
polarity of the gated branch:
* Big sizes (4B / 9B / 35B-A3B / 122B-A10B / 397B-A17B) emit an open
``<think>\\n`` by default and the empty ``<think>\\n\\n</think>\\n\\n``
block when ``enable_thinking`` is explicitly false.
* Small sizes (0.8B / 2B) flip the polarity — they emit the empty
block by default and the open ``<think>\\n`` only when
``enable_thinking`` is explicitly true.
def _default_enable_thinking(tokenizer) -> bool:
"""Hard-coded ``enable_thinking`` default for ``tokenizer``'s model.
A one-shot ``apply_chat_template`` call with no flag and a minimal
user message reveals which variant is in use: the empty-block tail
ends with ``</think>``, the open-think tail does not. Failing the
probe (no chat_template, exotic config) falls back to the big-model
default of True, which matches every entry in
``MODEL_RENDERER_MAP`` that routes to ``qwen3.5`` without explicit
polarity awareness.
Falls back to ``True`` (the big-model default, and the majority of the
family) for unknown / fine-tuned checkpoints whose ``name_or_path`` isn't
in ``_ENABLE_THINKING_DEFAULTS``; pass an explicit ``enable_thinking=`` to
a small-size fine-tune that needs ``False``.
"""
try:
out = tokenizer.apply_chat_template(
[{"role": "user", "content": "x"}],
tokenize=False,
add_generation_prompt=True,
)
except Exception:
return True
if not isinstance(out, str):
return True
return not out.rstrip().endswith("</think>")
return _ENABLE_THINKING_DEFAULTS.get(getattr(tokenizer, "name_or_path", ""), True)
class Qwen35Renderer:
"""Deterministic message → token renderer for Qwen3.5 models."""
_config_cls: type = Qwen35RendererConfig
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: Qwen35RendererConfig | None = None,
*,
processor: Any = None,
enable_thinking: bool | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
image_cache_max: int = 256,
):
self._tokenizer = tokenizer
self._processor = processor
if enable_thinking is None:
enable_thinking = _detect_enable_thinking_default(tokenizer)
self._enable_thinking = enable_thinking
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
cfg = config or type(self)._config_cls()
# ``enable_thinking=None`` defers to the model's known default (see
# ``_ENABLE_THINKING_DEFAULTS``). Materialise here so downstream reads
# see a concrete bool; rebind the config with the resolved value so
# introspection sees the same.
if cfg.enable_thinking is None:
cfg = cfg.model_copy(
update={"enable_thinking": _default_enable_thinking(tokenizer)}
)
self.config = cfg
# Look up special token IDs from the tokenizer (not hardcoded)
self._im_start = self._token_id("<|im_start|>")
@@ -141,7 +151,6 @@ class Qwen35Renderer:
# rationale (FIFO-bounded; same image seen across rollouts /
# bridge re-renders).
self._image_cache: dict[str, tuple[Any, int]] = {}
self._image_cache_max = image_cache_max
@property
def mm_token_type_id_map(self) -> dict[int, int]:
@@ -186,7 +195,7 @@ class Qwen35Renderer:
grid_thw = out["image_grid_thw"][0]
merge_size = proc.image_processor.merge_size
num_image_tokens = int(grid_thw.prod()) // (merge_size * merge_size)
if len(self._image_cache) >= self._image_cache_max:
if len(self._image_cache) >= self.config.image_cache_max:
self._image_cache.pop(next(iter(self._image_cache)))
self._image_cache[h] = (out, num_image_tokens)
return pil, out, num_image_tokens, h
@@ -291,33 +300,88 @@ class Qwen35Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
content_mask: list[bool] = []
mm_hashes: dict[str, list[str]] = {}
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
mm_items: dict[str, list[dict[str, Any]]] = {}
# 1-indexed counters for ``add_vision_id`` (mirrors the Jinja's
# ``image_count`` / ``video_count`` namespaces). Increment only
# in the main message loop — the template renders the system
# message with ``do_vision_count=False`` and would raise on
# vision in system content anyway, so the renderer's
# ``emit_image`` is only reached from user / tool emission paths.
vision_counts = {"image": 0, "video": 0}
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
def emit_ids(
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
def emit_special(
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_text(
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
) -> None:
emit_ids(
self._encode(text),
msg_idx,
is_sampled=is_sampled,
is_content=is_content,
)
def emit_text_segments(
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
) -> None:
"""Tokenize concatenated segments as one BPE pass; per-token
``is_content`` follows each token's source segment.
Lets call sites express "this wrap + this body, joined the
same way as the chat template, but attributed separately"
without splitting the encode call (which could shift BPE
merges at the boundary)."""
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_image(part: dict[str, Any], msg_idx: int) -> None:
# Image placeholders only appear in user / tool messages; the
# model never samples them. Pin is_sampled=False here so
# callers don't need to thread the flag through.
# callers don't need to thread the flag through. The
# ``<|image_pad|>`` placeholders represent caller-provided
# image data, so they ARE body content (is_content=True);
# the surrounding ``<|vision_start|>`` / ``<|vision_end|>``
# specials are template scaffold.
_, out, n, h = self._process_image(part)
emit_special(self._vision_start, msg_idx, is_sampled=False)
vision_counts["image"] += 1
if self.config.add_vision_id:
emit_text(
f"Picture {vision_counts['image']}: ",
msg_idx,
is_sampled=False,
is_content=False,
)
emit_special(
self._vision_start, msg_idx, is_sampled=False, is_content=False
)
offset = len(tokens)
for _ in range(n):
emit_special(self._image_pad, msg_idx, is_sampled=False)
emit_special(self._vision_end, msg_idx, is_sampled=False)
emit_special(
self._image_pad, msg_idx, is_sampled=False, is_content=True
)
emit_special(self._vision_end, msg_idx, is_sampled=False, is_content=False)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -337,20 +401,28 @@ class Qwen35Renderer:
``<|im_end|>``), matching how Jinja's ``render_content`` macro
concatenates strings before tokenization. This preserves BPE
byte-parity against ``apply_chat_template``.
Within each flush the ``"user\\n"`` wrap is scaffold and the
text parts are body. ``emit_text_segments`` carries that
attribution through the BPE pass.
"""
# Every token in a user message is conversation history that
# the model never samples at inference.
emit_special(self._im_start, msg_idx, is_sampled=False)
buf: list[str] = ["user\n"]
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
# First flush includes the ``"user\n"`` wrap as a scaffold
# segment; subsequent flushes are pure body (after a media
# break).
buf_segments: list[tuple[str, bool]] = [("user\n", False)]
def flush_buf() -> None:
if buf:
emit_text("".join(buf), msg_idx, is_sampled=False)
buf.clear()
if buf_segments:
emit_text_segments(buf_segments, msg_idx, is_sampled=False)
buf_segments.clear()
for item in content_list:
if isinstance(item, str):
buf.append(item)
if item:
buf_segments.append((item, True))
elif isinstance(item, dict):
if _is_image_part(item):
flush_buf()
@@ -360,14 +432,15 @@ class Qwen35Renderer:
"Video parts are not yet supported by Qwen35Renderer."
)
elif "text" in item:
buf.append(item["text"])
if item["text"]:
buf_segments.append((item["text"], True))
else:
raise ValueError(f"Unexpected content item: {item}")
else:
raise ValueError(f"Unexpected content item: {item}")
flush_buf()
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -376,31 +449,37 @@ class Qwen35Renderer:
# System message index for attribution
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n", sys_idx, is_sampled=False)
# Tools header + JSON definitions
tool_text = _TOOLS_HEADER
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
# Body = system content (if any). Everything else in this
# block — role tag, tools header / footer / instructions, the
# JSON tool specs — is scaffold. The tools dict is
# recoverable from the ``tools`` argument; don't re-attribute
# its embedded JSON as message body.
segments: list[tuple[str, bool]] = [
("system\n", False),
(_TOOLS_HEADER, False),
]
for tool in tools:
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
tool_text += _TOOLS_FOOTER
tool_text += _TOOLS_INSTRUCTIONS
# Append user's system content if present
segments.append(("\n" + json.dumps(tool, ensure_ascii=False), False))
segments.append((_TOOLS_FOOTER, False))
segments.append((_TOOLS_INSTRUCTIONS, False))
if first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
if sys_content:
tool_text += "\n\n" + sys_content
emit_text(tool_text, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
segments.append(("\n\n", False))
segments.append((sys_content, True))
emit_text_segments(segments, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
elif first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
emit_special(self._im_start, 0, is_sampled=False)
emit_text("system\n" + sys_content, 0, is_sampled=False)
emit_special(self._im_end, 0, is_sampled=False)
emit_text("\n", 0, is_sampled=False)
emit_special(self._im_start, 0, is_sampled=False, is_content=False)
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if sys_content:
sys_segments.append((sys_content, True))
emit_text_segments(sys_segments, 0, is_sampled=False)
emit_special(self._im_end, 0, is_sampled=False, is_content=False)
emit_text("\n", 0, is_sampled=False, is_content=False)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
@@ -420,17 +499,20 @@ class Qwen35Renderer:
if self._content_has_media(raw_content):
emit_user_with_media(raw_content, i)
else:
emit_special(self._im_start, i, is_sampled=False)
emit_text("user\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
emit_special(self._im_start, i, is_sampled=False, is_content=False)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if content:
user_segments.append((content, True))
emit_text_segments(user_segments, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False, is_content=False)
emit_text("\n", i, is_sampled=False, is_content=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
messages,
i,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
self._render_assistant(
msg,
@@ -441,6 +523,7 @@ class Qwen35Renderer:
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
@@ -450,6 +533,7 @@ class Qwen35Renderer:
emit_special=emit_special,
emit_text=emit_text,
emit_image=emit_image,
emit_text_segments=emit_text_segments,
)
else:
@@ -457,16 +541,16 @@ class Qwen35Renderer:
# ── 4. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
if self.config.enable_thinking:
emit_special(self._think, -1, is_sampled=False, is_content=False)
emit_text("\n", -1, is_sampled=False, is_content=False)
else:
emit_special(self._think, -1, is_sampled=False)
emit_text("\n\n", -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
emit_text("\n\n", -1, is_sampled=False)
emit_special(self._think, -1, is_sampled=False, is_content=False)
emit_text("\n\n", -1, is_sampled=False, is_content=False)
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
emit_text("\n\n", -1, is_sampled=False, is_content=False)
mm_data: MultiModalData | None = None
if mm_hashes or mm_placeholders or mm_items:
@@ -480,6 +564,9 @@ class Qwen35Renderer:
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
multi_modal_data=mm_data,
)
@@ -541,36 +628,102 @@ class Qwen35Renderer:
if previous_ids is None:
return None
# ``add_vision_id`` numbers placeholders across the whole
# conversation. The bridge can only seed that counter from
# ``previous_multi_modal_data`` (raw prior token ids don't carry
# the image/video count back), so if the caller asks for
# ``add_vision_id=True`` while omitting prior mm-data on a
# conversation that already contains images, the bridged
# output would silently emit ``Picture 1:`` again. Refuse the
# bridge in that case — the caller falls back to a full
# re-render, which has the full message list and counts from
# scratch correctly.
if (
self.config.add_vision_id
and previous_multi_modal_data is None
and self._vision_start in previous_ids
):
return None
# Seed combined-token list with prior turn so placeholder offsets
# are absolute in the bridged sequence (matching ``render()``).
# Parallel ``indices``/``sampled`` are seeded with ``-1``/``False``
# for the prior portion — the bridge has no attribution info for
# ``previous_ids``. Bridge-added tokens get proper ``msg_idx``
# (relative to ``new_messages``) and uniformly ``False``
# ``sampled``: nothing the bridge emits was model-sampled.
# ``is_content`` follows the same rules as in :meth:`render` so
# consumers can walk the trajectory and read each step's own
# body mask; the prior portion is uniformly False since we have
# no attribution info for it.
tokens: list[int] = list(previous_ids)
indices: list[int] = [-1] * len(previous_ids)
sampled: list[bool] = [False] * len(previous_ids)
content_mask: list[bool] = [False] * len(previous_ids)
new_hashes: dict[str, list[str]] = {}
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
# Seed the ``add_vision_id`` counters from prior-turn images / videos
# so the bridged turn's first placeholder gets ``Picture {prev+1}``.
# Bridges can't recover the count from raw token ids, so callers
# must thread ``previous_multi_modal_data`` through to keep
# ``add_vision_id`` parity across turns.
prev_image_count = 0
prev_video_count = 0
if previous_multi_modal_data is not None:
prev_image_count = len(previous_multi_modal_data.mm_items.get("image", []))
prev_video_count = len(previous_multi_modal_data.mm_items.get("video", []))
vision_counts = {"image": prev_image_count, "video": prev_video_count}
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't track sampled_mask here. Local helpers accept the kwarg
# for signature compatibility with ``_render_tool`` and ignore
# it; the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty.
def emit_special(
token_id: int, _msg_idx: int = -1, *, is_sampled: bool = False
token_id: int,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_text(
text: str, _msg_idx: int = -1, *, is_sampled: bool = False
text: str,
msg_idx: int = -1,
*,
is_sampled: bool = False,
is_content: bool = False,
) -> None:
tokens.extend(self._encode(text))
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
content_mask.extend([is_content] * len(ids))
def emit_image(part: dict[str, Any], _msg_idx: int = -1) -> None:
def emit_text_segments(
segments: list[tuple[str, bool]],
msg_idx: int = -1,
*,
is_sampled: bool = False,
) -> None:
for tok_id, is_content in attribute_text_segments(
self._tokenizer, segments
):
tokens.append(tok_id)
indices.append(msg_idx)
sampled.append(is_sampled)
content_mask.append(is_content)
def emit_image(part: dict[str, Any], msg_idx: int = -1) -> None:
_, out, n, h = self._process_image(part)
emit_special(self._vision_start)
vision_counts["image"] += 1
if self.config.add_vision_id:
emit_text(f"Picture {vision_counts['image']}: ", msg_idx)
emit_special(self._vision_start, msg_idx)
offset = len(tokens)
for _ in range(n):
emit_special(self._image_pad)
emit_special(self._vision_end)
emit_special(self._image_pad, msg_idx, is_content=True)
emit_special(self._vision_end, msg_idx)
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -582,35 +735,37 @@ class Qwen35Renderer:
}
)
def emit_user_with_media(content_list: list[Any]) -> None:
emit_special(self._im_start)
buf: list[str] = ["user\n"]
def emit_user_with_media(content_list: list[Any], msg_idx: int) -> None:
emit_special(self._im_start, msg_idx)
buf_segments: list[tuple[str, bool]] = [("user\n", False)]
def flush_buf() -> None:
if buf:
emit_text("".join(buf))
buf.clear()
if buf_segments:
emit_text_segments(buf_segments, msg_idx)
buf_segments.clear()
for item in content_list:
if isinstance(item, str):
buf.append(item)
if item:
buf_segments.append((item, True))
elif isinstance(item, dict):
if _is_image_part(item):
flush_buf()
emit_image(item)
emit_image(item, msg_idx)
elif _is_video_part(item):
raise NotImplementedError(
"Video parts are not yet supported by Qwen35Renderer."
)
elif "text" in item:
buf.append(item["text"])
if item["text"]:
buf_segments.append((item["text"], True))
else:
raise ValueError(f"Unexpected content item: {item}")
else:
raise ValueError(f"Unexpected content item: {item}")
flush_buf()
emit_special(self._im_end)
emit_text("\n")
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# Trailing ``\n`` after ``<|im_end|>`` — ``render()`` emits it as
# part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
@@ -623,15 +778,21 @@ class Qwen35Renderer:
content = self._render_content(raw_content).strip()
if role == "user":
if self._content_has_media(raw_content):
emit_user_with_media(raw_content)
emit_user_with_media(raw_content, i)
else:
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
user_segments: list[tuple[str, bool]] = [("user\n", False)]
if content:
user_segments.append((content, True))
emit_text_segments(user_segments, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._im_start, i)
emit_text("system\n" + content, i)
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
if content:
sys_segments.append((content, True))
emit_text_segments(sys_segments, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "tool":
@@ -641,6 +802,7 @@ class Qwen35Renderer:
emit_special=emit_special,
emit_text=emit_text,
emit_image=emit_image,
emit_text_segments=emit_text_segments,
)
else:
return None
@@ -648,7 +810,7 @@ class Qwen35Renderer:
# Generation prompt — matches the gen-prompt branch of ``render()``.
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if self._enable_thinking:
if self.config.enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
else:
@@ -680,8 +842,17 @@ class Qwen35Renderer:
for modality, vals in new_items.items():
merged_items.setdefault(modality, []).extend(vals)
bridge_roles = [m.get("role") or "" for m in new_messages]
bridge_tool_names = extract_message_tool_names(new_messages)
if not (merged_hashes or merged_placeholders or merged_items):
return RenderedTokens(token_ids=tokens)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
)
mm_data = MultiModalData(
mm_hashes=merged_hashes,
@@ -690,7 +861,11 @@ class Qwen35Renderer:
)
return RenderedTokens(
token_ids=tokens,
message_indices=[-1] * len(tokens),
message_indices=indices,
sampled_mask=sampled,
is_content=content_mask,
message_roles=bridge_roles,
message_tool_names=bridge_tool_names,
multi_modal_data=mm_data,
)
@@ -732,6 +907,7 @@ class Qwen35Renderer:
emit_special,
emit_text,
emit_ids,
emit_text_segments,
) -> None:
# Extract reasoning_content
reasoning_content = ""
@@ -754,26 +930,36 @@ class Qwen35Renderer:
# at inference the chat template emits these as the generation
# prompt and the model never samples them. Marking the role tag
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced. The split between
# ``assistant`` and ``\n`` is a safe BPE boundary in the Qwen
# tokenizer (``\n`` after the role is its own token).
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# what the model would actually have produced. ``is_content`` is
# also False here — the role tag isn't part of any message's
# body, on any role.
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges.
# span to preserve BPE merges. For assistant messages the
# invariant ``is_content == sampled_mask`` holds — every sampled
# token is body, every scaffold token isn't. The XML-style tool
# call tags (``<function=...>``, ``<parameter=...>``, etc.) are
# part of the model's emitted output too — keep them
# ``is_content=True`` per the assistant rule.
emit_thinking = self._should_render_thinking(msg_idx, last_query_index) or (
preserve_thinking and bool(reasoning_content)
)
if emit_thinking:
# Include thinking block
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text("\n\n" + content, msg_idx, is_sampled=True)
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
emit_text(
"\n" + reasoning_content + "\n",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
emit_text("\n\n" + content, msg_idx, is_sampled=True, is_content=True)
else:
emit_text(content, msg_idx, is_sampled=True)
emit_text(content, msg_idx, is_sampled=True, is_content=True)
# Tool calls
tool_calls = msg.get("tool_calls") or []
@@ -786,13 +972,18 @@ class Qwen35Renderer:
# Separator before <tool_call>
if tc_idx == 0:
if content.strip():
emit_text("\n\n", msg_idx, is_sampled=True)
emit_text("\n\n", msg_idx, is_sampled=True, is_content=True)
# else: no separator
else:
emit_text("\n", msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_text("\n<function=" + name + ">\n", msg_idx, is_sampled=True)
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
emit_text(
"\n<function=" + name + ">\n",
msg_idx,
is_sampled=True,
is_content=True,
)
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
@@ -813,16 +1004,20 @@ class Qwen35Renderer:
+ "\n</parameter>\n",
msg_idx,
is_sampled=True,
is_content=True,
)
emit_text("</function>\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_text("</function>\n", msg_idx, is_sampled=True, is_content=True)
emit_special(
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
# end its turn, so it is part of the sampled stream (and the
# assistant's body). The trailing ``\n`` is template-appended
# between turns and never sampled — scaffold for is_content too.
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
# ------------------------------------------------------------------
# Tool message rendering
@@ -836,6 +1031,7 @@ class Qwen35Renderer:
emit_special,
emit_text,
emit_image,
emit_text_segments,
) -> None:
# Consecutive tool messages share a single <|im_start|>user ... <|im_end|>
# envelope. Whether to open and close the envelope depends only on the
@@ -843,9 +1039,11 @@ class Qwen35Renderer:
# tool message — keep this predicate text/media-agnostic.
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False. The bridge's
# local emit_special / emit_text accept the is_sampled kwarg for
# signature compatibility but ignore it.
# tokens, so every emission is is_sampled=False. The ``content``
# field's body bytes get ``is_content=True``; everything else —
# the ``<|im_start|>user`` wrap, the inter-section ``\n``s, the
# ``<|tool_response>`` specials — is scaffold so the SFT mask
# for tool body never trains the model to emit them.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
@@ -853,11 +1051,11 @@ class Qwen35Renderer:
raw_content = messages[msg_idx].get("content")
if not prev_is_tool:
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("user", msg_idx, is_sampled=False)
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
emit_text("user", msg_idx, is_sampled=False, is_content=False)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._tool_response, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
emit_special(self._tool_response, msg_idx, is_sampled=False, is_content=False)
if self._content_has_media(raw_content):
# Mirror the chat template's ``render_content`` macro for list
@@ -867,16 +1065,22 @@ class Qwen35Renderer:
# ``_content_has_media`` returns False unless content is a list,
# but the type checker can't follow that through the call.
assert isinstance(raw_content, list)
buf: list[str] = ["\n"]
# First flush: leading ``"\n"`` is scaffold (separates the
# ``<|tool_response>`` special from the body); subsequent
# text items in this run are body. After a media break, the
# buffer resets to pure body until the next media break or
# end-of-content.
buf_segments: list[tuple[str, bool]] = [("\n", False)]
def flush_buf() -> None:
if buf:
emit_text("".join(buf), msg_idx, is_sampled=False)
buf.clear()
if buf_segments:
emit_text_segments(buf_segments, msg_idx, is_sampled=False)
buf_segments.clear()
for item in raw_content:
if isinstance(item, str):
buf.append(item)
if item:
buf_segments.append((item, True))
elif isinstance(item, dict):
if _is_image_part(item):
flush_buf()
@@ -886,19 +1090,29 @@ class Qwen35Renderer:
"Video parts are not yet supported by Qwen35Renderer."
)
elif "text" in item:
buf.append(item["text"])
if item["text"]:
buf_segments.append((item["text"], True))
else:
raise ValueError(f"Unexpected content item: {item}")
else:
raise ValueError(f"Unexpected content item: {item}")
flush_buf()
emit_text("\n", msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
else:
content = self._render_content(raw_content).strip()
emit_text("\n" + content + "\n", msg_idx, is_sampled=False)
# ``\n`` + content + ``\n`` — body is the middle segment only.
# Single BPE pass over the joined text preserves boundary
# merges.
emit_text_segments(
[("\n", False), (content, True), ("\n", False)],
msg_idx,
is_sampled=False,
)
emit_special(self._tool_response_end, msg_idx, is_sampled=False)
emit_special(
self._tool_response_end, msg_idx, is_sampled=False, is_content=False
)
if not next_is_tool:
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
+9 -6
View File
@@ -7,12 +7,12 @@ Delta vs Qwen3.5 (template line 122):
``None`` as ``null`` (not ``None``), fixing the single-turn extension-break
mode where a boolean parameter's case drifted across a re-render.
The template's other delta vs Qwen3.5 (a ``preserve_thinking`` toggle that
flips historical ``<think>`` retention on or off globally) is no longer
exposed as a constructor kwarg — its default-False behaviour matches
Qwen3.5 and is now baked in. Callers who want the toggled-on behaviour
pass ``preserve_all_thinking=True`` to ``create_renderer``, the
renderer-agnostic spelling of the same intent.
Historical-thinking retention follows Qwen3.5's default (drop past
``<think>`` blocks). The upstream template carries a ``preserve_thinking``
Jinja toggle for the opposite polarity; on the renderer side that intent
maps to the renderer-agnostic ``preserve_all_thinking`` /
``preserve_thinking_between_tool_calls`` flags on
:class:`renderers.Qwen36RendererConfig`.
Everything else — tool system prompt, tool-call XML structure, thinking
markers, bridge logic, parser — is identical to Qwen3.5.
@@ -23,12 +23,15 @@ from __future__ import annotations
import json
from typing import Any
from renderers.configs import Qwen36RendererConfig
from renderers.qwen35 import Qwen35Renderer
class Qwen36Renderer(Qwen35Renderer):
"""Deterministic message → token renderer for Qwen3.6 models."""
_config_cls = Qwen36RendererConfig
@staticmethod
def _render_arg_value(arg_value: Any) -> str:
if isinstance(arg_value, str):
+268 -118
View File
@@ -42,9 +42,12 @@ from renderers.base import (
PlaceholderRange,
RenderedTokens,
ToolSpec,
attribute_text_segments,
extract_message_tool_names,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.configs import Qwen3VLRendererConfig
from renderers.parsing import parse_qwen3
_TOOLS_HEADER = (
@@ -70,9 +73,14 @@ def _is_image_part(item: Any) -> bool:
t = item.get("type")
if t in ("image", "image_url"):
return True
# Permissive fallback: chat templates check ``'image' in content`` to
# accept loosely-shaped image parts, so mirror that.
return "image" in item or "image_url" in item
if t is not None:
return False
# Untyped fallback for loosely-shaped image parts. Require a truthy
# value: HF Arrow schema unification (Dataset.from_list over a list of
# heterogeneous content dicts) fills missing keys with None, so any
# text part round-tripped through a Dataset will have ``image_url: None``
# as a key. Mere key presence isn't enough.
return bool(item.get("image")) or bool(item.get("image_url"))
def _is_video_part(item: Any) -> bool:
@@ -81,7 +89,9 @@ def _is_video_part(item: Any) -> bool:
t = item.get("type")
if t in ("video", "video_url"):
return True
return "video" in item or "video_url" in item
if t is not None:
return False
return bool(item.get("video")) or bool(item.get("video_url"))
def _load_pil_image(item: dict[str, Any]):
@@ -170,14 +180,31 @@ class _Emitter:
value than the current buffer triggers a flush first — split points
are always at the ``is_sampled`` boundary, which the caller is
expected to place at a ``\\n`` boundary so BPE merges don't drift.
``is_content`` is the per-token body/scaffold attribution. Within a
single flush adjacent text fragments may carry different
``is_content`` values (e.g. ``"user\\n"`` scaffold + caller content
body): the buffer stores fragments as a list of
``(text, is_content)`` segments and flushes via
:func:`attribute_text_segments`, which performs one BPE pass over
the joined text and assigns per-token is_content from each token's
source segment. When every segment in a flush shares the same
is_content (the common case for sampled assistant body / pure
scaffold) the fast path of a single ``encode()`` call is used and
no offset-tokenizer lookup is required.
"""
def __init__(self, encode_fn, msg_idx: int = -1):
def __init__(self, encode_fn, tokenizer=None, msg_idx: int = -1):
self._encode = encode_fn
self._tokenizer = tokenizer
self.token_ids: list[int] = []
self.message_indices: list[int] = []
self.sampled: list[bool] = []
self._buf: str = ""
self.is_content: list[bool] = []
# Buffered text fragments as ``(text, is_content)`` tuples. All
# fragments share a single ``_buf_sampled`` / ``_buf_idx``;
# changing either of those triggers a flush.
self._segments: list[tuple[str, bool]] = []
self._buf_idx: int = msg_idx
self._buf_sampled: bool = False
self.msg_idx = msg_idx
@@ -187,49 +214,78 @@ class _Emitter:
# text doesn't get glued to the previous one's BPE context.
# In practice messages are always separated by an <|im_end|>
# special token, which already flushes — but be defensive.
if self._buf:
if self._segments:
self._flush()
self.msg_idx = msg_idx
self._buf_idx = msg_idx
def text(self, text: str, *, is_sampled: bool) -> None:
def text(self, text: str, *, is_sampled: bool, is_content: bool) -> None:
if not text:
return
# Adjacent text under different msg_idx or is_sampled is rare in
# this template — but flush at those boundaries so attribution
# and the sampled signal stay accurate.
if self._buf and (
# and the sampled signal stay accurate. is_content boundaries do
# NOT force a flush: they're carried through the joined BPE pass
# via :func:`attribute_text_segments`, preserving merges across
# the wrap/body boundary.
if self._segments and (
self._buf_idx != self.msg_idx or self._buf_sampled != is_sampled
):
self._flush()
if not self._buf:
if not self._segments:
self._buf_idx = self.msg_idx
self._buf_sampled = is_sampled
self._buf += text
self._segments.append((text, is_content))
def special(self, token_id: int, *, is_sampled: bool) -> None:
if self._buf:
def special(self, token_id: int, *, is_sampled: bool, is_content: bool) -> None:
if self._segments:
self._flush()
self.token_ids.append(token_id)
self.message_indices.append(self.msg_idx)
self.sampled.append(is_sampled)
self.is_content.append(is_content)
def cursor(self) -> int:
"""Current token offset after flushing — used to anchor placeholder ranges."""
if self._buf:
if self._segments:
self._flush()
return len(self.token_ids)
def finalize(self) -> None:
if self._buf:
if self._segments:
self._flush()
def _flush(self) -> None:
ids = self._encode(self._buf)
self.token_ids.extend(ids)
self.message_indices.extend([self._buf_idx] * len(ids))
self.sampled.extend([self._buf_sampled] * len(ids))
self._buf = ""
segments = self._segments
self._segments = []
if not segments:
return
# Fast path: every segment shares the same is_content — use the
# plain ``encode()`` call so we don't pay for the offset
# tokenizer. This is the common case (pure scaffold flushes, or
# pure body flushes).
first_ic = segments[0][1]
all_same = all(ic == first_ic for _, ic in segments)
if all_same:
joined = "".join(text for text, _ in segments)
ids = self._encode(joined)
self.token_ids.extend(ids)
self.message_indices.extend([self._buf_idx] * len(ids))
self.sampled.extend([self._buf_sampled] * len(ids))
self.is_content.extend([first_ic] * len(ids))
return
# Mixed body/scaffold flush — encode once and attribute back to
# each segment via the fast tokenizer's offset_mapping. Requires
# a tokenizer (not just the encode fn) to look up offsets.
assert self._tokenizer is not None, (
"_Emitter mixed-is_content flush requires a tokenizer; "
"pass one to the constructor."
)
for tok_id, is_content in attribute_text_segments(self._tokenizer, segments):
self.token_ids.append(tok_id)
self.message_indices.append(self._buf_idx)
self.sampled.append(self._buf_sampled)
self.is_content.append(is_content)
class Qwen3VLRenderer:
@@ -237,35 +293,30 @@ class Qwen3VLRenderer:
Constructor args:
tokenizer: HF tokenizer for the model.
config: Typed renderer config (see
:class:`renderers.Qwen3VLRendererConfig`). Defaults to a
blank config with template defaults.
processor: Optional ``Qwen3VLProcessor``. Required when rendering
messages that contain image / video parts. If not supplied,
the renderer lazy-loads it via ``AutoProcessor.from_pretrained``
keyed off ``tokenizer.name_or_path`` the first time a
multimodal part is seen.
preserve_all_thinking / preserve_thinking_between_tool_calls:
No-ops on Qwen3-VL — the chat template already drops past
``<think>`` blocks unconditionally. Stored for Protocol parity.
image_cache_max: Max entries in the per-instance image-processor
cache (FIFO eviction). Default 256 covers typical RL pools
(``rollouts_per_example`` × in-flight examples). Bump for runs
with large image sets where the working set exceeds the cap.
``preserve_all_thinking`` / ``preserve_thinking_between_tool_calls``
on the config are no-ops here — the chat template drops past
``<think>`` blocks unconditionally. Stored for Protocol parity.
"""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
config: Qwen3VLRendererConfig | None = None,
*,
processor: Any = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
image_cache_max: int = 256,
):
self._tokenizer = tokenizer
self._processor = processor
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self.config = config or Qwen3VLRendererConfig()
self._im_start = self._token_id("<|im_start|>")
self._im_end = self._token_id("<|im_end|>")
@@ -274,6 +325,7 @@ class Qwen3VLRenderer:
self._tool_call_end = self._token_id("</tool_call>")
self._tool_response = self._token_id("<tool_response>")
self._tool_response_end = self._token_id("</tool_response>")
self._think_end = self._token_id("</think>")
self._vision_start = self._token_id("<|vision_start|>")
self._vision_end = self._token_id("<|vision_end|>")
self._image_pad = self._token_id("<|image_pad|>")
@@ -288,7 +340,6 @@ class Qwen3VLRenderer:
# tuples of ``(processor_out, num_image_tokens)`` — bounded to
# avoid unbounded growth on long-lived pools.
self._image_cache: dict[str, tuple[Any, int]] = {}
self._image_cache_max = image_cache_max
def _token_id(self, token: str) -> int:
tid = self._tokenizer.convert_tokens_to_ids(token)
@@ -377,7 +428,7 @@ class Qwen3VLRenderer:
grid_thw = out["image_grid_thw"][0]
merge_size = proc.image_processor.merge_size
num_image_tokens = int(grid_thw.prod()) // (merge_size * merge_size)
if len(self._image_cache) >= self._image_cache_max:
if len(self._image_cache) >= self.config.image_cache_max:
# FIFO eviction — Python dicts preserve insertion order, so
# ``next(iter(...))`` is the oldest key.
self._image_cache.pop(next(iter(self._image_cache)))
@@ -394,21 +445,38 @@ class Qwen3VLRenderer:
if not messages:
raise ValueError("No messages provided.")
em = _Emitter(self._encode)
em = _Emitter(self._encode, tokenizer=self._tokenizer)
mm_hashes: dict[str, list[str]] = {}
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
mm_items: dict[str, list[dict[str, Any]]] = {}
# ``add_vision_id`` mirrors the Jinja's ``image_count`` /
# ``video_count`` namespaces. Counters are 1-indexed and run
# across the entire conversation; they increment unconditionally
# on each image / video (the Qwen3-VL template increments first,
# then emits ``Picture N: `` only when ``add_vision_id`` is set).
vision_counts = {"image": 0, "video": 0}
def emit_image(part: dict[str, Any]) -> None:
# Image placeholders are prompt-side scaffolding the user
# message attaches — the model never samples ``<|vision_start|>``
# / ``<|image_pad|>`` / ``<|vision_end|>``.
# / ``<|image_pad|>`` / ``<|vision_end|>``. The
# ``<|image_pad|>`` placeholders represent caller-provided
# image data, so they ARE body content (is_content=True);
# the surrounding ``<|vision_start|>`` / ``<|vision_end|>``
# markers are renderer-emitted scaffold.
_, out, n, h = self._process_image(part)
em.special(self._vision_start, is_sampled=False)
vision_counts["image"] += 1
if self.config.add_vision_id:
em.text(
f"Picture {vision_counts['image']}: ",
is_sampled=False,
is_content=False,
)
em.special(self._vision_start, is_sampled=False, is_content=False)
offset = em.cursor()
for _ in range(n):
em.special(self._image_pad, is_sampled=False)
em.special(self._vision_end, is_sampled=False)
em.special(self._image_pad, is_sampled=False, is_content=True)
em.special(self._vision_end, is_sampled=False, is_content=False)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -425,16 +493,24 @@ class Qwen3VLRenderer:
User / tool content is conversation context the model never
samples — every text fragment goes in as ``is_sampled=False``.
Text from the caller IS the message body, so every text
fragment is ``is_content=True``; the vision-marker specials
around image_pad placeholders are scaffold (handled in
:func:`emit_image`).
"""
if isinstance(content, str):
em.text(content, is_sampled=False)
em.text(content, is_sampled=False, is_content=True)
return
if not isinstance(content, list):
em.text(self._render_text_content(content), is_sampled=False)
em.text(
self._render_text_content(content),
is_sampled=False,
is_content=True,
)
return
for item in content:
if isinstance(item, str):
em.text(item, is_sampled=False)
em.text(item, is_sampled=False, is_content=True)
elif isinstance(item, dict):
if _is_image_part(item):
emit_image(item)
@@ -443,7 +519,7 @@ class Qwen3VLRenderer:
"Video parts are not yet supported by Qwen3VLRenderer."
)
elif "text" in item:
em.text(item["text"], is_sampled=False)
em.text(item["text"], is_sampled=False, is_content=True)
# ── 1. System + tools ───────────────────────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -451,26 +527,37 @@ class Qwen3VLRenderer:
if tools:
sys_idx = 0 if first_is_system else -1
em.set_msg_idx(sys_idx)
em.special(self._im_start, is_sampled=False)
buf = "system\n"
em.special(self._im_start, is_sampled=False, is_content=False)
# Body = system content (if any). Everything else in this
# block — role tag, tools header / footer, JSON tool specs —
# is scaffold. The tools dict is recoverable from the
# ``tools`` argument; we don't re-attribute its embedded
# JSON as message body.
em.text("system\n", is_sampled=False, is_content=False)
if first_is_system:
buf += self._render_text_content(messages[0].get("content")) + "\n\n"
buf += _TOOLS_HEADER
sys_content = self._render_text_content(messages[0].get("content"))
if sys_content:
em.text(sys_content, is_sampled=False, is_content=True)
em.text("\n\n", is_sampled=False, is_content=False)
em.text(_TOOLS_HEADER, is_sampled=False, is_content=False)
for tool in tools:
buf += "\n" + json.dumps(tool, ensure_ascii=False)
buf += _TOOLS_FOOTER
em.text(buf, is_sampled=False)
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
em.text(
"\n" + json.dumps(tool, ensure_ascii=False),
is_sampled=False,
is_content=False,
)
em.text(_TOOLS_FOOTER, is_sampled=False, is_content=False)
em.special(self._im_end, is_sampled=False, is_content=False)
em.text("\n", is_sampled=False, is_content=False)
elif first_is_system:
em.set_msg_idx(0)
em.special(self._im_start, is_sampled=False)
em.text(
"system\n" + self._render_text_content(messages[0].get("content")),
is_sampled=False,
)
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
em.special(self._im_start, is_sampled=False, is_content=False)
em.text("system\n", is_sampled=False, is_content=False)
sys_content = self._render_text_content(messages[0].get("content"))
if sys_content:
em.text(sys_content, is_sampled=False, is_content=True)
em.special(self._im_end, is_sampled=False, is_content=False)
em.text("\n", is_sampled=False, is_content=False)
# ── 2. Iterate messages ─────────────────────────────────────
for i, msg in enumerate(messages):
@@ -482,11 +569,11 @@ class Qwen3VLRenderer:
em.set_msg_idx(i)
if role == "user":
em.special(self._im_start, is_sampled=False)
em.text("user\n", is_sampled=False)
em.special(self._im_start, is_sampled=False, is_content=False)
em.text("user\n", is_sampled=False, is_content=False)
render_media_content(msg.get("content"))
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
em.special(self._im_end, is_sampled=False, is_content=False)
em.text("\n", is_sampled=False, is_content=False)
elif role == "assistant":
self._render_assistant(msg, em)
@@ -500,8 +587,8 @@ class Qwen3VLRenderer:
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
em.set_msg_idx(-1)
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
em.special(self._im_start, is_sampled=False, is_content=False)
em.text("assistant\n", is_sampled=False, is_content=False)
em.finalize()
@@ -517,6 +604,9 @@ class Qwen3VLRenderer:
token_ids=em.token_ids,
message_indices=em.message_indices,
sampled_mask=em.sampled,
is_content=em.is_content,
message_roles=[m.get("role") or "" for m in messages],
message_tool_names=extract_message_tool_names(messages),
multi_modal_data=mm_data,
)
@@ -545,6 +635,7 @@ class Qwen3VLRenderer:
stop_ids={self._im_end, self._endoftext},
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
reasoning_end_id=self._think_end,
)
def get_stop_token_ids(self) -> list[int]:
@@ -584,30 +675,74 @@ class Qwen3VLRenderer:
if previous_ids is None:
return None
# Bridge output is consumed as the next turn's prompt — the
# caller blanket-masks it via ``prompt_mask=[False]*N``, so we
# don't surface a sampled_mask here. The shared ``_render_tool``
# helper still routes through ``em.special``/``em.text`` with
# ``is_sampled`` kwargs, which the emitter accepts and tracks,
# but the returned ``RenderedTokens`` leaves ``sampled_mask``
# empty (the field defaults to ``[]``).
em = _Emitter(self._encode)
# ``add_vision_id`` numbers placeholders across the whole
# conversation. The bridge can only seed that counter from
# ``previous_multi_modal_data`` (raw prior token ids don't carry
# the image/video count back), so if the caller asks for
# ``add_vision_id=True`` while omitting prior mm-data on a
# conversation that already contains images, the bridged
# output would silently emit ``Picture 1:`` again. Refuse the
# bridge in that case — the caller falls back to a full
# re-render, which has the full message list and counts
# correctly.
if (
self.config.add_vision_id
and previous_multi_modal_data is None
and self._vision_start in previous_ids
):
return None
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). ``is_content`` follows the same
# rules as in :meth:`render` so consumers can walk the trajectory
# and read each step's own body mask. Downstream consumers can
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
# output to get per-new-message token counts without re-rendering.
em = _Emitter(self._encode, tokenizer=self._tokenizer)
# Seed the emitter with the prior turn's tokens so cursor() reports
# absolute offsets in the combined sequence.
# absolute offsets in the combined sequence. Per-token attribution
# for the prior portion is unknown to the bridge (it only has
# prev_prompt_ids + prev_completion_ids as raw lists), so seed
# all side channels with the "no info" sentinel.
em.token_ids = list(previous_ids)
em.message_indices = [-1] * len(previous_ids)
em.sampled = [False] * len(previous_ids)
em.is_content = [False] * len(previous_ids)
new_hashes: dict[str, list[str]] = {}
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
# Seed the vision counters from any prior-turn images / videos
# the bridge was handed via ``previous_multi_modal_data``. The
# ``add_vision_id`` template numbers placeholders across the
# whole conversation, so a new turn's first image is
# ``Picture {prev_total + 1}``. The bridge can't recover this
# count from raw token ids, so callers must thread
# ``previous_multi_modal_data`` through when they want
# ``add_vision_id`` parity across turns.
prev_image_count = 0
prev_video_count = 0
if previous_multi_modal_data is not None:
prev_image_count = len(previous_multi_modal_data.mm_items.get("image", []))
prev_video_count = len(previous_multi_modal_data.mm_items.get("video", []))
vision_counts = {"image": prev_image_count, "video": prev_video_count}
def emit_image(part: dict[str, Any]) -> None:
_, out, n, h = self._process_image(part)
em.special(self._vision_start, is_sampled=False)
vision_counts["image"] += 1
if self.config.add_vision_id:
em.text(
f"Picture {vision_counts['image']}: ",
is_sampled=False,
is_content=False,
)
em.special(self._vision_start, is_sampled=False, is_content=False)
offset = em.cursor()
for _ in range(n):
em.special(self._image_pad, is_sampled=False)
em.special(self._vision_end, is_sampled=False)
em.special(self._image_pad, is_sampled=False, is_content=True)
em.special(self._vision_end, is_sampled=False, is_content=False)
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -621,14 +756,18 @@ class Qwen3VLRenderer:
def render_media_content(content: Any) -> None:
if isinstance(content, str):
em.text(content, is_sampled=False)
em.text(content, is_sampled=False, is_content=True)
return
if not isinstance(content, list):
em.text(self._render_text_content(content), is_sampled=False)
em.text(
self._render_text_content(content),
is_sampled=False,
is_content=True,
)
return
for item in content:
if isinstance(item, str):
em.text(item, is_sampled=False)
em.text(item, is_sampled=False, is_content=True)
elif isinstance(item, dict):
if _is_image_part(item):
emit_image(item)
@@ -637,34 +776,34 @@ class Qwen3VLRenderer:
"Video parts are not yet supported by Qwen3VLRenderer."
)
elif "text" in item:
em.text(item["text"], is_sampled=False)
em.text(item["text"], is_sampled=False, is_content=True)
em.set_msg_idx(-1)
em.text("\n", is_sampled=False)
em.text("\n", is_sampled=False, is_content=False)
for i, msg in enumerate(new_messages):
role = msg.get("role")
em.set_msg_idx(i)
if role == "user":
em.special(self._im_start, is_sampled=False)
em.text("user\n", is_sampled=False)
em.special(self._im_start, is_sampled=False, is_content=False)
em.text("user\n", is_sampled=False, is_content=False)
render_media_content(msg.get("content"))
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
em.special(self._im_end, is_sampled=False, is_content=False)
em.text("\n", is_sampled=False, is_content=False)
elif role == "system":
em.special(self._im_start, is_sampled=False)
em.text("system\n", is_sampled=False)
em.special(self._im_start, is_sampled=False, is_content=False)
em.text("system\n", is_sampled=False, is_content=False)
render_media_content(msg.get("content"))
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
em.special(self._im_end, is_sampled=False, is_content=False)
em.text("\n", is_sampled=False, is_content=False)
elif role == "tool":
self._render_tool(new_messages, i, em, render_media_content)
else:
return None
em.set_msg_idx(-1)
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
em.special(self._im_start, is_sampled=False, is_content=False)
em.text("assistant\n", is_sampled=False, is_content=False)
em.finalize()
# Merge prev mm_data with the new turn's items.
@@ -700,6 +839,11 @@ class Qwen3VLRenderer:
return RenderedTokens(
token_ids=em.token_ids,
message_indices=em.message_indices,
sampled_mask=em.sampled,
is_content=em.is_content,
message_roles=[m.get("role") or "" for m in new_messages],
message_tool_names=extract_message_tool_names(new_messages),
multi_modal_data=mm_data,
)
@@ -712,20 +856,22 @@ class Qwen3VLRenderer:
# at inference the chat template emits these as the generation
# prompt and the model never samples them. Splitting the text
# at the ``\n`` after the role tag is safe: Qwen3 BPE treats
# ``\n`` as a token boundary.
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
# ``\n`` as a token boundary. For the assistant role the
# invariant ``is_content == sampled_mask`` holds — every sampled
# token is body, every scaffold token isn't.
em.special(self._im_start, is_sampled=False, is_content=False)
em.text("assistant\n", is_sampled=False, is_content=False)
# Body (content + tool calls) is the model-sampled portion.
if not tool_calls:
em.text(content, is_sampled=True)
em.text(content, is_sampled=True, is_content=True)
else:
for tc_idx, tc in enumerate(tool_calls):
if tc_idx == 0:
separator = "\n" if original_content else ""
em.text(content + separator, is_sampled=True)
em.text(content + separator, is_sampled=True, is_content=True)
else:
em.text("\n", is_sampled=True)
em.text("\n", is_sampled=True, is_content=True)
func = tc.get("function") or tc
name = func.get("name", "")
@@ -736,18 +882,19 @@ class Qwen3VLRenderer:
else json.dumps(arguments, ensure_ascii=False)
)
em.special(self._tool_call, is_sampled=True)
em.special(self._tool_call, is_sampled=True, is_content=True)
em.text(
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
is_sampled=True,
is_content=True,
)
em.special(self._tool_call_end, is_sampled=True)
em.special(self._tool_call_end, is_sampled=True, is_content=True)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn. The trailing ``\n`` is template-appended between
# turns and never sampled.
em.special(self._im_end, is_sampled=True)
em.text("\n", is_sampled=False)
# end its turn (and counts as part of its body). The trailing
# ``\n`` is template-appended between turns and never sampled.
em.special(self._im_end, is_sampled=True, is_content=True)
em.text("\n", is_sampled=False, is_content=False)
def _render_tool(
self,
@@ -758,24 +905,27 @@ class Qwen3VLRenderer:
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False. (render_media_content
# also stamps is_sampled=False on its emissions.)
# tokens, so every emission is is_sampled=False. The
# ``content`` body bytes get ``is_content=True`` (via
# ``render_media_content``); everything else — the
# ``<|im_start|>user`` wrap, inter-section ``\n``s, and the
# ``<|tool_response>`` specials — is scaffold.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
)
if not prev_is_tool:
em.special(self._im_start, is_sampled=False)
em.text("user", is_sampled=False)
em.special(self._im_start, is_sampled=False, is_content=False)
em.text("user", is_sampled=False, is_content=False)
em.text("\n", is_sampled=False)
em.special(self._tool_response, is_sampled=False)
em.text("\n", is_sampled=False)
em.text("\n", is_sampled=False, is_content=False)
em.special(self._tool_response, is_sampled=False, is_content=False)
em.text("\n", is_sampled=False, is_content=False)
render_media_content(messages[msg_idx].get("content"))
em.text("\n", is_sampled=False)
em.special(self._tool_response_end, is_sampled=False)
em.text("\n", is_sampled=False, is_content=False)
em.special(self._tool_response_end, is_sampled=False, is_content=False)
if not next_is_tool:
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
em.special(self._im_end, is_sampled=False, is_content=False)
em.text("\n", is_sampled=False, is_content=False)
+46 -1
View File
@@ -10,6 +10,7 @@ import pytest
from renderers import create_renderer
from renderers.base import load_tokenizer
from renderers.configs import config_from_name
# (HuggingFace model name, renderer name or "auto")
#
@@ -32,7 +33,24 @@ RENDERER_MODELS = [
("moonshotai/Kimi-K2.6", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
# Ultra resolves to the `nemotron-3-ultra` config variant via the model
# name (auto → MODEL_RENDERER_MAP → nemotron-3-ultra).
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
("poolside/Laguna-XS.2", "auto"),
# 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"),
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
]
@@ -44,7 +62,7 @@ def _load(model_name: str, renderer_name: str):
key = f"{model_name}:{renderer_name}"
if key not in _cache:
tokenizer = load_tokenizer(model_name)
renderer = create_renderer(tokenizer, renderer=renderer_name)
renderer = create_renderer(tokenizer, config_from_name(renderer_name))
_cache[key] = (tokenizer, renderer)
return _cache[key]
@@ -102,3 +120,30 @@ def _skip_gpt_oss_for_hf_parity_tests(request):
f"{model_name}: renderer matches openai-harmony / vLLM, not HF "
"apply_chat_template — see test_gpt_oss_harmony_parity.py"
)
# Llama-3's chat template fills the "Today Date:" line via ``strftime_now``,
# so ``apply_chat_template`` with no explicit ``date_string`` bakes in the
# real wall-clock date — non-deterministic and not byte-stable against a
# renderer pinned to "26 Jul 2024". Generic HF-parity tests can't pass a
# kwarg, so they're skipped here; deterministic byte-parity (with the date
# passed on both sides) is covered in test_llama_3.py.
_LLAMA_HF_PARITY_TEST_FILES = {
"test_render_ids.py",
"test_build_helpers.py",
}
@pytest.fixture(autouse=True)
def _skip_llama_for_hf_parity_tests(request):
callspec = getattr(request.node, "callspec", None)
model_name = callspec.params.get("model_name") if callspec else None
if model_name != "meta-llama/Llama-3.2-1B-Instruct":
return
test_file = os.path.basename(str(request.node.fspath))
if test_file in _LLAMA_HF_PARITY_TEST_FILES:
pytest.skip(
f"{model_name}: template uses strftime_now for the date line, so "
"generic apply_chat_template parity is non-deterministic — "
"deterministic byte-parity is covered in test_llama_3.py"
)
+3 -1
View File
@@ -33,6 +33,7 @@ _BRIDGE_MODELS = [
("moonshotai/Kimi-K2-Instruct", "auto"),
("moonshotai/Kimi-K2.5", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
("openai/gpt-oss-20b", "gpt-oss"),
]
@@ -41,9 +42,10 @@ _BRIDGE_MODELS = [
def _load(model_name: str, renderer_name: str):
from renderers import create_renderer
from renderers.base import load_tokenizer
from renderers.configs import config_from_name
tok = load_tokenizer(model_name)
return tok, create_renderer(tok, renderer=renderer_name)
return tok, create_renderer(tok, config_from_name(renderer_name))
def pytest_generate_tests(metafunc):
+227 -16
View File
@@ -1,8 +1,10 @@
import asyncio
import base64
import json
import httpx
import numpy as np
import pytest
from renderers.base import (
ParsedResponse,
ParsedToolCall,
@@ -19,7 +21,15 @@ class _FakeRenderer:
assert messages == [{"role": "user", "content": "hi"}]
assert tools == [{"type": "function", "function": {"name": "echo"}}]
assert add_generation_prompt is True
return RenderedTokens(token_ids=[1, 2, 3])
# Populate the full attribution surface so the test can verify
# ``generate`` threads it through to the result dict unchanged.
return RenderedTokens(
token_ids=[1, 2, 3],
message_indices=[0, 0, -1],
sampled_mask=[False, False, False],
is_content=[False, True, False],
message_roles=["user"],
)
def render_ids(self, messages, *, tools=None, add_generation_prompt=False):
return self.render(
@@ -62,8 +72,8 @@ class _FakeClient:
self.calls.append(
{"path": path, "cast_to": cast_to, "body": body, "options": options}
)
routed_experts = np.array([[[1]], [[2]]], dtype=np.int32)
return {
routed_experts = np.array([[[1]], [[2]]], dtype=np.uint8)
payload = {
"request_id": "gen-test",
"choices": [
{
@@ -77,7 +87,7 @@ class _FakeClient:
},
"finish_reason": "stop",
"routed_experts": {
"data": base64.b85encode(routed_experts.tobytes()).decode(
"data": base64.b64encode(routed_experts.tobytes()).decode(
"ascii"
),
"shape": list(routed_experts.shape),
@@ -85,6 +95,10 @@ class _FakeClient:
}
],
}
return httpx.Response(
200,
content=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
)
def test_generate_builds_request_body_and_parses_response():
@@ -113,6 +127,7 @@ def test_generate_builds_request_body_and_parses_response():
# /inference/v1/generate is mounted at the server root, so we post to
# an absolute URL stripped of the OpenAI SDK's automatic /v1 prefix.
assert client.calls[0]["path"] == "http://fake-host:8000/inference/v1/generate"
assert client.calls[0]["cast_to"] is httpx.Response
assert client.calls[0]["body"] == {
"model": "test-model",
"token_ids": [1, 2, 3],
@@ -134,9 +149,22 @@ def test_generate_builds_request_body_and_parses_response():
assert result["prompt_ids"] == [1, 2, 3]
assert result["completion_ids"] == [7, 8]
assert result["completion_logprobs"] == [-0.1, -0.2]
assert result["routed_experts"] == [[[1]], [[2]]]
assert result["routed_experts"]["shape"] == [2, 1, 1]
assert isinstance(result["routed_experts"]["data"], memoryview)
assert result["routed_experts"]["data"].tobytes() == base64.b64encode(b"\x01\x02")
assert result["multi_modal_data"] is None
assert result["request_id"] == "gen-test"
# Per-token attribution from the renderer surfaces on the result so
# downstream consumers (verifiers RendererClient → prime-rl) can
# build selective loss masks without a second render pass.
attr = result["prompt_attribution"]
assert attr is not None
assert isinstance(attr, RenderedTokens)
assert attr.token_ids == [1, 2, 3]
assert attr.is_content == [False, True, False]
assert attr.sampled_mask == [False, False, False]
assert attr.message_indices == [0, 0, -1]
assert attr.message_roles == ["user"]
assert len(result["tool_calls"]) == 1
tc = result["tool_calls"][0]
assert tc.name == "echo"
@@ -207,6 +235,44 @@ def test_generate_uses_prebuilt_prompt_ids_without_rendering():
assert client.calls[0]["body"]["token_ids"] == [11, 12, 13]
assert result["prompt_ids"] == [11, 12, 13]
# Pre-built prompt without explicit attribution → ``None`` carried
# through. Consumers fall back to whatever attribution-free path
# they have (e.g. uniform completion mask).
assert result["prompt_attribution"] is None
def test_generate_threads_prompt_attribution_through_prebuilt_prompt_path():
"""When the caller passes both ``prompt_ids`` and ``prompt_attribution``
(the multi-turn bridge path in verifiers), ``generate`` must thread
the attribution through to the result dict unchanged — no re-rendering,
no per-token reshuffling. Lets downstream consumers carry the
renderer's body/scaffold cut into the trajectory step without an
extra render pass."""
client = _FakeClient()
# Caller-supplied attribution; mirrors what
# ``RendererClient._get_incremental_prompt_ids`` returns from the
# bridge_to_next_turn output.
supplied = RenderedTokens(
token_ids=[11, 12, 13],
message_indices=[-1, 0, 0],
sampled_mask=[False, False, False],
is_content=[False, True, True],
message_roles=["tool"],
)
result = asyncio.run(
generate(
client=client,
renderer=_NoRenderRenderer(),
messages=[{"role": "user", "content": "hi"}],
model="test-model",
prompt_ids=[11, 12, 13],
prompt_attribution=supplied,
)
)
# Exact passthrough — same object, no copy / no transform.
assert result["prompt_attribution"] is supplied
# ---------------------------------------------------------------------------
@@ -214,30 +280,42 @@ def test_generate_uses_prebuilt_prompt_ids_without_rendering():
# ---------------------------------------------------------------------------
def test_generate_serializes_multimodal_features_for_qwen3_vl():
@pytest.mark.parametrize(
"model_id,renderer_class_path",
[
("Qwen/Qwen3-VL-4B-Instruct", "renderers.qwen3_vl:Qwen3VLRenderer"),
("Qwen/Qwen3.5-2B", "renderers.qwen35:Qwen35Renderer"),
],
ids=["qwen3_vl", "qwen35"],
)
def test_generate_serializes_multimodal_features_for_qwen_vl_family(
model_id, renderer_class_path
):
"""When the renderer emits ``MultiModalData``, ``generate`` translates
it into vLLM's ``features`` payload (mm_hashes + mm_placeholders +
base64-encoded kwargs_data) and sticks it in the request body."""
import pytest as _pytest
base64-encoded kwargs_data) and sticks it in the request body. Covers
every renderer routed through ``_build_qwen_vl_features``."""
import importlib
_pytest.importorskip("torch")
_pytest.importorskip("vllm", reason="vllm needed for features serialization")
pytest.importorskip("torch")
pytest.importorskip("vllm", reason="vllm needed for features serialization")
import torch as _torch
from renderers.base import (
MultiModalData,
PlaceholderRange,
load_tokenizer,
)
from renderers.qwen3_vl import Qwen3VLRenderer
# Build a minimal real Qwen3VLRenderer so type dispatch in
mod_name, cls_name = renderer_class_path.split(":")
renderer_cls = getattr(importlib.import_module(mod_name), cls_name)
# Build a minimal real renderer so type dispatch in
# _build_mm_features hits the qwen branch. The tokenizer is only
# touched in __init__ to grab special-token ids; render() / etc.
# aren't called here because we pre-supply prompt_ids + mm_data.
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
renderer = Qwen3VLRenderer(tokenizer)
tokenizer = load_tokenizer(model_id)
renderer = renderer_cls(tokenizer)
# Two synthetic 1×2×2 images. Field factory expects pixel_values
# shape ``(sum_HW, embed_dim)`` and grid_thw shape ``(N, 3)``; the
@@ -291,3 +369,136 @@ def test_generate_serializes_multimodal_features_for_qwen3_vl():
# Items are base64 strings (encode_mm_kwargs_item output).
for item in features["kwargs_data"]["image"]:
assert isinstance(item, str) and len(item) > 0
# ---------------------------------------------------------------------------
# Prompt overflow handling.
# ---------------------------------------------------------------------------
class _LongRenderer(_FakeRenderer):
"""Renders a 10-token prompt regardless of input — enough to overflow a
small ``max_prompt_len``."""
def render(self, messages, *, tools=None, add_generation_prompt=False):
from renderers.base import RenderedTokens
return RenderedTokens(token_ids=list(range(10)))
def test_generate_raises_overlong_prompt_when_explicit_cap_exceeded():
"""Pre-flight overflow check: when an explicit ``max_prompt_len`` is set
and the rendered prompt is longer, ``generate`` raises
``OverlongPromptError`` without dispatching the request to the engine."""
from renderers.client import OverlongPromptError
client = _FakeClient()
renderer = _LongRenderer()
with pytest.raises(OverlongPromptError) as excinfo:
asyncio.run(
generate(
client=client,
renderer=renderer,
messages=[{"role": "user", "content": "hi"}],
model="test-model",
max_prompt_len=4,
)
)
assert excinfo.value.prompt_len == 10
assert excinfo.value.max_prompt_len == 4
assert client.calls == [], "request must not be dispatched on pre-flight fail"
def test_generate_allows_prompt_at_max_prompt_len():
"""A prompt exactly equal to ``max_prompt_len`` is allowed (the check is
strict ``>``); only longer prompts trip the pre-flight."""
client = _FakeClient()
renderer = _LongRenderer()
result = asyncio.run(
generate(
client=client,
renderer=renderer,
messages=[{"role": "user", "content": "hi"}],
model="test-model",
max_prompt_len=10,
)
)
assert len(client.calls) == 1
assert result["prompt_ids"] == list(range(10))
def test_generate_auto_discovers_max_prompt_len_from_models_endpoint():
"""When ``max_prompt_len`` is ``None`` (default), ``generate`` discovers
the cap via ``GET /v1/models`` and reads ``ModelCard.max_model_len``.
The result is cached per ``(base_url, model)`` so subsequent calls
don't re-query."""
from renderers.client import OverlongPromptError, _max_prompt_len_cache
class _ClientWithModels(_FakeClient):
def __init__(self):
super().__init__()
self.base_url = "http://disco-host:8000/v1"
self.models_calls = 0
async def get(self, path, *, cast_to):
self.models_calls += 1
assert path == "/models"
return {
"object": "list",
"data": [
{"id": "test-model", "max_model_len": 4},
{"id": "other", "max_model_len": 999},
],
}
# Clear cache so this test isn't affected by earlier ones.
_max_prompt_len_cache.clear()
client = _ClientWithModels()
renderer = _LongRenderer()
with pytest.raises(OverlongPromptError) as excinfo:
asyncio.run(
generate(
client=client,
renderer=renderer,
messages=[{"role": "user", "content": "hi"}],
model="test-model",
)
)
assert excinfo.value.max_prompt_len == 4
assert excinfo.value.prompt_len == 10
assert client.models_calls == 1, "lookup must hit /models once"
assert client.calls == [], "pre-flight must short-circuit the request"
def test_generate_caches_max_prompt_len_lookup_failure():
"""When ``GET /v1/models`` fails (e.g. mock client without ``.get``),
the lookup result is cached as ``None`` and the pre-flight quietly
disables — the request still goes through, callers fall back to
whatever reactive overflow handling they have."""
from renderers.client import _max_prompt_len_cache
# _FakeClient has no .get method → AttributeError → cached None.
_max_prompt_len_cache.clear()
client = _FakeClient()
client.base_url = "http://no-models:8000/v1"
result = asyncio.run(
generate(
client=client,
renderer=_LongRenderer(),
messages=[{"role": "user", "content": "hi"}],
model="test-model",
)
)
# Request was dispatched (no pre-flight rejection) and round-tripped.
assert len(client.calls) == 1
assert result["prompt_ids"] == list(range(10))
assert _max_prompt_len_cache[("http://no-models:8000/v1", "test-model")] is None
+152
View File
@@ -0,0 +1,152 @@
"""DeepSeek-R1 renderer: the reasoning variant of the DeepSeek format.
General byte-parity vs ``apply_chat_template`` is covered by the conftest
barrage (``test_render_ids`` now includes both DeepSeek models). These tests
pin the behaviors that distinguish R1 from V3: the ``<think>`` generation
prompt and the stripping of ``</think>`` from historical assistant turns.
"""
from functools import lru_cache
import pytest
from renderers import (
DeepSeekR1Renderer,
DeepSeekV3Renderer,
create_renderer,
)
from renderers.base import load_tokenizer
@lru_cache
def _r1():
tok = load_tokenizer("deepseek-ai/DeepSeek-R1")
return tok, create_renderer(tok)
@lru_cache
def _v3():
tok = load_tokenizer("deepseek-ai/DeepSeek-V3")
return tok, create_renderer(tok)
# Baseline render_ids == apply_chat_template parity. Tool-cycle shapes are
# intentionally excluded: the DeepSeek template renders tool_calls only when
# content is None (a pre-existing renderer↔template gap, tracked separately),
# which is orthogonal to the V3/R1 reasoning split this module covers.
_PARITY_SHAPES = [
(
"single_turn",
[
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
],
{},
),
(
"multi_turn",
[
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
],
{},
),
(
"reasoning_content_field",
[
{"role": "user", "content": "x"},
{"role": "assistant", "reasoning_content": "r", "content": "4"},
],
{},
),
(
"gen_prompt",
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
],
{"add_generation_prompt": True},
),
(
"inline_think_history",
[
{"role": "user", "content": "q"},
{"role": "assistant", "content": "<think>reasoning</think>answer"},
{"role": "user", "content": "q2"},
],
{},
),
]
@pytest.mark.parametrize("loader", [_v3, _r1], ids=["v3", "r1"])
@pytest.mark.parametrize(
"shape_id,messages,kwargs", _PARITY_SHAPES, ids=[s[0] for s in _PARITY_SHAPES]
)
def test_render_ids_matches_apply_chat_template(loader, shape_id, messages, kwargs):
tok, renderer = loader()
got = renderer.render_ids(messages, **kwargs)
expected = list(
tok.apply_chat_template(messages, tokenize=True, return_dict=False, **kwargs)
)
assert got == expected
def test_auto_detection_picks_the_right_renderer():
_, r1 = _r1()
_, v3 = _v3()
assert isinstance(r1, DeepSeekR1Renderer)
assert isinstance(v3, DeepSeekV3Renderer)
def test_generation_prompt_differs():
"""R1 prefills ``<think>`` to trigger reasoning; V3 does not."""
msgs = [{"role": "user", "content": "hi"}]
tr1, r1 = _r1()
tv3, v3 = _v3()
r1_text = tr1.decode(r1.render_ids(msgs, add_generation_prompt=True))
v3_text = tv3.decode(v3.render_ids(msgs, add_generation_prompt=True))
# R1 prefills <think> to trigger reasoning; V3 emits a bare assistant
# turn. (Exact byte parity vs apply_chat_template is the gen_prompt case
# in the parity matrix above; here we just pin the V3/R1 distinction —
# decode trims the trailing "\n" so we don't match on it.)
assert "<think>" in r1_text and r1_text.rstrip().endswith("<think>")
assert "<think>" not in v3_text
def test_r1_strips_reasoning_from_history():
"""A historical assistant turn carrying an inline ``<think>…</think>``
trace renders only the post-``</think>`` answer, byte-identical to the R1
chat template's ``content.split('</think>')[-1]``.
"""
tok, r1 = _r1()
msgs = [
{"role": "user", "content": "q"},
{"role": "assistant", "content": "<think>private reasoning</think>The answer."},
{"role": "user", "content": "q2"},
]
got = r1.render_ids(msgs)
expected = list(tok.apply_chat_template(msgs, tokenize=True, return_dict=False))
assert got == expected
# Reasoning must not survive into the rendered history.
assert "private reasoning" not in tok.decode(got)
def test_v3_emits_content_verbatim_ignoring_reasoning():
"""V3 (non-reasoning) ignores ``reasoning_content`` — matching its
template, which only reads ``content``."""
tok, v3 = _v3()
msgs = [
{"role": "user", "content": "x"},
{"role": "assistant", "reasoning_content": "should be ignored", "content": "4"},
]
got = v3.render_ids(msgs)
expected = list(tok.apply_chat_template(msgs, tokenize=True, return_dict=False))
assert got == expected
assert "should be ignored" not in tok.decode(got)
+4 -1
View File
@@ -33,6 +33,7 @@ from openai_harmony import (
ToolDescription,
load_harmony_encoding,
)
from renderers.configs import GptOssRendererConfig
from renderers.gpt_oss import GptOssRenderer
from transformers import AutoTokenizer
@@ -49,7 +50,9 @@ def tokenizer():
def renderer(tokenizer):
# Pin the date so the rendered preamble matches the harmony oracle
# built with the same fixed date.
return GptOssRenderer(tokenizer, conversation_start_date=DATE_FOR_PARITY)
return GptOssRenderer(
tokenizer, GptOssRendererConfig(conversation_start_date=DATE_FOR_PARITY)
)
@pytest.fixture(scope="module")
+389
View File
@@ -0,0 +1,389 @@
"""Per-token ``RenderedTokens.is_content`` invariants.
``is_content[k]`` answers "does ``token_ids[k]`` come from message body
bytes (caller-provided content / tool_calls / reasoning_content, or
the model's sampled emission for the assistant role) or is it template
scaffolding the renderer added around the body (role tags, special
tokens, separators, tool-response wraps, generation prompt)?"
By design ``is_content`` is a superset of ``sampled_mask``:
- Equal on every token attributed to an assistant message (sampled ==
body for that role by construction).
- Carries new information on every other role: the model never samples
user / tool / system tokens, so ``sampled_mask`` is uniformly
``False`` over those — ``is_content`` differentiates body from wrap.
These tests parametrise across every renderer in
``conftest.RENDERER_MODELS`` and verify the contract for hand-coded
renderers. ``DefaultRenderer`` leaves ``is_content`` empty by design
(the Jinja template is opaque, so the renderer cannot know the
wrap/body split) and is exempt from the populated-length check.
The body-bytes decode invariant uses ``in`` (substring) rather than
strict equality because some renderers normalise whitespace, strip
trailing newlines, etc. within the message body emit — but the
caller-provided content must always be recoverable as a substring of
the decoded body run.
"""
from __future__ import annotations
def _is_populated(rendered) -> bool:
return len(rendered.is_content) == len(rendered.token_ids) and bool(
rendered.is_content
)
def test_is_content_length_or_empty(model_name, renderer):
"""``is_content`` is either empty (opt-out) or matches token_ids
length exactly. No partial fills."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
n_tokens = len(rendered.token_ids)
n_mask = len(rendered.is_content)
assert n_mask == 0 or n_mask == n_tokens, (
f"{model_name}: is_content length {n_mask} must be 0 or match "
f"token_ids length {n_tokens}"
)
def test_is_content_equals_sampled_on_assistant(model_name, renderer):
"""On every token attributed to an assistant message,
``is_content[k] == sampled_mask[k]``. The two signals collapse on
that role by design — the model's sampled output IS the assistant
message's body, and the surrounding scaffold is neither sampled
nor body."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello world!"},
]
rendered = renderer.render(msgs)
if not _is_populated(rendered):
return
if len(rendered.sampled_mask) != len(rendered.token_ids):
return # renderer opts out of sampled_mask
mismatches = []
for k, msg_idx in enumerate(rendered.message_indices):
if msg_idx < 0:
continue
if msgs[msg_idx].get("role") != "assistant":
continue
if rendered.is_content[k] != rendered.sampled_mask[k]:
mismatches.append((k, rendered.is_content[k], rendered.sampled_mask[k]))
assert not mismatches, (
f"{model_name}: is_content != sampled_mask on assistant tokens "
f"(k, is_content, sampled): {mismatches[:8]}"
)
def test_is_content_excludes_generation_prompt(model_name, renderer):
"""All generation-prompt tokens (msg_idx=-1) are scaffold — the
next-turn opener the chat template injects so the model can
continue. ``is_content`` must be False over that entire span."""
msgs = [{"role": "user", "content": "Hi"}]
rendered = renderer.render(msgs, add_generation_prompt=True)
if not _is_populated(rendered):
return
bad = [
k
for k, (msg_idx, is_content) in enumerate(
zip(rendered.message_indices, rendered.is_content)
)
if msg_idx == -1 and is_content
]
assert not bad, (
f"{model_name}: generation-prompt tokens marked is_content=True "
f"at positions {bad[:8]}"
)
def test_is_content_recovers_user_body(model_name, tokenizer, renderer):
"""The decoded run of is_content=True tokens within a user message
contains the user's original content. ``in`` rather than equality
because some templates normalise whitespace inside the body emit;
the input substring must still be recoverable from the decoded
body run."""
user_text = "Hello, my name is Sebastian."
msgs = [
{"role": "user", "content": user_text},
{"role": "assistant", "content": "Hi!"},
]
rendered = renderer.render(msgs)
if not _is_populated(rendered):
return
user_body_ids = [
tid
for tid, mi, ic in zip(
rendered.token_ids, rendered.message_indices, rendered.is_content
)
if mi == 0 and ic
]
assert user_body_ids, (
f"{model_name}: no is_content=True tokens attributed to user message"
)
decoded = tokenizer.decode(user_body_ids).strip()
assert user_text in decoded or decoded in user_text, (
f"{model_name}: user body run decodes to {decoded!r}, "
f"expected to contain {user_text!r}"
)
def test_is_content_recovers_tool_body(model_name, tokenizer, renderer):
"""The decoded run of is_content=True tokens within a tool message
contains the tool response body. The whole point of the body/wrap
cut: SFT on this run trains the model to anticipate tool outputs
without learning to emit the surrounding ``<|tool_response>`` /
role-tag scaffold (which would interrupt a real rollout)."""
tool_text = "The capital of France is Paris."
msgs = [
{"role": "user", "content": "What's the capital of France?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"type": "function",
"id": "call_1",
"function": {
"name": "lookup",
"arguments": {"q": "capital of France"},
},
}
],
},
{"role": "tool", "content": tool_text, "tool_call_id": "call_1"},
{"role": "assistant", "content": "Paris."},
]
rendered = renderer.render(msgs)
if not _is_populated(rendered):
return
tool_body_ids = [
tid
for tid, mi, ic in zip(
rendered.token_ids, rendered.message_indices, rendered.is_content
)
if mi == 2 and ic
]
assert tool_body_ids, (
f"{model_name}: no is_content=True tokens attributed to tool message"
)
decoded = tokenizer.decode(tool_body_ids).strip()
assert tool_text in decoded, (
f"{model_name}: tool body run decodes to {decoded!r}, "
f"expected to contain {tool_text!r}"
)
def test_is_content_recovers_system_body(model_name, tokenizer, renderer):
"""The decoded run of is_content=True tokens within a system
message contains the caller-provided system content. Tools header
/ footer (if present) are scaffold and never appear as body."""
sys_text = "You are an unusually precise assistant."
msgs = [
{"role": "system", "content": sys_text},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hi!"},
]
rendered = renderer.render(msgs)
if not _is_populated(rendered):
return
sys_body_ids = [
tid
for tid, mi, ic in zip(
rendered.token_ids, rendered.message_indices, rendered.is_content
)
if mi == 0 and ic
]
assert sys_body_ids, (
f"{model_name}: no is_content=True tokens attributed to system message"
)
decoded = tokenizer.decode(sys_body_ids).strip()
assert sys_text in decoded, (
f"{model_name}: system body run decodes to {decoded!r}, "
f"expected to contain {sys_text!r}"
)
def test_is_content_no_body_on_role_tag(model_name, renderer):
"""The first token attributed to a user/system/tool message must
have ``is_content=False`` — that's the leading role-tag run
(``<|im_start|>`` / equivalent), which is template scaffold, never
body."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
if not _is_populated(rendered):
return
user_positions = [k for k, idx in enumerate(rendered.message_indices) if idx == 0]
assert user_positions, f"{model_name}: no tokens attributed to user message"
first_k = user_positions[0]
assert not rendered.is_content[first_k], (
f"{model_name}: first user-attributed token at k={first_k} should "
f"be is_content=False (role-tag scaffolding), but was True"
)
def test_content_token_spans_by_role_isolates_tool_body(
model_name, tokenizer, renderer
):
"""``content_token_spans_by_role()["tool"]`` returns spans over
which every token is the tool message body. Joining the decoded
spans recovers the tool response. Adjacent scaffold tokens
(``<|tool_response>``, role-tag openers) are never inside any
returned span."""
tool_text = "Result: 42"
msgs = [
{"role": "user", "content": "What's 6*7?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"type": "function",
"id": "call_x",
"function": {"name": "calc", "arguments": {"e": "6*7"}},
}
],
},
{"role": "tool", "content": tool_text, "tool_call_id": "call_x"},
{"role": "assistant", "content": "42."},
]
rendered = renderer.render(msgs)
if not _is_populated(rendered):
return
spans = rendered.content_token_spans_by_role()
tool_spans = spans.get("tool") or []
assert tool_spans, f"{model_name}: no tool content spans returned"
pieces: list[str] = []
for s, e in tool_spans:
run_ids = rendered.token_ids[s:e]
# All tokens in the span must be is_content=True by definition.
for k in range(s, e):
assert rendered.is_content[k], (
f"{model_name}: span {(s, e)} contains is_content=False at k={k}"
)
pieces.append(tokenizer.decode(run_ids))
joined = "".join(pieces).strip()
assert tool_text in joined, (
f"{model_name}: joined tool spans decode to {joined!r}, "
f"expected to contain {tool_text!r}"
)
def test_content_mask_for_roles_excludes_assistant_when_unset(model_name, renderer):
"""``content_mask_for_roles({"tool"})`` returns a mask that's True
only on tool body tokens — never on assistant tokens, even though
those also have ``is_content=True``. The role filter is the whole
point: SFT-on-tool-body must not bleed into the assistant span."""
msgs = [
{"role": "user", "content": "Hi"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"type": "function",
"id": "call_a",
"function": {"name": "ping", "arguments": {}},
}
],
},
{"role": "tool", "content": "pong", "tool_call_id": "call_a"},
{"role": "assistant", "content": "OK."},
]
rendered = renderer.render(msgs)
if not _is_populated(rendered):
return
tool_mask = rendered.content_mask_for_roles({"tool"})
assert len(tool_mask) == len(rendered.token_ids)
for k, mi in enumerate(rendered.message_indices):
if mi < 0:
assert not tool_mask[k], (
f"{model_name}: scaffold token k={k} (msg_idx=-1) marked in tool mask"
)
continue
role = msgs[mi].get("role")
if role != "tool" and tool_mask[k]:
raise AssertionError(
f"{model_name}: tool-role mask True on a {role!r} token at k={k}"
)
def test_build_training_sample_content_sft_roles_picks_up_tool_body(
model_name, renderer
):
"""``build_training_sample(..., content_sft_roles={"tool"})``
produces a loss mask that's True on tool body tokens AND assistant
sampled tokens, but False on the tool-message scaffold (role tag,
``<|tool_response>`` wraps, separators). The canonical
SFT-on-tool-body + RL-on-assistant composition."""
from renderers import build_training_sample
msgs = [
{"role": "user", "content": "Hi"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"type": "function",
"id": "call_z",
"function": {"name": "noop", "arguments": {}},
}
],
},
{"role": "tool", "content": "done", "tool_call_id": "call_z"},
{"role": "assistant", "content": "OK."},
]
ids, mask = build_training_sample(
renderer,
msgs,
role_to_mask=lambda m: m["role"] == "assistant",
content_sft_roles={"tool"},
)
assert len(mask) == len(ids)
# We need at least one trainable tool-body token if the renderer
# populates is_content. Renderers that opt out (empty is_content)
# fall back to the existing role_to_mask behaviour, which leaves
# tool tokens False — that's the documented fallback and is fine.
rendered = renderer.render(msgs)
if not _is_populated(rendered):
return
trainable_per_role: dict[str, int] = {}
for k, mi in enumerate(rendered.message_indices):
if mi < 0:
continue
if mask[k]:
r = msgs[mi].get("role") or ""
trainable_per_role[r] = trainable_per_role.get(r, 0) + 1
assert trainable_per_role.get("tool", 0) > 0, (
f"{model_name}: build_training_sample with content_sft_roles={{'tool'}} "
f"trained on zero tool tokens"
)
assert trainable_per_role.get("assistant", 0) > 0, (
f"{model_name}: assistant tokens dropped from training mask"
)
assert trainable_per_role.get("user", 0) == 0, (
f"{model_name}: user tokens leaked into training mask: {trainable_per_role}"
)
+53
View File
@@ -0,0 +1,53 @@
"""Kimi K2.5 tool-schema TypeScript rendering: bool/null literal correctness.
Regression for PR #55: ``_function_to_typescript`` used to leak Python
literals (``True`` / ``False`` / ``None``) into output advertised as
TypeScript. Both call sites — ``_EnumType.to_typescript_style`` (for
non-string enum members) and ``_TypedParam.to_typescript_style`` (for
bool defaults) — now route non-string values through ``json.dumps`` so
booleans and ``None`` render as ``true`` / ``false`` / ``null``.
"""
from __future__ import annotations
from renderers.kimi_k25 import _function_to_typescript
def test_bool_default_renders_as_json_literal():
"""Bool defaults must render as ``true`` / ``false``, not ``True`` / ``False``."""
out = _function_to_typescript(
{
"name": "set_logging",
"parameters": {
"type": "object",
"properties": {
"verbose": {"type": "boolean", "default": True},
"quiet": {"type": "boolean", "default": False},
},
},
}
)
assert "// Default: true" in out
assert "// Default: false" in out
assert "Default: True" not in out
assert "Default: False" not in out
def test_enum_non_string_members_render_as_json_literals():
"""``null`` / bool / int enum members must render as JSON literals, not Python ``repr``."""
out = _function_to_typescript(
{
"name": "set_mode",
"parameters": {
"type": "object",
"properties": {
"mode": {"enum": ["auto", None, True, False, 0]},
},
},
}
)
assert '"auto" | null | true | false | 0' in out
# Python literals must not leak through.
assert "None" not in out
assert "True" not in out
assert "False" not in out
+415
View File
@@ -0,0 +1,415 @@
"""Llama-3 renderer coverage.
Covers ``Llama3Renderer`` and the ``meta-llama/Llama-3.2-{1B,3B}-Instruct``
entries in ``MODEL_RENDERER_MAP``. ``load_tokenizer`` uses the
unrestricted ``unsloth/Llama-3.2-{1B,3B}-Instruct`` mirrors underneath
(verified byte-identical chat templates) so CI doesn't need an HF token
with Meta license access.
"""
from __future__ import annotations
import pytest
from renderers import Llama3Renderer, Llama3RendererConfig, create_renderer
from renderers.base import (
MODEL_RENDERER_MAP,
ParsedResponse,
ToolCallParseStatus,
load_tokenizer,
)
# Pinned date for byte-parity tests. Matches the chat template's
# strftime fallback so we don't have to override on the apply side.
_PINNED_DATE = "26 Jul 2024"
_MODEL_PAIRS = [
# (canonical meta-llama id used by MODEL_RENDERER_MAP, unrestricted
# mirror used to actually load the tokenizer in tests)
("meta-llama/Llama-3.2-1B-Instruct", "unsloth/Llama-3.2-1B-Instruct"),
("meta-llama/Llama-3.2-3B-Instruct", "unsloth/Llama-3.2-3B-Instruct"),
]
@pytest.fixture(scope="module", params=_MODEL_PAIRS, ids=[m for m, _ in _MODEL_PAIRS])
def llama_pair(request):
canonical, mirror = request.param
tok = load_tokenizer(canonical)
renderer = Llama3Renderer(tok, Llama3RendererConfig(date_string=_PINNED_DATE))
return canonical, mirror, tok, renderer
# ---------------------------------------------------------------------------
# MODEL_RENDERER_MAP shape
# ---------------------------------------------------------------------------
def test_canonical_meta_llama_paths_route_to_llama_3():
for canonical, _ in _MODEL_PAIRS:
assert MODEL_RENDERER_MAP.get(canonical) == "llama-3", (
f"{canonical}: expected to route to 'llama-3'"
)
def test_create_renderer_via_explicit_config(llama_pair):
"""``Llama3RendererConfig`` resolves to Llama3Renderer in the registry."""
_, _, tok, _ = llama_pair
r = create_renderer(tok, Llama3RendererConfig())
assert isinstance(r, Llama3Renderer)
def test_create_renderer_auto_resolves_after_mirror_load(llama_pair):
"""``load_tokenizer(canonical_meta_id)`` loads from the unrestricted
mirror but preserves the canonical name needed for auto-resolution."""
canonical, _, tok, _ = llama_pair
assert tok.name_or_path == canonical
assert isinstance(create_renderer(tok), Llama3Renderer)
# ---------------------------------------------------------------------------
# Constructor contract
# ---------------------------------------------------------------------------
def test_default_date_matches_chat_template_strftime_fallback(llama_pair):
"""Default ``date_string`` is ``"26 Jul 2024"`` so output stays
deterministic without an explicit override."""
_, _, tok, _ = llama_pair
r = Llama3Renderer(tok)
assert r.config.date_string == _PINNED_DATE
def test_preserve_thinking_flags_are_noops(llama_pair):
"""Llama-3 has no reasoning channel, so the ``preserve_*_thinking``
flags are accepted but never change the token stream — the same
never-preserves contract as Kimi-K2 / Qwen3-VL. (Cross-renderer
coverage lives in tests/test_preserve_thinking.py.)"""
_, _, tok, _ = llama_pair
msgs = [
{"role": "user", "content": "Hi."},
{
"role": "assistant",
"reasoning_content": "internal musings",
"content": "Hello!",
},
]
base = Llama3Renderer(tok).render_ids(msgs)
for flag in ("preserve_all_thinking", "preserve_thinking_between_tool_calls"):
r = Llama3Renderer(tok, Llama3RendererConfig(**{flag: True}))
assert r.config.__getattribute__(flag) is True
assert r.render_ids(msgs) == base, f"{flag} must be a no-op for Llama-3"
# ---------------------------------------------------------------------------
# Byte parity vs apply_chat_template
# ---------------------------------------------------------------------------
def _expected(tok, messages, **kwargs):
kwargs.setdefault("add_generation_prompt", False)
kwargs.setdefault("date_string", _PINNED_DATE)
return list(
tok.apply_chat_template(messages, tokenize=True, return_dict=False, **kwargs)
)
def test_parity_minimal_user(llama_pair):
_, _, tok, r = llama_pair
msgs = [{"role": "user", "content": "Hi."}]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_system_and_user(llama_pair):
_, _, tok, r = llama_pair
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_system_user_assistant(llama_pair):
_, _, tok, r = llama_pair
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
{"role": "assistant", "content": "Hello!"},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_no_system_with_gen_prompt(llama_pair):
_, _, tok, r = llama_pair
msgs = [{"role": "user", "content": "Hi."}]
assert r.render_ids(msgs, add_generation_prompt=True) == _expected(
tok, msgs, add_generation_prompt=True
)
def test_parity_multi_turn(llama_pair):
_, _, tok, r = llama_pair
msgs = [
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_trims_whitespace(llama_pair):
_, _, tok, r = llama_pair
msgs = [
{"role": "user", "content": " hello "},
{"role": "assistant", "content": "\n\nworld\n"},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_custom_date(llama_pair):
"""``date_string`` constructor override changes both sides identically."""
_, _, tok, _ = llama_pair
r = Llama3Renderer(tok, Llama3RendererConfig(date_string="01 Jan 2026"))
msgs = [{"role": "user", "content": "Hi."}]
expected = list(
tok.apply_chat_template(
msgs, tokenize=True, return_dict=False, date_string="01 Jan 2026"
)
)
assert r.render_ids(msgs) == expected
def test_parity_tools_in_user_default(llama_pair):
_, _, tok, r = llama_pair
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
},
},
}
]
msgs = [
{"role": "system", "content": "Be terse."},
{"role": "user", "content": "Weather?"},
]
assert r.render_ids(msgs, tools=tools) == _expected(tok, msgs, tools=tools)
def test_parity_tools_in_system_mode(llama_pair):
"""When constructed with ``tools_in_user_message=False``, the renderer
matches ``apply_chat_template(... tools_in_user_message=False)``."""
_, _, tok, _ = llama_pair
r = Llama3Renderer(
tok,
Llama3RendererConfig(date_string=_PINNED_DATE, tools_in_user_message=False),
)
tools = [
{
"type": "function",
"function": {"name": "get_weather", "parameters": {}},
}
]
msgs = [
{"role": "system", "content": "Be terse."},
{"role": "user", "content": "Weather?"},
]
expected = list(
tok.apply_chat_template(
msgs,
tokenize=True,
return_dict=False,
tools=tools,
tools_in_user_message=False,
date_string=_PINNED_DATE,
)
)
assert r.render_ids(msgs, tools=tools) == expected
def test_parity_tool_call_round_trip(llama_pair):
"""Assistant tool_calls + tool response + final assistant — covers
the JSON tool-call body emission and the ``ipython`` response role."""
_, _, tok, r = llama_pair
msgs = [
{"role": "user", "content": "Weather?"},
{
"role": "assistant",
"tool_calls": [
{
"type": "function",
"function": {
"name": "get_weather",
"arguments": {"city": "NYC"},
},
}
],
},
{"role": "tool", "content": '{"temp": 72}'},
{"role": "assistant", "content": "It's 72."},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_parity_tool_response_dict_content(llama_pair):
"""Tool response with mapping content goes through ``tojson`` in the
template; the renderer's ``_tool_response_str`` mirrors that."""
_, _, tok, r = llama_pair
msgs = [
{"role": "user", "content": "x"},
{
"role": "assistant",
"tool_calls": [{"function": {"name": "f", "arguments": {}}}],
},
{"role": "tool", "content": {"k": "v", "n": 42}},
{"role": "assistant", "content": "ok"},
]
assert r.render_ids(msgs) == _expected(tok, msgs)
def test_render_raises_on_multiple_tool_calls(llama_pair):
"""Llama-3 chat template explicitly raises on >1 tool call per turn —
the renderer mirrors that contract."""
_, _, _, r = llama_pair
msgs = [
{"role": "user", "content": "x"},
{
"role": "assistant",
"tool_calls": [
{"function": {"name": "f", "arguments": {}}},
{"function": {"name": "g", "arguments": {}}},
],
},
]
with pytest.raises(ValueError, match="single tool call"):
r.render_ids(msgs)
# ---------------------------------------------------------------------------
# parse_response
# ---------------------------------------------------------------------------
def _tokens_for(tok, text: str) -> list[int]:
return tok.encode(text, add_special_tokens=False)
def test_parse_response_plain_content(llama_pair):
_, _, tok, r = llama_pair
ids = _tokens_for(tok, "Hello, world!") + [r._eot]
out = r.parse_response(ids)
assert isinstance(out, ParsedResponse)
assert out.content == "Hello, world!"
assert out.tool_calls == []
assert out.reasoning_content is None
def test_parse_response_tool_call(llama_pair):
_, _, tok, r = llama_pair
body = '{"name": "get_weather", "parameters": {"city": "NYC"}}'
ids = _tokens_for(tok, body) + [r._eot]
out = r.parse_response(ids)
assert out.content == ""
assert len(out.tool_calls) == 1
tc = out.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "get_weather"
assert tc.arguments == {"city": "NYC"}
def test_parse_response_malformed_tool_call_falls_through_to_content(llama_pair):
"""A body that LOOKS like a tool call but doesn't parse should land
in content rather than dropping silently."""
_, _, tok, r = llama_pair
body = '{"name": "x", broken'
ids = _tokens_for(tok, body) + [r._eot]
out = r.parse_response(ids)
assert out.tool_calls == []
assert "{" in out.content
# ---------------------------------------------------------------------------
# Bridge contract
# ---------------------------------------------------------------------------
def _simulate_prior_turn(r):
prior = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
]
asst = [{"role": "assistant", "content": "Hello!"}]
prev_prompt = r.render_ids(prior, add_generation_prompt=True)
full = r.render_ids(prior + asst, add_generation_prompt=False)
prev_completion = list(full[len(prev_prompt) :])
stop = set(r.get_stop_token_ids())
last = -1
for i in range(len(prev_completion) - 1, -1, -1):
if prev_completion[i] in stop:
last = i
break
if last >= 0:
prev_completion = prev_completion[: last + 1]
return prev_prompt, prev_completion
def test_bridge_extends_prev_verbatim_on_clean_stop(llama_pair):
_, _, _, r = llama_pair
prev_prompt, prev_completion = _simulate_prior_turn(r)
new_messages = [{"role": "user", "content": "What's 2+2?"}]
bridged = r.bridge_to_next_turn(prev_prompt, prev_completion, new_messages)
assert bridged is not None
prev = prev_prompt + prev_completion
assert bridged.token_ids[: len(prev)] == prev
assert len(bridged.token_ids) > len(prev)
def test_bridge_matches_fresh_render_on_clean_stop(llama_pair):
"""The whole point of the bridge: it must produce the same tokens as
a fresh render of the full message list — except sampled tokens are
kept verbatim rather than re-rendered."""
_, _, _, r = llama_pair
prior = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
]
asst = [{"role": "assistant", "content": "Hello!"}]
new_messages = [{"role": "user", "content": "What's 2+2?"}]
prev_prompt, prev_completion = _simulate_prior_turn(r)
bridged = r.bridge_to_next_turn(prev_prompt, prev_completion, new_messages)
fresh = r.render_ids(prior + asst + new_messages, add_generation_prompt=True)
assert bridged.token_ids == fresh
def test_bridge_rejects_assistant_in_extension(llama_pair):
_, _, _, r = llama_pair
prev_prompt, prev_completion = _simulate_prior_turn(r)
bridged = r.bridge_to_next_turn(
prev_prompt,
prev_completion,
[{"role": "assistant", "content": "forbidden"}],
)
assert bridged is None
def test_bridge_synthesises_close_on_truncation(llama_pair):
_, _, _, r = llama_pair
prev_prompt, prev_completion = _simulate_prior_turn(r)
trunc = prev_completion[:-1]
if not trunc:
pytest.skip("simulated prior had no completion tokens to truncate")
bridged = r.bridge_to_next_turn(
prev_prompt, trunc, [{"role": "user", "content": "ping"}]
)
assert bridged is not None
base = prev_prompt + trunc
assert bridged.token_ids[: len(base)] == base
assert len(bridged.token_ids) > len(base)
+67 -1
View File
@@ -9,9 +9,11 @@ repo doesn't auto-propagate.
from __future__ import annotations
import re
from types import SimpleNamespace
from unittest.mock import patch
from renderers.base import TRUSTED_REVISIONS, load_tokenizer
from renderers import base
from renderers.base import TOKENIZER_SOURCE_OVERRIDES, TRUSTED_REVISIONS, load_tokenizer
# ---------------------------------------------------------------------------
@@ -70,6 +72,23 @@ def test_kimi_loads_with_pinned_revision(mock_from_pretrained):
}
@patch("transformers.AutoTokenizer.from_pretrained")
def test_meta_llama_loads_tokenizer_from_unsloth_mirror(mock_from_pretrained):
"""Canonical Meta Llama repos are gated; load their tokenizer/chat
template from the audited unrestricted mirror while preserving the
canonical name for renderer auto-resolution."""
canonical = "meta-llama/Llama-3.2-1B-Instruct"
mirror = "unsloth/Llama-3.2-1B-Instruct"
mock_from_pretrained.return_value = SimpleNamespace(name_or_path=mirror)
tok = load_tokenizer(canonical, use_fastokens=False)
args, kwargs = mock_from_pretrained.call_args
assert args == (mirror,)
assert kwargs == {"trust_remote_code": False}
assert tok.name_or_path == canonical
@patch("transformers.AutoTokenizer.from_pretrained")
def test_unknown_path_falls_through_to_no_remote_code(mock_from_pretrained):
"""Unknown / fine-tuned model paths — including ``moonshotai/Kimi-K2*``
@@ -92,6 +111,53 @@ def test_unknown_path_falls_through_to_no_remote_code(mock_from_pretrained):
)
def test_tokenizer_source_overrides_are_exact_llama_mirrors():
"""Mirror overrides are intentionally narrow: only verified
byte-identical Llama tokenizer/template mirrors should live here."""
assert TOKENIZER_SOURCE_OVERRIDES == {
"meta-llama/Llama-3.2-1B-Instruct": "unsloth/Llama-3.2-1B-Instruct",
"meta-llama/Llama-3.2-3B-Instruct": "unsloth/Llama-3.2-3B-Instruct",
}
def test_offset_tokenizer_uses_unsloth_mirror_for_meta_llama(monkeypatch):
"""Offset-tokenizer reloads must use the same unrestricted source
override, otherwise Llama rendering can hit the gated Meta repo after
the initial tokenizer load succeeds."""
class _NoOffsets:
name_or_path = "meta-llama/Llama-3.2-1B-Instruct"
def __call__(self, *args, **kwargs):
raise NotImplementedError("fastokens shim has no offsets")
class _OffsetTokenizer:
is_fast = True
def __init__(self, name_or_path: str):
self.name_or_path = name_or_path
def __call__(self, *args, **kwargs):
return {"offset_mapping": [(0, 1)]}
calls = []
def _fake_load(name_or_path, **kwargs):
calls.append((name_or_path, kwargs))
return _OffsetTokenizer(name_or_path)
base._offset_tokenizers.clear()
monkeypatch.setattr(base, "_load_tokenizer_via_auto", _fake_load)
try:
tok = base._get_offset_tokenizer(_NoOffsets())
finally:
base._offset_tokenizers.clear()
assert calls == [("unsloth/Llama-3.2-1B-Instruct", {"trust_remote_code": False})]
assert tok.name_or_path == "meta-llama/Llama-3.2-1B-Instruct"
# ---------------------------------------------------------------------------
# Smoke: real tokenizer loads behave as expected
# ---------------------------------------------------------------------------
+46 -5
View File
@@ -3,8 +3,7 @@
``load_tokenizer`` defaults to routing every supported model through
``fastokens.patch_transformers()`` for ~10x faster encode. Models in
``FASTOKENS_INCOMPATIBLE`` skip the patch (DeepSeek's Metaspace
pretokenizer isn't supported; MiniMax tokenizers diverge on literal
special-token text). Callers can opt out per-call with
pretokenizer isn't supported). Callers can opt out per-call with
``use_fastokens=False``.
These tests pin the policy:
@@ -47,8 +46,8 @@ def test_fastokens_incompatible_is_explicit_set():
{
"deepseek-ai/DeepSeek-V3",
"deepseek-ai/DeepSeek-V3-Base",
"MiniMaxAI/MiniMax-M2",
"MiniMaxAI/MiniMax-M2.5",
"deepseek-ai/DeepSeek-R1",
"deepseek-ai/DeepSeek-R1-0528",
}
)
@@ -108,7 +107,7 @@ def test_fast_and_vanilla_encode_identically_on_compatible_model():
def test_incompat_model_loads_via_vanilla_backend(model):
"""For models we know diverge / fail under fastokens, the fast path
must be skipped so the load still succeeds with a vanilla backend."""
if "DeepSeek" in model or "MiniMax" in model:
if "DeepSeek" in model:
# Skip if upstream gating / size makes the load impractical here.
# We only care that the path doesn't try fastokens. Probe the
# tokenizer_config to make sure the repo is reachable; if not,
@@ -170,3 +169,45 @@ def test_fallback_on_fastokens_load_error(monkeypatch):
assert "Shim" not in _backend_class_name(tok)
# Still works.
assert len(tok.encode("hi", add_special_tokens=False)) > 0
# ---------------------------------------------------------------------------
# Print suppression: fastokens itself prints "[fastokens]
# patch_transformers: ..." on every patch/unpatch call. Building a
# RendererPool of size N would emit ~N lines (the pool factory calls
# load_tokenizer once per slot). load_tokenizer swallows that stdout
# chatter and emits a single INFO log on the first patch instead.
# ---------------------------------------------------------------------------
def test_no_fastokens_stdout_chatter(capsys, caplog):
"""``load_tokenizer`` must not leak ``[fastokens]`` prints onto
stdout, and must emit exactly one INFO log per process announcing
the fast path (not once per call)."""
import logging
import renderers.base as rb
# Reset the process-wide "announced" flag so this test sees the
# first-call log even if another test loaded a tokenizer earlier.
rb._FASTOKENS_ANNOUNCED = False
with caplog.at_level(logging.INFO, logger="renderers.base"):
load_tokenizer(_FAST_MODEL)
load_tokenizer(_FAST_MODEL)
captured = capsys.readouterr()
assert "[fastokens]" not in captured.out, (
f"fastokens print leaked to stdout: {captured.out!r}"
)
assert "[fastokens]" not in captured.err, (
f"fastokens print leaked to stderr: {captured.err!r}"
)
fastokens_info = [
r for r in caplog.records if "fastokens enabled" in r.getMessage()
]
assert len(fastokens_info) == 1, (
f"expected exactly one fastokens INFO log across two loads, "
f"got {len(fastokens_info)}"
)
+1 -1
View File
@@ -99,7 +99,7 @@ def test_kimi_k2_unknown_role_message_indices():
from renderers.base import load_tokenizer
tok = load_tokenizer("moonshotai/Kimi-K2-Instruct")
renderer = create_renderer(tok, renderer="auto")
renderer = create_renderer(tok)
msgs = [
{"role": "user", "content": "hi"},
+97
View File
@@ -0,0 +1,97 @@
"""Tests for ``RenderedTokens.message_tool_names`` and its populating helper.
``message_tool_names`` is a per-message sidecar parallel to
``message_roles``: for each tool-role message in the rendered slice
it carries the tool function name, ``None`` everywhere else. The name
comes from ``msg["name"]`` when set, otherwise from a
``tool_call_id`` join against any prior assistant's ``tool_calls`` in
the same slice. Pure metadata — does not affect the rendered token
stream, does not mutate the caller's messages.
Unit tests below cover the join's case matrix without a tokenizer.
The single integration test runs every renderer in the conftest
matrix to catch any of the ~25 ``RenderedTokens(...)`` construction
sites that might fail to wire the field through.
"""
from __future__ import annotations
from renderers.base import extract_message_tool_names
def test_extract_empty():
assert extract_message_tool_names([]) == []
def test_extract_caller_provided_name_wins():
"""``msg['name']`` set by the caller is used verbatim — no join attempted."""
messages = [
{"role": "tool", "tool_call_id": "c1", "name": "caller_set", "content": "x"},
]
assert extract_message_tool_names(messages) == ["caller_set"]
def test_extract_resolves_from_prior_assistant():
"""Tool message without ``name``: recovered via tool_call_id → assistant.tool_calls."""
messages = [
{"role": "user", "content": "go"},
{
"role": "assistant",
"tool_calls": [{"id": "c1", "function": {"name": "screenshot"}}],
},
{"role": "tool", "tool_call_id": "c1", "content": "ok"},
]
assert extract_message_tool_names(messages) == [None, None, "screenshot"]
def test_extract_orphan_tool_message_is_none():
"""``tool_call_id`` matching no in-slice assistant resolves to ``None``
(bridge case: the issuing assistant lives in the prior portion that
``new_messages`` doesn't cover).
"""
messages = [{"role": "tool", "tool_call_id": "orphan", "content": "x"}]
assert extract_message_tool_names(messages) == [None]
def test_extract_does_not_mutate_caller():
"""Caller's tool message must not gain a ``name`` field after extraction —
the helper produces a sidecar list, not a mutated view of the input.
"""
messages = [
{
"role": "assistant",
"tool_calls": [{"id": "c1", "function": {"name": "f"}}],
},
{"role": "tool", "tool_call_id": "c1", "content": "x"},
]
extract_message_tool_names(messages)
assert "name" not in messages[1]
def test_renderer_populates_message_tool_names(model_name, renderer):
"""Every renderer wires ``message_tool_names`` through ``RenderedTokens``.
Catches missed wire-up at any of the ~25 ``RenderedTokens(...)``
construction sites across concrete renderers. The input is
spec-conformant (tool message carries ``tool_call_id`` but no
``name``) so the resolution path exercises the internal join.
"""
messages = [
{"role": "user", "content": "go"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c1",
"type": "function",
"function": {"name": "screenshot", "arguments": {}},
}
],
},
{"role": "tool", "tool_call_id": "c1", "content": "ok"},
]
rt = renderer.render(messages)
assert rt.message_tool_names == [None, None, "screenshot"], (
f"{model_name}: got {rt.message_tool_names}"
)
+220 -4
View File
@@ -33,7 +33,16 @@ from renderers import (
Qwen3VLRenderer,
create_renderer,
)
from renderers.base import load_tokenizer
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
from renderers.configs import _config_class_for
def _config_with_add_vision_id(model_name: str, add_vision_id: bool):
"""Build the typed config for ``model_name`` (resolved via
``MODEL_RENDERER_MAP``) with ``add_vision_id`` set. The qwen_vl
family — Qwen3.5 and Qwen3-VL — both expose this field."""
renderer_name = MODEL_RENDERER_MAP[model_name]
return _config_class_for(renderer_name)(add_vision_id=add_vision_id)
pytest.importorskip("PIL", reason="Pillow required for multimodal tests")
@@ -111,7 +120,7 @@ def _load_processor_and_renderer(model_name: str):
)
else:
processor = AutoProcessor.from_pretrained(model_name)
renderer = create_renderer(tokenizer, renderer="auto")
renderer = create_renderer(tokenizer)
# Inject processor so the renderer doesn't try to fetch it lazily.
if hasattr(renderer, "_processor") and renderer._processor is None:
renderer._processor = processor
@@ -636,7 +645,7 @@ def test_modality_registry_models_route_to_renderer():
if not _hf_snapshot_cached(model_name):
continue
tokenizer = load_tokenizer(model_name)
renderer = create_renderer(tokenizer, renderer="auto")
renderer = create_renderer(tokenizer)
# We expect a hand-coded VL renderer, not the default fallback.
assert not type(renderer).__name__.startswith("Default"), (
f"{model_name} routed to DefaultRenderer despite being in "
@@ -682,6 +691,176 @@ def test_tool_response_image_byte_parity(mm_model_name, modality, tiny_image):
)
def _qwen_vl_processor_input_ids_with_kwargs(
processor, messages, add_gp, **template_kwargs
):
"""Variant of ``_qwen_vl_processor_input_ids`` that forwards
``template_kwargs`` to ``apply_chat_template`` so the parity oracle
can exercise the same typed-config template field the renderer was
constructed with (e.g. ``add_vision_id=True``).
"""
text = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=add_gp,
**template_kwargs,
)
images = []
for msg in messages:
content = msg.get("content")
if not isinstance(content, list):
continue
for item in content:
if not isinstance(item, dict):
continue
if (
item.get("type") in ("image", "image_url")
or "image" in item
or "image_url" in item
):
if "image" in item and not isinstance(item["image"], dict):
images.append(item["image"])
return processor(images=images, text=text, return_tensors="pt")["input_ids"][
0
].tolist()
# ``add_vision_id`` is exposed on the Qwen-VL family renderers
# (Qwen3.5 / Qwen3.6 / Qwen3-VL) per the chat-template audit. Kimi K2.5
# / K2.6's template has no equivalent toggle, so it's intentionally
# absent from ``KimiK25RendererConfig`` and skipped here.
_ADD_VISION_ID_CASES = [
(m, mo) for m, mo in _CASES if mo == "image" and _detect_family(m) == "qwen_vl"
]
@pytest.mark.parametrize(
"mm_model_name,modality",
_ADD_VISION_ID_CASES,
ids=[f"{m}|{mo}" for m, mo in _ADD_VISION_ID_CASES],
)
@pytest.mark.parametrize("add_vision_id", [True, False])
def test_add_vision_id_parity_vs_processor(
mm_model_name, modality, add_vision_id, tiny_image
):
"""Parity for ``add_vision_id`` across image-bearing shapes.
When True, the renderer must prefix each image / video placeholder
with ``Picture N: `` / ``Video N: `` matching the Jinja template's
``image_count`` / ``video_count`` namespaces. When False, the
prefix is suppressed entirely. Both branches must reproduce
``processor.apply_chat_template(messages, add_vision_id=<value>)``
token-for-token after image expansion.
"""
if not _hf_snapshot_cached(mm_model_name):
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
kit = _modality_kit(modality, mm_model_name)
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
# Build a fresh renderer for the kwarg under test (the shared
# fixture has ``add_vision_id=False`` baked in).
renderer = create_renderer(
tokenizer,
_config_with_add_vision_id(mm_model_name, add_vision_id),
)
if hasattr(renderer, "_processor") and renderer._processor is None:
renderer._processor = processor
for case in _build_cases(kit["make_part"], tiny_image):
messages, add_gp = case.values
ours = renderer.render_ids(messages, add_generation_prompt=add_gp)
theirs = _qwen_vl_processor_input_ids_with_kwargs(
processor, messages, add_gp, add_vision_id=add_vision_id
)
assert ours == theirs, (
f"{mm_model_name} / add_vision_id={add_vision_id} / "
f"case={case.id}: renderer diverges from processor.\n"
f" ours[:80]={ours[:80]}\n theirs[:80]={theirs[:80]}\n"
f" len(ours)={len(ours)} len(theirs)={len(theirs)}"
)
@pytest.mark.parametrize(
"mm_model_name,modality",
_ADD_VISION_ID_CASES,
ids=[f"{m}|{mo}" for m, mo in _ADD_VISION_ID_CASES],
)
def test_bridge_refuses_when_add_vision_id_loses_prior_count(
mm_model_name, modality, tiny_image
):
"""When ``add_vision_id=True``, the bridge needs the prior turn's
image / video count to keep the ``Picture N:`` numbering correct.
The only source of that count for the bridged turn is
``previous_multi_modal_data``; raw prior token ids don't carry it
back unambiguously (``<|vision_start|>`` is shared between image
and video placeholders).
If a caller omits ``previous_multi_modal_data`` on a conversation
that already contains images, naively continuing the bridge would
emit ``Picture 1:`` again for the new turn — diverging from
``apply_chat_template`` and a full re-render. The bridge must
refuse (return None) so the caller falls back to a full re-render.
"""
if not _hf_snapshot_cached(mm_model_name):
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
kit = _modality_kit(modality, mm_model_name)
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
renderer = create_renderer(
tokenizer,
_config_with_add_vision_id(mm_model_name, True),
)
if hasattr(renderer, "_processor") and renderer._processor is None:
renderer._processor = processor
initial = [
{
"role": "user",
"content": [
kit["make_part"](tiny_image),
{"type": "text", "text": "Turn one."},
],
}
]
new_messages = [
{
"role": "user",
"content": [
kit["make_part"](tiny_image),
{"type": "text", "text": "Turn two."},
],
}
]
initial_rendered = renderer.render(initial, add_generation_prompt=True)
im_end_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
completion_ids = tokenizer.encode("Saw it.", add_special_tokens=False) + [im_end_id]
# No previous_multi_modal_data → bridge must refuse so the caller
# falls back to a full re-render (where the counter restarts from
# the full message list and lands on Picture 2: correctly).
bridged = renderer.bridge_to_next_turn(
previous_prompt_ids=initial_rendered.token_ids,
previous_completion_ids=completion_ids,
new_messages=new_messages,
)
assert bridged is None, (
f"{mm_model_name}: bridge should refuse when add_vision_id=True "
"and previous_multi_modal_data is omitted but prior contains images"
)
# With the prior mm_data threaded through, the bridge proceeds.
bridged_ok = renderer.bridge_to_next_turn(
previous_prompt_ids=initial_rendered.token_ids,
previous_completion_ids=completion_ids,
new_messages=new_messages,
previous_multi_modal_data=initial_rendered.multi_modal_data,
)
assert bridged_ok is not None, (
f"{mm_model_name}: bridge unexpectedly refused even with previous_multi_modal_data"
)
def test_qwen3_vl_renderer_exposes_image_modality():
"""The flagship multimodal renderer is concretely Qwen3VLRenderer.
@@ -692,6 +871,43 @@ def test_qwen3_vl_renderer_exposes_image_modality():
if not _hf_snapshot_cached(model):
pytest.skip(f"{model}: HF snapshot not cached locally")
tokenizer = load_tokenizer(model)
renderer = create_renderer(tokenizer, renderer="auto")
renderer = create_renderer(tokenizer)
assert isinstance(renderer, Qwen3VLRenderer)
assert "image" in MULTIMODAL_MODELS[model]
def test_is_image_part_treats_type_field_as_authoritative():
"""``Dataset.from_list`` unifies the Arrow schema across the elements
of a list-typed column. A content list mixing text and image parts
round-trips with ``image_url: None`` added to every text part (and
``text: None`` added to every image part). The classifier must treat
the ``type`` field as authoritative when present — falling back to
a key-presence check on ``image_url`` would misclassify the text
part and the renderer would later raise on ``_load_pil_image(None)``.
"""
from renderers.qwen3_vl import _is_image_part, _is_video_part
# Typed parts classify by their ``type``.
assert _is_image_part(
{"type": "image_url", "image_url": {"url": "data:image/png;base64,XXX"}}
)
assert _is_image_part({"type": "image", "image": object()})
assert _is_video_part(
{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,XXX"}}
)
# Schema-unified text parts — typed as text, with a None zombie key
# for the sibling modality — must NOT classify as image / video.
schema_unified_text = {"type": "text", "text": "hello", "image_url": None}
assert not _is_image_part(schema_unified_text)
assert not _is_video_part(schema_unified_text)
schema_unified_text_with_video = {"type": "text", "text": "hi", "video_url": None}
assert not _is_video_part(schema_unified_text_with_video)
# Untyped fallback only fires when ``type`` is absent, and requires
# a truthy value (mere key presence isn't enough).
assert _is_image_part({"image_url": {"url": "data:..."}})
assert _is_image_part({"image": object()})
assert not _is_image_part({"image_url": None})
assert not _is_image_part({"image": None})
assert not _is_video_part({"video_url": None})
+676
View File
@@ -0,0 +1,676 @@
"""Exhaustive token-for-token parity for the Nemotron-3 renderer.
The shared barrage in ``test_render_ids.py`` covers the common message
shapes against every model. This file pins the Nemotron-3-specific template
branches that the shared matrix can't reach — they'd fail on other models or
exercise behaviour unique to the Nemotron-3 chat template:
* reasoning + empty / ``None`` content with and without tool calls (the
template trims the assembled ``<think>…</think>{content}`` block and appends
exactly one separator — a stray ``\\n`` here is the most common agentic
regression);
* the historical-thinking truncation boundary, which is ``loop.index0 <
last_user_idx`` in **all three** variants (Nano / Super / Ultra) — so an
in-flight tool cycle (assistant turns after the last user message) keeps its
reasoning by default;
* inline ``<think>…</think>`` tags carried in ``content`` rendering verbatim
(the template only reformats reasoning supplied via ``reasoning_content``);
* verbatim (unstripped) user / system / tool content and ``reasoning_content``;
* the ``enable_thinking`` / ``truncate_history_thinking`` template kwargs;
* the per-variant reasoning-effort kwargs: ``low_effort`` (Super) and
``medium_effort`` (Ultra), each a no-op on the variants that don't define it.
Every assertion compares ``renderer.render_ids(...)`` to
``tokenizer.apply_chat_template(..., tokenize=True)`` — a pass means the
renderer is byte-for-byte faithful for that case. Tokenizers are loaded from
the local HF cache (offline); no network.
The variants split across two configs: ``nemotron-3`` (Nano / Super, with
``low_effort``) and ``nemotron-3-ultra`` (Ultra, with ``medium_effort``). The
helper resolves the right config class per model from ``MODEL_RENDERER_MAP``.
"""
from __future__ import annotations
from functools import lru_cache
import pytest
from renderers import create_renderer
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
from renderers.configs import _config_class_for
# BF16 / FP8 share a tokenizer; only the BF16 checkpoints are cached for tests.
NANO = "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"
SUPER = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
ULTRA = "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16"
MODELS = [NANO, SUPER, ULTRA]
@lru_cache
def _tok(model: str):
return load_tokenizer(model)
def _config_cls(model: str):
"""The typed-config class the model resolves to (``nemotron-3`` for
Nano/Super, ``nemotron-3-ultra`` for Ultra)."""
return _config_class_for(MODEL_RENDERER_MAP[model])
def _renderer(model: str, **flags):
# Build with the model's own variant config so the renderer picks the right
# ``</think>`` glue (and only valid kwargs are accepted).
return create_renderer(_tok(model), _config_cls(model)(**flags))
def _expected(
model: str, messages, *, tools=None, add_generation_prompt=False, **kwargs
):
out = _tok(model).apply_chat_template(
messages,
tools=tools,
tokenize=True,
return_dict=False,
add_generation_prompt=add_generation_prompt,
**kwargs,
)
if isinstance(out, str): # some tokenizers return str even with tokenize=True
return list(_tok(model).encode(out, add_special_tokens=False))
return list(out)
def _assert_parity(
model, messages, *, tools=None, add_generation_prompt=False, **template_kwargs
):
"""Renderer ids == apply_chat_template ids for ``model``.
``template_kwargs`` (e.g. ``enable_thinking``, ``truncate_history_thinking``)
are forwarded to both the renderer config and ``apply_chat_template`` so the
two sides stay aligned.
"""
renderer = _renderer(model, **template_kwargs)
got = renderer.render_ids(
messages, tools=tools, add_generation_prompt=add_generation_prompt
)
exp = _expected(
model,
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
**template_kwargs,
)
assert got == exp, (
f"{model}: render_ids diverged from apply_chat_template\n"
f" exp …{_tok(model).decode(exp[-40:])!r}\n"
f" got …{_tok(model).decode(got[-40:])!r}"
)
pytestmark = pytest.mark.parametrize("model", MODELS, ids=["nano", "super", "ultra"])
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "The city name"}
},
"required": ["city"],
},
},
}
]
# ── Reasoning + tool calls: the trim / separator boundary ─────────────
def test_reasoning_empty_content_tool_call(model):
"""reason → tool call, no prose. Must be ``</think>\\n<tool_call>`` (one
newline), not ``</think>\\n\\n<tool_call>``."""
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "I should call the weather tool.",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
],
tools=TOOLS,
)
def test_reasoning_none_content_tool_call(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "Call the tool.",
"content": None,
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
],
tools=TOOLS,
)
def test_reasoning_content_tool_call(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "Think first.",
"content": "Let me check.",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
],
tools=TOOLS,
)
def test_reasoning_empty_content_no_tool_call(model):
"""reason → empty answer, no tool call: ``</think>`` glued to ``<|im_end|>``."""
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{"role": "assistant", "reasoning_content": "thinking", "content": ""},
],
)
def test_multiple_tool_calls_with_reasoning(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris and London?"},
{
"role": "assistant",
"reasoning_content": "Two cities — two calls.",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
},
{
"function": {
"name": "get_weather",
"arguments": {"city": "London"},
}
},
],
},
],
tools=TOOLS,
)
def test_tool_call_with_nested_object_args(model):
_assert_parity(
model,
[
{"role": "user", "content": "go"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {
"city": "Paris",
"opts": {"unit": "c", "days": [1, 2]},
},
}
}
],
},
],
tools=TOOLS,
)
# ── Historical-thinking truncation boundary (last_user_idx) ───────────
def test_inflight_tool_cycle_keeps_reasoning(model):
"""Assistant turns after the last user message (the in-flight tool cycle)
keep their reasoning by default — boundary is ``loop.index0 <
last_user_idx`` in every variant."""
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"reasoning_content": "Call the tool first.",
"content": "calling",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": '{"temp": 20}'},
{
"role": "assistant",
"reasoning_content": "Now I can answer.",
"content": "It is 20 degrees.",
},
],
tools=TOOLS,
)
def test_history_truncation_drops_older_reasoning(model):
"""A reasoning turn before the last user message is collapsed to an empty
think block (tool-call branch trims the remainder on Nano/Super)."""
_assert_parity(
model,
[
{"role": "user", "content": "Q1"},
{
"role": "assistant",
"reasoning_content": "reasoning before tool",
"content": "calling",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": '{"temp": 20}'},
{"role": "assistant", "reasoning_content": "after", "content": "Done."},
{"role": "user", "content": "Q2"},
{"role": "assistant", "reasoning_content": "final", "content": "A2"},
],
tools=TOOLS,
)
def test_two_block_tool_conversation(model):
_assert_parity(
model,
[
{"role": "system", "content": "be brief"},
{"role": "user", "content": "first"},
{
"role": "assistant",
"reasoning_content": "R2",
"content": "calling.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "a"}}}
],
},
{"role": "tool", "content": "result-a"},
{"role": "assistant", "reasoning_content": "R4", "content": "answer-1"},
{"role": "user", "content": "second"},
{
"role": "assistant",
"reasoning_content": "R6",
"content": "calling.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "b"}}}
],
},
{"role": "tool", "content": "result-b"},
{"role": "assistant", "reasoning_content": "R8", "content": "answer-2"},
],
tools=TOOLS,
)
def test_plain_multi_turn_reasoning_truncation(model):
_assert_parity(
model,
[
{"role": "user", "content": "Q1"},
{
"role": "assistant",
"reasoning_content": "long reasoning one",
"content": "A1",
},
{"role": "user", "content": "Q2"},
{
"role": "assistant",
"reasoning_content": "long reasoning two",
"content": "A2",
},
],
)
@pytest.mark.parametrize("truncate", [True, False])
def test_truncate_history_thinking_kwarg(model, truncate):
"""``truncate_history_thinking=False`` keeps reasoning on every past turn."""
_assert_parity(
model,
[
{"role": "user", "content": "Q1"},
{
"role": "assistant",
"reasoning_content": "first reasoning",
"content": "A1",
},
{"role": "user", "content": "Q2"},
{
"role": "assistant",
"reasoning_content": "second reasoning",
"content": "A2",
},
],
truncate_history_thinking=truncate,
)
# ── Inline <think> tags carried in content (no reasoning_content field) ─
def test_inline_think_tags_final_turn_verbatim(model):
"""Inline ``<think>…</think>`` in the final assistant ``content`` renders
verbatim — the renderer must not parse + reformat it."""
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "<think>secret</think>visible"},
],
)
def test_inline_think_tags_history_turn(model):
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{
"role": "assistant",
"content": "<think>secret reasoning</think>visible answer",
},
{"role": "user", "content": "again"},
{"role": "assistant", "content": "second"},
],
)
# ── Verbatim (unstripped) content ─────────────────────────────────────
def test_system_content_whitespace_verbatim(model):
_assert_parity(
model,
[
{"role": "system", "content": " padded system "},
{"role": "user", "content": "hi"},
],
)
def test_user_content_whitespace_verbatim(model):
_assert_parity(
model,
[
{"role": "user", "content": " padded user "},
{"role": "assistant", "content": "ok"},
],
)
def test_assistant_content_whitespace(model):
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{"role": "assistant", "content": " spaced answer "},
],
)
def test_reasoning_content_whitespace_verbatim(model):
_assert_parity(
model,
[
{"role": "user", "content": "hi"},
{
"role": "assistant",
"reasoning_content": " padded reason ",
"content": "answer",
},
],
)
def test_tool_content_whitespace_verbatim(model):
_assert_parity(
model,
[
{"role": "user", "content": "go"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": " spaced tool result "},
{"role": "assistant", "content": "done"},
],
tools=TOOLS,
)
def test_system_whitespace_with_tools(model):
_assert_parity(
model,
[
{"role": "system", "content": " weather bot "},
{"role": "user", "content": "Weather?"},
],
tools=TOOLS,
)
# ── Generation prompt / thinking toggle ───────────────────────────────
@pytest.mark.parametrize("enable_thinking", [True, False])
def test_generation_prompt_thinking_toggle(model, enable_thinking):
_assert_parity(
model,
[{"role": "user", "content": "hi"}],
add_generation_prompt=True,
enable_thinking=enable_thinking,
)
def test_generation_prompt_after_tool_response(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": '{"temp": 20}'},
],
tools=TOOLS,
add_generation_prompt=True,
)
# ── Whole-conversation cycles, no reasoning ───────────────────────────
def test_full_tool_cycle_no_reasoning(model):
_assert_parity(
model,
[
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "Let me check.",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
}
],
},
{"role": "tool", "content": '{"temp": 20, "condition": "sunny"}'},
{"role": "assistant", "content": "It is 20 degrees and sunny."},
],
tools=TOOLS,
)
def test_consecutive_tool_responses(model):
_assert_parity(
model,
[
{"role": "user", "content": "Weather in Paris and London?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"function": {
"name": "get_weather",
"arguments": {"city": "Paris"},
}
},
{
"function": {
"name": "get_weather",
"arguments": {"city": "London"},
}
},
],
},
{"role": "tool", "content": '{"temp": 20}'},
{"role": "tool", "content": '{"temp": 15}'},
{"role": "assistant", "content": "Paris: 20, London: 15."},
],
tools=TOOLS,
)
def test_no_system_no_tools_injects_empty_system(model):
_assert_parity(
model,
[
{"role": "user", "content": "Hello!"},
{"role": "assistant", "content": "Hi there!"},
],
)
# ── Reasoning-effort kwargs (variant-specific) ────────────────────────
_EFFORT_SHAPES = [
# gen-prompt shape: hint rides on the (only) user message.
([{"role": "user", "content": "solve it"}], {"add_generation_prompt": True}),
# multi-turn: hint must land on the LAST user message, not the first.
(
[
{"role": "user", "content": "first"},
{"role": "assistant", "content": "ok"},
{"role": "user", "content": "second"},
],
{"add_generation_prompt": True},
),
]
@pytest.mark.parametrize("flag", [True, False])
@pytest.mark.parametrize(
"shape,extra", _EFFORT_SHAPES, ids=["gen_prompt", "multi_turn"]
)
def test_low_effort_kwarg(model, flag, shape, extra):
"""``low_effort`` appends ``\\n\\n{reasoning effort: low}`` to the last user
message on **Super**; it's a no-op on **Nano** (its template never defines
it). Ultra's config has no such field, so it's skipped."""
if model == ULTRA:
pytest.skip("low_effort is a nemotron-3 (Nano/Super) kwarg")
_assert_parity(model, shape, low_effort=flag, **extra)
@pytest.mark.parametrize("flag", [True, False])
@pytest.mark.parametrize(
"shape,extra", _EFFORT_SHAPES, ids=["gen_prompt", "multi_turn"]
)
def test_medium_effort_kwarg(model, flag, shape, extra):
"""``medium_effort`` appends ``\\n\\n{reasoning effort: efficient}`` on
**Ultra**. Nano/Super configs have no such field, so they're skipped."""
if model != ULTRA:
pytest.skip("medium_effort is a nemotron-3-ultra kwarg")
_assert_parity(model, shape, medium_effort=flag, **extra)
def test_effort_kwarg_lives_on_the_right_variant(model):
"""Each effort kwarg is declared only on the variant whose template defines
it — the discriminated union rejects the wrong combination at config load."""
fields = _config_cls(model).template_field_names()
if model == ULTRA:
assert "medium_effort" in fields and "low_effort" not in fields
else:
assert "low_effort" in fields and "medium_effort" not in fields
+104
View File
@@ -0,0 +1,104 @@
"""Offline wiring tests for the Nemotron-3 variant split.
Assert the model→renderer mapping, the per-variant typed-config surface, and
the name-based ``low_effort`` gating WITHOUT loading any tokenizer (no
network). This pins the wiring the parity matrix can't reach — in particular
the FP8 Ultra entry, which no test loads a tokenizer for — so it can't
silently rot.
The two variants:
* ``nemotron-3`` — Nano / Super, shared template. Config exposes ``low_effort``
(honoured on Super, a no-op on Nano).
* ``nemotron-3-ultra`` — Ultra, distinct ``</think>`` glue. Config exposes
``medium_effort``.
Both route to the one ``Nemotron3Renderer`` class, which selects the variant
from ``config.name``.
"""
from types import SimpleNamespace
from renderers.base import MODEL_RENDERER_MAP, RENDERER_REGISTRY, _populate_registry
from renderers.configs import (
Nemotron3RendererConfig,
Nemotron3UltraRendererConfig,
_config_class_for,
)
from renderers.nemotron3 import Nemotron3Renderer, Nemotron3UltraRenderer, _is_super
_ULTRA_REPOS = [
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8",
]
_NANO_SUPER_REPOS = [
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
]
def _fake_tok(name):
return SimpleNamespace(name_or_path=name)
def test_models_map_to_their_variant():
for repo in _ULTRA_REPOS:
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3-ultra", repo
for repo in _NANO_SUPER_REPOS:
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3", repo
def test_each_discriminator_maps_to_its_config_and_renderer_class():
# Config discriminator → config class.
assert _config_class_for("nemotron-3") is Nemotron3RendererConfig
assert _config_class_for("nemotron-3-ultra") is Nemotron3UltraRendererConfig
# Registry → renderer class (Ultra is a sibling subclass, matching the
# GLM-5/5.1 and Qwen3.5/3.6 house style — not one class under two names).
_populate_registry()
assert RENDERER_REGISTRY["nemotron-3"] is Nemotron3Renderer
assert RENDERER_REGISTRY["nemotron-3-ultra"] is Nemotron3UltraRenderer
assert issubclass(Nemotron3UltraRenderer, Nemotron3Renderer)
def test_variant_is_encoded_by_the_class():
# The ``</think>`` glue is selected by the class hook, not config.name —
# so the right renderer class must be constructed (create_renderer routes
# config.name → class). Default config also follows the class.
assert Nemotron3Renderer._ultra is False
assert Nemotron3UltraRenderer._ultra is True
assert Nemotron3Renderer._config_cls is Nemotron3RendererConfig
assert Nemotron3UltraRenderer._config_cls is Nemotron3UltraRendererConfig
def test_template_fields_per_variant():
# ``low_effort`` lives only on the Nano/Super config; ``medium_effort``
# only on Ultra. Both ARE chat-template kwargs (unlike the removed ``ultra``
# selector), so they appear in the template-field surface.
assert Nemotron3RendererConfig.template_field_names() == frozenset(
{"enable_thinking", "truncate_history_thinking", "low_effort"}
)
assert Nemotron3UltraRendererConfig.template_field_names() == frozenset(
{"enable_thinking", "truncate_history_thinking", "medium_effort"}
)
def test_configs_reject_the_other_variants_effort_kwarg():
# Discriminated-union honesty: a bad combination fails at config-load.
import pytest
from pydantic import ValidationError
with pytest.raises(ValidationError):
Nemotron3RendererConfig(medium_effort=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
Nemotron3UltraRendererConfig(low_effort=True) # type: ignore[call-arg]
# And the removed ``ultra`` selector is gone entirely.
with pytest.raises(ValidationError):
Nemotron3RendererConfig(ultra=True) # type: ignore[call-arg]
def test_is_super_name_detection():
assert _is_super(_fake_tok("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"))
assert not _is_super(_fake_tok("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"))
# Unknown / local-path checkpoints default to False → low_effort no-op.
assert not _is_super(_fake_tok("/home/user/local-ckpt"))
assert not _is_super(SimpleNamespace()) # no name_or_path attr
+141 -2
View File
@@ -13,7 +13,7 @@ from renderers.base import ToolCallParseStatus, load_tokenizer
@lru_cache
def _qwen3_vl():
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
renderer = create_renderer(tokenizer, renderer="auto")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
@@ -98,10 +98,73 @@ def test_qwen3_vl_malformed_tool_call_surfaces_as_invalid_json():
assert tc.token_span is not None
@lru_cache
def _qwen3():
tokenizer = load_tokenizer("Qwen/Qwen3-0.6B")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
def test_qwen3_in_think_tool_call_is_not_a_real_call():
"""A ``<tool_call>`` the model drafts *inside* its ``<think>`` trace must
stay reasoning — only the call emitted after ``</think>`` counts.
Regression for #78: Thinking models (e.g. Qwen3-*-Thinking-2507) draft
tool-call syntax while planning. Because ``<tool_call>`` is a real vocab
token, the parser used to scan the whole stream and emit the in-think
draft *and* the genuine post-``</think>`` call as two tool calls — a
phantom duplicate that made callers execute the same code twice. The scan
is now anchored after ``</think>``, mirroring vLLM's reasoning-then-tools
ordering.
"""
tokenizer, renderer = _qwen3()
text = (
"<think>\nLet me draft the call:\n"
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
"</tool_call>\nYes, that looks right.\n</think>\n"
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
"</tool_call>"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "execute_code"
assert tc.arguments == {"code": "print(1)"}
# The drafted call stays in the reasoning trace, not content.
assert parsed.reasoning_content is not None
assert "<tool_call>" in parsed.reasoning_content
assert parsed.content == ""
def test_qwen3_distinct_parallel_calls_after_think_are_preserved():
"""The fix must not over-correct: two *genuine* parallel calls emitted
after ``</think>`` are still both returned (no dedup), preserving the
faithful-transcription contract for real invocations.
"""
tokenizer, renderer = _qwen3()
text = (
"<think>\nplan\n</think>\n"
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(1)"}}\n'
"</tool_call>\n"
'<tool_call>\n{"name": "execute_code", "arguments": {"code": "print(2)"}}\n'
"</tool_call>"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert len(parsed.tool_calls) == 2
assert [tc.arguments for tc in parsed.tool_calls] == [
{"code": "print(1)"},
{"code": "print(2)"},
]
assert parsed.reasoning_content == "plan"
@lru_cache
def _kimi_k25():
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
renderer = create_renderer(tokenizer, renderer="auto")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
@@ -135,3 +198,79 @@ def test_kimi_k25_tool_call_carries_token_span():
assert 0 <= start < end <= len(token_ids), (
f"span {tc.token_span} out of range for {len(token_ids)} input tokens"
)
def test_kimi_k25_in_think_section_is_not_a_real_call():
"""A tool-call section the model drafts inside its ``<think>`` trace must
not be parsed — only the section after ``</think>`` counts.
Regression for #78. K2.5's failure mode differed from Qwen3's: the
in-think section tripped the "truncated reasoning" guard and the parser
*dropped every tool call* (returned zero), losing the genuine call. The
scan is now anchored past ``</think>``.
"""
tokenizer, renderer = _kimi_k25()
section = (
"<|tool_calls_section_begin|>"
"<|tool_call_begin|>functions.execute_code:0"
'<|tool_call_argument_begin|>{"code": "print(1)"}'
"<|tool_call_end|><|tool_calls_section_end|>"
)
text = f"<think>\nLet me draft:\n{section}\nlooks right.\n</think>\nGo.\n{section}"
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "execute_code"
assert tc.arguments == {"code": "print(1)"}
# The drafted section stays in the reasoning trace.
assert parsed.reasoning_content is not None
assert "<|tool_calls_section_begin|>" in parsed.reasoning_content
assert parsed.content == "Go."
@lru_cache
def _deepseek_v3():
tokenizer = load_tokenizer("deepseek-ai/DeepSeek-V3")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
def test_deepseek_v3_in_think_section_is_not_a_real_call():
"""A tool-call section drafted inside ``<think>`` must not be parsed —
only the section after ``</think>`` counts.
Regression for #78. DeepSeek-V3's failure mode: it returned the *wrong*
call (the in-think draft) and lost reasoning, because ``</think>`` is
multi-token text there and the scan wasn't anchored past it.
"""
tokenizer, renderer = _deepseek_v3()
def section(name: str) -> str:
return (
"<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>"
f'{name}\n```json\n{{"code": "print(1)"}}\n```'
"<|tool▁call▁end|><|tool▁calls▁end|>"
)
text = (
f"<think>\nLet me draft:\n{section('draft_tool')}\nlooks right.\n</think>\n"
f"Go.\n{section('real_tool')}"
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
# Assert the *post-``</think>``* section was chosen, not the in-think draft.
# (Use ``startswith`` rather than ``== "real_tool"``: under transformers
# 5.x the DeepSeek tokenizer's decode drops the ``\n`` between name and the
# ```json fence, so ``_parse_deepseek_tool_calls`` folds the fence into the
# name — a pre-existing, #78-unrelated quirk. What matters here is *which*
# section won.)
assert tc.name is not None and tc.name.startswith("real_tool")
assert "draft_tool" not in tc.name
# The drafted section stays in the reasoning trace, not content.
assert parsed.reasoning_content is not None
assert "draft_tool" in parsed.reasoning_content
assert parsed.content == "Go."
+1 -2
View File
@@ -133,8 +133,7 @@ def test_tool_calls_is_list_of_parsed_tool_call(model_name, tokenizer, renderer)
Empty list = "model did not emit any tool calls". A list with non-OK
entries = "model tried and the parser caught the failure"; those are
deliberately preserved so verifier / RL-loss code can see them. This
replaces the older list-or-None convention.
deliberately preserved so verifier / RL-loss code can see them.
"""
text = "Hello!"
ids = tokenizer.encode(text, add_special_tokens=False)
+5 -4
View File
@@ -114,11 +114,12 @@ def test_think_reasoning_parser_no_block():
def test_default_renderer_uses_parsers():
"""DefaultRenderer + parsers should extract tool calls and reasoning."""
from renderers import create_renderer
from renderers import DefaultRendererConfig, create_renderer
tok = load_tokenizer("Qwen/Qwen3-0.6B")
renderer = create_renderer(
tok, renderer="default", tool_parser="qwen3", reasoning_parser="think"
tok,
DefaultRendererConfig(tool_parser="qwen3", reasoning_parser="think"),
)
assert renderer.supports_tools is True
@@ -134,10 +135,10 @@ def test_default_renderer_uses_parsers():
def test_default_renderer_without_parsers_is_backward_compatible():
"""Without parsers, DefaultRenderer still does basic <think> extraction."""
from renderers import create_renderer
from renderers import DefaultRendererConfig, create_renderer
tok = load_tokenizer("Qwen/Qwen3-0.6B")
renderer = create_renderer(tok, renderer="default")
renderer = create_renderer(tok, DefaultRendererConfig())
assert renderer.supports_tools is False
ids = tok.encode("<think>r</think>a", add_special_tokens=False)
+62 -45
View File
@@ -1,9 +1,10 @@
"""Smoke coverage for the ``preserve_*_thinking`` override flags.
Flags are constructor-only (``create_renderer(..., preserve_all_thinking=True)``)
and stored as instance attributes — there is no call-site ``render`` /
``render_ids`` override. Each test that wants a non-default flag builds
a fresh renderer for that configuration via ``_make`` below.
Flags live on the typed renderer config (e.g.
``Qwen3RendererConfig(preserve_all_thinking=True)``) and are stored on
the renderer as ``self.config.preserve_*``. Each test that wants a
non-default flag builds a fresh renderer for that configuration via
``_make`` below.
Two invariants per renderer:
@@ -22,15 +23,22 @@ default==override equality instead of strict growth.
from __future__ import annotations
import pytest
from pydantic import ValidationError
from renderers import create_renderer
from renderers.base import should_preserve_past_thinking
from renderers.base import MODEL_RENDERER_MAP, should_preserve_past_thinking
from renderers.configs import _config_class_for
def _make(tokenizer, renderer_name, **flags):
"""Build a fresh renderer with the given preserve_*_thinking flags
bound at construction. Reuses the cached tokenizer fixture."""
return create_renderer(tokenizer, renderer=renderer_name, **flags)
if renderer_name == "auto":
renderer_name = MODEL_RENDERER_MAP.get(
getattr(tokenizer, "name_or_path", ""), "default"
)
config = _config_class_for(renderer_name)(**flags)
return create_renderer(tokenizer, config)
# Renderers whose template doesn't drop past-asst thinking or has no
@@ -43,6 +51,11 @@ NO_OP_MODELS = {
"Qwen/Qwen3-VL-8B-Instruct",
"Qwen/Qwen3-VL-30B-A3B-Instruct",
"poolside/Laguna-XS.2",
# Llama-3 has no reasoning channel at all — preserve flags can't add
# or drop anything, so they're pure no-ops.
"meta-llama/Llama-3.2-1B-Instruct",
"meta-llama/Llama-3.2-3B-Instruct",
"unsloth/Llama-3.2-1B-Instruct",
}
@@ -311,6 +324,11 @@ NEVER_PRESERVES_MODELS = {
"Qwen/Qwen3-VL-4B-Instruct",
"Qwen/Qwen3-VL-8B-Instruct",
"Qwen/Qwen3-VL-30B-A3B-Instruct",
# Llama-3 ships no <think> rendering path, so reasoning_content never
# surfaces in the output regardless of the preserve flags.
"meta-llama/Llama-3.2-1B-Instruct",
"meta-llama/Llama-3.2-3B-Instruct",
"unsloth/Llama-3.2-1B-Instruct",
}
@@ -379,17 +397,19 @@ def test_default_renderer_raises_on_flags():
"""``DefaultRenderer`` falls back to apply_chat_template with no
selective re-emit pathway, so constructing one with either flag set
must raise — fail fast, before any render is attempted."""
from renderers import DefaultRendererConfig
from renderers.base import load_tokenizer
tok = load_tokenizer("Qwen/Qwen2.5-0.5B-Instruct")
# No flags → constructs cleanly.
create_renderer(tok, renderer="default")
create_renderer(tok, DefaultRendererConfig())
# Either flag set → raises at construction.
with pytest.raises(NotImplementedError):
create_renderer(tok, renderer="default", preserve_all_thinking=True)
create_renderer(tok, DefaultRendererConfig(preserve_all_thinking=True))
with pytest.raises(NotImplementedError):
create_renderer(
tok, renderer="default", preserve_thinking_between_tool_calls=True
tok,
DefaultRendererConfig(preserve_thinking_between_tool_calls=True),
)
@@ -399,31 +419,27 @@ def test_default_renderer_raises_on_flags():
def test_create_renderer_records_flag_state(model_name, renderer_name, tokenizer):
"""Each renderer exposes the bound flag state via ``_preserve_*``
attributes — useful for downstream code (pool cache keys, logging,
test assertions) that needs to confirm what was constructed."""
"""Each renderer exposes the bound flag state via ``self.config`` —
useful for downstream code (pool cache keys, logging, test
assertions) that needs to confirm what was constructed."""
from renderers.default import DefaultRenderer
bare = create_renderer(tokenizer, renderer=renderer_name)
assert bare._preserve_all_thinking is False
assert bare._preserve_thinking_between_tool_calls is False
bare = _make(tokenizer, renderer_name)
assert bare.config.preserve_all_thinking is False
assert bare.config.preserve_thinking_between_tool_calls is False
if not isinstance(bare, DefaultRenderer):
# DefaultRenderer raises at construction with either flag set —
# covered by ``test_default_renderer_raises_on_flags``.
all_on = create_renderer(
tokenizer, renderer=renderer_name, preserve_all_thinking=True
)
assert all_on._preserve_all_thinking is True
assert all_on._preserve_thinking_between_tool_calls is False
all_on = _make(tokenizer, renderer_name, preserve_all_thinking=True)
assert all_on.config.preserve_all_thinking is True
assert all_on.config.preserve_thinking_between_tool_calls is False
btc_on = create_renderer(
tokenizer,
renderer=renderer_name,
preserve_thinking_between_tool_calls=True,
btc_on = _make(
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
)
assert btc_on._preserve_all_thinking is False
assert btc_on._preserve_thinking_between_tool_calls is True
assert btc_on.config.preserve_all_thinking is False
assert btc_on.config.preserve_thinking_between_tool_calls is True
# ---------------------------------------------------------------------------
@@ -431,30 +447,31 @@ def test_create_renderer_records_flag_state(model_name, renderer_name, tokenizer
# ---------------------------------------------------------------------------
def test_glm5_constructor_rejects_clear_thinking():
"""``clear_thinking`` was a chat-template-kwarg pass-through. It is
superseded by the renderer-agnostic ``preserve_all_thinking`` override
and must no longer be accepted by the constructor — its default-True
semantics are now baked into the render gate."""
def test_glm5_config_accepts_clear_thinking():
"""``clear_thinking`` is a chat-template field on GLM-5's typed
config. The GLM-5 / GLM-5.1 Jinja templates gate historical
reasoning on ``clear_thinking is defined and not clear_thinking``,
so passing ``clear_thinking=False`` here must reach the renderer's
historical-reasoning gate. Parity vs ``apply_chat_template`` is
asserted in ``test_renderer_config_parity``."""
from renderers import GLM5RendererConfig
from renderers.base import load_tokenizer
from renderers.glm5 import GLM5Renderer
tok = load_tokenizer("zai-org/GLM-5")
with pytest.raises(TypeError):
GLM5Renderer(tok, clear_thinking=True) # type: ignore[call-arg]
with pytest.raises(TypeError):
GLM5Renderer(tok, clear_thinking=False) # type: ignore[call-arg]
# Both values must be accepted without raising.
GLM5Renderer(tok, GLM5RendererConfig(clear_thinking=True))
GLM5Renderer(tok, GLM5RendererConfig(clear_thinking=False))
def test_qwen36_constructor_rejects_preserve_thinking():
def test_qwen36_config_rejects_unknown_field():
"""``preserve_thinking`` on Qwen3.6 was a chat-template-kwarg
pass-through. It is superseded by the renderer-agnostic
``preserve_all_thinking`` override and must no longer be accepted by
the constructor — its default-False semantics are now inherited from
Qwen3.5's render gate."""
from renderers.base import load_tokenizer
from renderers.qwen36 import Qwen36Renderer
pass-through in an earlier revision. It is superseded by the
renderer-agnostic ``preserve_all_thinking`` override and must not
appear on the typed config — its default-False semantics are now
inherited from Qwen3.5's render gate. ``extra="forbid"`` on the
pydantic model enforces this at construction."""
from renderers import Qwen36RendererConfig
tok = load_tokenizer("Qwen/Qwen3.6-35B-A3B")
with pytest.raises(TypeError):
Qwen36Renderer(tok, preserve_thinking=True) # type: ignore[call-arg]
with pytest.raises(ValidationError, match="preserve_thinking"):
Qwen36RendererConfig(preserve_thinking=True) # type: ignore[call-arg]
+37 -14
View File
@@ -5,9 +5,8 @@ Seven Qwen3.5 sizes route to ``Qwen35Renderer``. The 4B / 9B / 35B-A3B /
``enable_thinking=true``); the smaller 0.8B / 2B sizes ship the polarity-
flipped variant (default ``enable_thinking=false`` → empty
``<think>\\n\\n</think>\\n\\n`` at the gen-prompt boundary). The renderer
detects polarity from the tokenizer's chat_template at construction, so
both variants render byte-identical to their own
``apply_chat_template``.
hard-codes this polarity per model (``_ENABLE_THINKING_DEFAULTS``), so
both variants render byte-identical to their own ``apply_chat_template``.
These tests lock in (a) the exact set of Qwen3.5 sizes in the map and
(b) byte parity for every one of them across representative
@@ -19,7 +18,7 @@ from __future__ import annotations
import pytest
from renderers import Qwen35Renderer, create_renderer
from renderers import Qwen35Renderer, Qwen35RendererConfig, create_renderer
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
@@ -57,7 +56,7 @@ def test_no_other_qwen35_sizes_silently_added():
# ---------------------------------------------------------------------------
# Polarity auto-detection: 0.8B / 2B flip ``enable_thinking`` default.
# Polarity defaults: 0.8B / 2B flip ``enable_thinking`` default.
# ---------------------------------------------------------------------------
@@ -73,19 +72,43 @@ def test_no_other_qwen35_sizes_silently_added():
("Qwen/Qwen3.5-397B-A17B", True),
],
)
def test_qwen35_enable_thinking_polarity_autodetected(qwen35_model, expected_default):
"""The renderer's ``_enable_thinking`` resolves to the chat template's
own default when no explicit flag is passed — so big / small sizes
each match their own template at the gen-prompt boundary."""
def test_qwen35_enable_thinking_polarity_default(qwen35_model, expected_default):
"""With no explicit flag, the renderer resolves ``enable_thinking`` from
the hard-coded per-model default — so big / small sizes each match their
own template at the gen-prompt boundary."""
tok = load_tokenizer(qwen35_model)
renderer = create_renderer(tok, renderer="qwen3.5")
renderer = create_renderer(tok, Qwen35RendererConfig())
assert isinstance(renderer, Qwen35Renderer)
assert renderer._enable_thinking is expected_default, (
assert renderer.config.enable_thinking is expected_default, (
f"{qwen35_model}: expected enable_thinking default {expected_default}, "
f"got {renderer._enable_thinking}"
f"got {renderer.config.enable_thinking}"
)
def test_construction_does_not_call_apply_chat_template():
"""The ``enable_thinking`` default is hard-coded per model, so building a
``Qwen35Renderer`` must not probe ``apply_chat_template`` — a
bring-your-own tokenizer with no chat-template support still works."""
class _Stub:
name_or_path = "Qwen/Qwen3.5-0.8B"
unk_token_id = -1
def convert_tokens_to_ids(self, token):
# Any stable non-unk id per token; the renderer only needs the
# special tokens to resolve to distinct, in-vocab ids.
return abs(hash(token)) % 1_000_000 + 1
def apply_chat_template(self, *args, **kwargs):
raise AssertionError(
"apply_chat_template must not be called at construction"
)
renderer = Qwen35Renderer(_Stub())
# 0.8B is a small size → thinking defaults off, from the hard-coded table.
assert renderer.config.enable_thinking is False
# ---------------------------------------------------------------------------
# Byte parity for each in-map Qwen3.5 size.
# ---------------------------------------------------------------------------
@@ -146,9 +169,9 @@ def test_qwen35_size_parity_with_apply_chat_template(
"""Each in-map Qwen3.5 size renders byte-identical to its own
``apply_chat_template`` output. Locks in the property that lets us
share ``Qwen35Renderer`` across all seven sizes — the polarity
flip on 0.8B / 2B is absorbed by the constructor's auto-detect."""
flip on 0.8B / 2B is absorbed by the per-model default."""
tok = load_tokenizer(qwen35_model)
renderer = create_renderer(tok, renderer="qwen3.5")
renderer = create_renderer(tok, Qwen35RendererConfig())
assert isinstance(renderer, Qwen35Renderer)
ours = renderer.render_ids(messages, add_generation_prompt=add_gen_prompt)
+3 -3
View File
@@ -338,7 +338,7 @@ def test_multi_step_tool_cycle(model_name, tokenizer, renderer):
@lru_cache
def _qwen3_vl():
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
renderer = create_renderer(tokenizer, renderer="auto")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
@@ -353,7 +353,7 @@ def test_qwen3_vl_auto_renderer():
@lru_cache
def _kimi_k25():
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
renderer = create_renderer(tokenizer, renderer="auto")
renderer = create_renderer(tokenizer)
return tokenizer, renderer
@@ -366,7 +366,7 @@ def test_kimi_k2_inline_think_tags_render_verbatim():
reasoning, producing tokens that disagreed with ``apply_chat_template``.
"""
tokenizer = load_tokenizer("moonshotai/Kimi-K2-Instruct")
renderer = create_renderer(tokenizer, renderer="auto")
renderer = create_renderer(tokenizer)
msgs = [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "<think>secret</think>visible"},
+116
View File
@@ -0,0 +1,116 @@
"""Unit tests for the typed-config surface — discriminated union,
auto-resolution, and ``extra="forbid"`` enforcement on per-renderer
configs."""
from types import SimpleNamespace
import pytest
from pydantic import TypeAdapter, ValidationError
from renderers import (
AutoRendererConfig,
DefaultRendererConfig,
GLM5RendererConfig,
Qwen3RendererConfig,
Qwen35RendererConfig,
RendererConfig,
base,
create_renderer,
)
def test_per_renderer_config_rejects_unknown_fields():
"""``extra="forbid"`` on every typed variant catches bogus keys at
construction: ``add_vision_id`` doesn't exist on ``Qwen3RendererConfig``
(Qwen3 is text-only), so passing it must raise."""
with pytest.raises(ValidationError, match="add_vision_id"):
Qwen3RendererConfig(add_vision_id=True)
def test_discriminated_union_dispatches_on_name():
"""A dict shaped like ``{"name": "glm-5", ...}`` deserialises to the
matching typed config; the union ``RendererConfig`` is what
downstream consumers (prime-rl, verifiers) hold as a single field."""
ta = TypeAdapter(RendererConfig)
parsed = ta.validate_python(
{"name": "glm-5", "enable_thinking": False, "clear_thinking": False}
)
assert isinstance(parsed, GLM5RendererConfig)
assert parsed.enable_thinking is False
assert parsed.clear_thinking is False
def test_discriminated_union_rejects_wrong_renderer_kwargs():
"""``add_vision_id`` under ``name="qwen3"`` is invalid at deserialise
time — the discriminator narrows to ``Qwen3RendererConfig`` whose
schema does not include that field."""
ta = TypeAdapter(RendererConfig)
with pytest.raises(ValidationError, match="add_vision_id"):
ta.validate_python({"name": "qwen3", "add_vision_id": True})
def test_default_renderer_config_accepts_arbitrary_extras():
"""``DefaultRenderer`` wraps ``apply_chat_template`` for unknown
templates, so its config uses ``extra="allow"`` and surfaces extras
via ``model_extra``."""
cfg = DefaultRendererConfig(
tool_parser="qwen3", enable_thinking=False, custom_jinja_kwarg=True
)
assert cfg.tool_parser == "qwen3"
assert cfg.model_extra == {
"enable_thinking": False,
"custom_jinja_kwarg": True,
}
def test_create_renderer_forwards_typed_config_to_renderer(monkeypatch):
"""``create_renderer`` dispatches on ``config.name`` via
``RENDERER_REGISTRY``; the renderer stores the config it was given."""
class _FakeRenderer:
def __init__(self, tokenizer, config):
self.tokenizer = tokenizer
self.config = config
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeRenderer)
renderer = create_renderer(
SimpleNamespace(name_or_path="unused"),
Qwen3RendererConfig(enable_thinking=False),
)
assert isinstance(renderer.config, Qwen3RendererConfig)
assert renderer.config.enable_thinking is False
def test_create_renderer_auto_resolves_via_model_map(monkeypatch):
"""``AutoRendererConfig`` (or ``config=None``) routes through
``MODEL_RENDERER_MAP`` to pick the matching renderer + typed config,
carrying the shared ``preserve_*`` flags over from the auto config."""
class _FakeQwen35:
def __init__(self, tokenizer, config):
self.tokenizer = tokenizer
self.config = config
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3.5", _FakeQwen35)
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen35", "qwen3.5")
renderer = create_renderer(
SimpleNamespace(name_or_path="fake/qwen35"),
AutoRendererConfig(preserve_all_thinking=True),
)
assert isinstance(renderer.config, Qwen35RendererConfig)
assert renderer.config.preserve_all_thinking is True
# Template-level kwargs stay at their per-renderer defaults — auto
# carries only the preserve_* flags.
assert renderer.config.add_vision_id is False
def test_create_renderer_default_argument_is_auto():
"""Passing no config is equivalent to passing ``AutoRendererConfig()``
— short form for the common case."""
tok = SimpleNamespace(name_or_path="") # no MODEL_RENDERER_MAP entry
renderer = create_renderer(tok)
# Falls through to DefaultRenderer when no match and no vision config.
assert renderer.__class__.__name__ == "DefaultRenderer"
+527
View File
@@ -0,0 +1,527 @@
"""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"),
("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],
"reasoning_effort": ["low", "medium", "high"],
# 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],
# 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 _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, []):
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, []):
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)})"
)
+13 -3
View File
@@ -43,7 +43,11 @@ _ROUNDTRIP_MODELS = [
("moonshotai/Kimi-K2.6", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
# Ultra: parse must recover content after a </think> glued directly to it
# (no separating newline) — the Ultra-specific glue stresses the round-trip.
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
("poolside/Laguna-XS.2", "auto"),
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
("openai/gpt-oss-20b", "gpt-oss"),
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
]
@@ -51,11 +55,11 @@ _ROUNDTRIP_MODELS = [
@lru_cache(maxsize=None)
def _load_renderer(model_name: str, renderer_name: str):
from renderers import create_renderer
from renderers import config_from_name, create_renderer
from renderers.base import load_tokenizer
tok = load_tokenizer(model_name)
return tok, create_renderer(tok, renderer=renderer_name)
return tok, create_renderer(tok, config_from_name(renderer_name))
def pytest_generate_tests(metafunc):
@@ -207,6 +211,12 @@ def test_roundtrip_multiple_tool_calls(
"""Parsers that loop over ``<tool_call>…</tool_call>`` blocks can
silently drop the second one; this test catches that."""
_maybe_skip_tool_calls(rt_renderer_name)
if rt_renderer_name == "llama-3":
pytest.skip(
"Llama-3's chat template forbids >1 tool call per assistant "
"message (the renderer raises, mirroring the template); the "
"single-call path is covered by test_roundtrip_single_tool_call."
)
msg = {
"role": "assistant",
@@ -316,7 +326,7 @@ def test_default_renderer_fallback_parser_preserves_boundary_whitespace(
"""
from renderers.default import DefaultRenderer
renderer = DefaultRenderer(rt_tokenizer, tool_parser=None, reasoning_parser=None)
renderer = DefaultRenderer(rt_tokenizer)
# Encode `<think>reason</think>\nvisible` as text and run through
# parse_response. We don't need the template to emit `<think>` here
+325
View File
@@ -0,0 +1,325 @@
"""Tests for per-message / per-role token-count and span helpers.
These methods on :class:`RenderedTokens` derive from the existing
``message_indices`` / ``sampled_mask`` / ``message_roles`` signals —
they're analytics helpers, not new attribution. The contract these
tests pin:
- ``sum(tokens_per_message()) + scaffold_count == len(token_ids)`` — the
helper accounts for every token exactly once, with ``-1``-attributed
scaffolding outside the per-message bucket.
- ``sampled_only=True`` excludes the role-tag opener
(``<|im_start|>role\\n``) the template injects around an assistant
message. The assistant message's sampled count must be strictly less
than its total count.
- ``sampled_only=True`` is zero for tool / user / system roles — the
model never samples conversation history.
- ``message_token_spans`` returns contiguous ``(start, end)`` slices
per message that ``zip``s against ``message_roles``. Slicing
``token_ids[start:end]`` recovers the message's tokens.
Renderers that opt out of ``sampled_mask`` (DefaultRenderer — the
Jinja template is opaque) are exempt from the ``sampled_only``
assertions and return all zeros from the helper under that flag.
"""
from __future__ import annotations
from renderers.base import RenderedTokens
def test_tokens_per_message_sum_equals_attributed(model_name, renderer):
"""``sum(tokens_per_message()) + scaffold_count == len(token_ids)``.
Every token lands in exactly one of (a) a caller-relative message
bucket, or (b) the ``-1`` scaffolding bucket. No double-counts, no
drops.
"""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs, add_generation_prompt=True)
counts = rendered.tokens_per_message()
scaffold = sum(1 for idx in rendered.message_indices if idx == -1)
assert sum(counts) + scaffold == len(rendered.token_ids), (
f"{model_name}: tokens_per_message sum {sum(counts)} + scaffold "
f"{scaffold} != token count {len(rendered.token_ids)}"
)
# message_roles populated, length matches caller input.
assert len(rendered.message_roles) == len(msgs), (
f"{model_name}: message_roles length {len(rendered.message_roles)} "
f"!= len(msgs) {len(msgs)}"
)
assert rendered.message_roles == ["system", "user", "assistant"], (
f"{model_name}: message_roles {rendered.message_roles} != input roles"
)
# Every caller message must have a positive count.
bad = [i for i, n in enumerate(counts) if n == 0]
assert not bad, f"{model_name}: messages with zero attributed tokens: {bad}"
def test_tokens_per_message_sampled_lt_total_for_assistant(model_name, renderer):
"""The assistant message's ``sampled_only=True`` count must be
strictly less than its full count.
The template wraps an assistant turn with at least one role-tag
token (``<|im_start|>assistant\\n`` or equivalent) that the model
doesn't sample at inference. Skips renderers that opt out of
``sampled_mask`` (DefaultRenderer).
"""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello world!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return
total = rendered.tokens_per_message()
sampled = rendered.tokens_per_message(sampled_only=True)
assistant_idx = 1
assert sampled[assistant_idx] < total[assistant_idx], (
f"{model_name}: assistant sampled count {sampled[assistant_idx]} "
f"not strictly less than total {total[assistant_idx]} — role-tag "
f"opener should have been excluded"
)
assert sampled[assistant_idx] > 0, (
f"{model_name}: assistant sampled count is zero — content tokens "
f"should be is_sampled=True"
)
def test_tokens_per_message_sampled_zero_for_history_roles(model_name, renderer):
"""``sampled_only=True`` counts are zero for user / system / tool —
the model never samples conversation history."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return
sampled = rendered.tokens_per_message(sampled_only=True)
assert sampled[0] == 0, (
f"{model_name}: system message sampled count {sampled[0]} != 0"
)
assert sampled[1] == 0, (
f"{model_name}: user message sampled count {sampled[1]} != 0"
)
def test_tokens_per_message_truncates_to_n_messages(model_name, renderer):
"""Passing explicit ``n_messages`` smaller than the populated count
silently drops tail messages — the helper doesn't raise."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
truncated = rendered.tokens_per_message(1)
assert len(truncated) == 1
assert truncated[0] > 0
def test_tokens_per_message_clamps_oversized_n_messages(model_name, renderer):
"""Passing ``n_messages`` larger than ``len(message_roles)`` is
clamped — the helper never reports more messages than the renderer
attributed, so callers can't read trailing-zero phantoms."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
clamped = rendered.tokens_per_message(99)
assert len(clamped) == len(rendered.message_roles)
assert clamped == rendered.tokens_per_message()
def test_tokens_per_message_bridge_attributes_new_messages(model_name, renderer):
"""``bridge_to_next_turn`` returns ``RenderedTokens`` with proper
per-token attribution AND populated ``message_roles`` for
``new_messages``. ``sampled_mask`` is uniformly ``False``.
DefaultRenderer's ``bridge_to_next_turn`` returns ``None``
unconditionally, so we skip when bridge is unsupported.
"""
prior = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered_prior = renderer.render(prior, add_generation_prompt=False)
new_messages = [
{"role": "user", "content": "Tell me a longer story please"},
]
bridge = renderer.bridge_to_next_turn(
previous_prompt_ids=rendered_prior.token_ids,
previous_completion_ids=[],
new_messages=new_messages,
)
if bridge is None:
return
assert len(bridge.message_indices) == len(bridge.token_ids), (
f"{model_name}: bridge message_indices length mismatch"
)
assert len(bridge.sampled_mask) == len(bridge.token_ids), (
f"{model_name}: bridge sampled_mask length mismatch"
)
assert bridge.message_roles == ["user"], (
f"{model_name}: bridge message_roles {bridge.message_roles} != ['user']"
)
assert not any(bridge.sampled_mask), (
f"{model_name}: bridge emitted a token marked is_sampled=True"
)
counts = bridge.tokens_per_message()
assert counts == [counts[0]] and counts[0] > 0, (
f"{model_name}: bridge attributed {counts} tokens; expected one "
f"positive entry for the new user message"
)
def test_tokens_by_role_includes_every_input_role(model_name, renderer):
"""``tokens_by_role`` returns a key for every role that appears in
``message_roles``. Counts sum to the same value as
``tokens_per_message``.
"""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
by_role = rendered.tokens_by_role()
assert set(by_role) == {"system", "user", "assistant"}, (
f"{model_name}: tokens_by_role keys {set(by_role)} != expected roles"
)
assert sum(by_role.values()) == sum(rendered.tokens_per_message()), (
f"{model_name}: tokens_by_role sum disagrees with tokens_per_message sum"
)
def test_tokens_by_role_sampled_only_assistant_only(model_name, renderer):
"""Under ``sampled_only=True``, only ``assistant`` has a positive
count — every other role's tokens were template-injected."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return
by_role = rendered.tokens_by_role(sampled_only=True)
assert by_role["assistant"] > 0
assert by_role["system"] == 0
assert by_role["user"] == 0
def test_message_token_spans_recover_token_ranges(model_name, renderer):
"""``message_token_spans()`` returns ``(start, end)`` such that
``token_ids[start:end]`` contains exactly the tokens attributed to
that message and ``token_ids[end-1]`` is still in that message
(i.e. the span is the inclusive token range of the message).
Also: spans cover every non-scaffolding token; the spans are
ordered by message index; concatenating
``token_ids[start:end]`` for every non-None span plus the
``-1``-attributed scaffolding tokens equals the original
``token_ids``.
"""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs, add_generation_prompt=True)
spans = rendered.message_token_spans()
assert len(spans) == len(msgs)
# Each span's tokens match the message_indices attribution.
for i, span in enumerate(spans):
assert span is not None, f"{model_name}: message {i} has no span"
start, end = span
attributed = [
rendered.message_indices[k]
for k in range(start, end)
if rendered.message_indices[k] == i
]
# At least one token in the span belongs to this message
# (contiguity assumption — see method docstring).
assert attributed, (
f"{model_name}: span {span} for msg {i} contains no msg-i tokens"
)
# Spans are non-decreasing by start.
starts = [s[0] for s in spans if s is not None]
assert starts == sorted(starts), (
f"{model_name}: spans not in message order: {starts}"
)
def test_role_token_spans_groups_by_role(model_name, renderer):
"""``role_token_spans()`` groups :meth:`message_token_spans` by
role. The total tokens captured per role should match
``tokens_by_role()``.
"""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
role_spans = rendered.role_token_spans()
by_role = rendered.tokens_by_role()
for role, spans in role_spans.items():
span_total = sum(e - s for s, e in spans)
assert span_total == by_role[role], (
f"{model_name}: role {role!r} span-total {span_total} != "
f"tokens_by_role {by_role[role]}"
)
def test_tokens_per_message_no_messages_helper_works():
"""Pure-data-shape: methods on a manually-constructed RenderedTokens
without any renderer involvement. No fixture needed."""
r = RenderedTokens(
token_ids=[10, 11, 12, 13, 14],
message_indices=[0, 0, 1, 1, -1],
sampled_mask=[False, True, False, False, False],
message_roles=["user", "assistant"],
)
assert r.tokens_per_message() == [2, 2]
assert r.tokens_per_message(sampled_only=True) == [1, 0]
assert r.tokens_by_role() == {"user": 2, "assistant": 2}
assert r.tokens_by_role(sampled_only=True) == {"user": 1, "assistant": 0}
assert r.message_token_spans() == [(0, 2), (2, 4)]
assert r.role_token_spans() == {
"user": [(0, 2)],
"assistant": [(2, 4)],
}
def test_message_token_spans_empty_message():
"""A message that contributed zero tokens (rare but possible for
empty content some templates skip) gets ``None`` as its span."""
r = RenderedTokens(
token_ids=[10, 11, 12],
message_indices=[0, 0, 2],
message_roles=["user", "assistant", "tool"],
)
spans = r.message_token_spans()
assert spans[0] == (0, 2)
assert spans[1] is None # no tokens attributed
assert spans[2] == (2, 3)
+76 -3
View File
@@ -26,7 +26,7 @@ import pytest
# (HuggingFace model name, renderer name). Two JSON-shaped controls
# (string types already preserved by the wire format) + four XML-style
# (string types already preserved by the wire format) + five XML-style
# parsers that rely on the schema to preserve them.
_MODELS = [
("Qwen/Qwen3-8B", "auto"), # hermes JSON — control
@@ -35,16 +35,17 @@ _MODELS = [
("zai-org/GLM-5", "auto"), # XML
("MiniMaxAI/MiniMax-M2.5", "auto"), # XML
("poolside/Laguna-XS.2", "auto"), # XML
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"), # XML
]
@lru_cache(maxsize=None)
def _load(model: str, renderer_name: str):
from renderers import create_renderer
from renderers import config_from_name, create_renderer
from renderers.base import load_tokenizer
tok = load_tokenizer(model)
return tok, create_renderer(tok, renderer=renderer_name)
return tok, create_renderer(tok, config_from_name(renderer_name))
def pytest_generate_tests(metafunc):
@@ -137,3 +138,75 @@ def test_string_arg_preserves_type(model, renderer_name, renderer, args):
assert got == args, (
f"{model}: tool-arg type drift — sent {args!r}, parser returned {got!r}"
)
# Schemas where ``string`` is one branch of a union (``anyOf`` / ``oneOf``).
# These are common in practice — e.g. ``form_input.value: str | bool`` in
# Pydantic serialises to ``{"anyOf": [{"type": "string"}, {"type": "boolean"}]}``.
# Without the union-aware check, the XML parser's ``json.loads`` falls back
# to raw text for bare strings, but flags the call ``INVALID_JSON`` because
# no top-level ``type`` key declared a string — silently dropping otherwise
# valid tool calls in the renderer client.
UNION_WITH_STRING_SCHEMAS = [
pytest.param(
{"anyOf": [{"type": "string"}, {"type": "boolean"}]},
id="anyOf-string-boolean",
),
pytest.param(
{"anyOf": [{"type": "string"}, {"type": "null"}]},
id="anyOf-string-null",
),
pytest.param(
{"oneOf": [{"type": "string"}, {"type": "integer"}]},
id="oneOf-string-integer",
),
]
@pytest.mark.parametrize("param_schema", UNION_WITH_STRING_SCHEMAS)
def test_union_with_string_emits_ok_status(
model, renderer_name, renderer, param_schema
):
"""Union schemas containing ``string`` must yield ``status=OK`` when
the model emits a bare string. Pre-fix, ``_coerce_arg_value`` flagged
this as ``INVALID_JSON`` because the top-level ``type`` key was
absent (the string branch was under ``anyOf`` / ``oneOf``)."""
from renderers.base import ToolCallParseStatus
tools = [
{
"type": "function",
"function": {
"name": "f",
"description": "Test tool with one union-typed parameter.",
"parameters": {
"type": "object",
"properties": {"x": param_schema},
"required": ["x"],
},
},
}
]
args = {"x": "abc"}
msg = {
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "functions.f:0",
"function": {"name": "f", "arguments": args},
}
],
}
completion_ids = _extract_assistant_tokens(renderer, PROMPT, msg, tools=tools)
parsed = renderer.parse_response(completion_ids, tools=tools)
assert parsed.tool_calls, f"{model}: parser returned no tool_calls"
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK, (
f"{model}: union-with-string schema flagged {tc.status} on bare string"
)
got = _normalize_args(tc.arguments)
assert got == args, (
f"{model}: tool-arg drift — sent {args!r}, parser returned {got!r}"
)
Generated
+53 -4
View File
@@ -9,9 +9,13 @@ resolution-markers = [
]
[options]
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer = "2026-05-18T21:42:54.18041997Z"
exclude-newer-span = "P7D"
[options.exclude-newer-package]
prime-pydantic-config = false
fastokens = false
[[package]]
name = "annotated-doc"
version = "0.0.4"
@@ -264,6 +268,35 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },
]
[[package]]
name = "fastokens"
version = "0.2.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/14/8e/7e88ec1d48db5a6e8d8d44318ce285e38c04b81508bdc2a60e17045a116f/fastokens-0.2.0.tar.gz", hash = "sha256:ef0e175de5c8cb1b616b3210d75dce1fab78e35fc02f77f03f7847d4678be686", size = 675822, upload-time = "2026-05-17T10:32:55.642Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e8/14/3d640cbe3c866ee6c113ea4ca37c16c5aa44be6412918928bbd3f3b739ef/fastokens-0.2.0-cp313-cp313t-macosx_10_12_x86_64.whl", hash = "sha256:e7db86c2785a502e3cd993c7d3a91c46e2751f94d1f446caa9600e9cf3dafbd1", size = 3078350, upload-time = "2026-05-17T10:32:41.313Z" },
{ url = "https://files.pythonhosted.org/packages/bc/bf/33ca3798842fb8bdacf03a97c874454d50fe328d44e0d3c3ba7a633fd3ab/fastokens-0.2.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fa8dcbc6ad3f7a7e9f5bf1ef3cfc9f0c04f0c8779be9e38864815dc567b27de4", size = 2983397, upload-time = "2026-05-17T10:32:38.823Z" },
{ url = "https://files.pythonhosted.org/packages/c4/0a/1bfd13fb855bce3ce50faa644d6e0e19343035706c2628e17da1247bbf50/fastokens-0.2.0-cp313-cp313t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:09b399600ae5beaa34e45afd05c6835b8569861955dfdc3e05afba25fe414e5a", size = 3309835, upload-time = "2026-05-17T10:32:33.427Z" },
{ url = "https://files.pythonhosted.org/packages/32/ce/33292977a81011ffc59cee1c20b6f8d0dbd9cb39209c327dc74dc542178d/fastokens-0.2.0-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f363b1e89fe4ed979224c326b25b33b28e1172134f3e7959238276170f12328e", size = 3615173, upload-time = "2026-05-17T10:32:30.898Z" },
{ url = "https://files.pythonhosted.org/packages/07/1c/1bef8b4831bf9220ae182fcee3e250273b7f537c81aec96041f6eb4bc990/fastokens-0.2.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d79358faa11658d8908fbdfab321b6ae6a0ff52ae3cdce7a0fda5c30629a276", size = 3295485, upload-time = "2026-05-17T10:32:36.109Z" },
{ url = "https://files.pythonhosted.org/packages/92/11/49afb739800b6a82af04fa1e991b68669c789ebeaa3bcbc96c2544c8ff9c/fastokens-0.2.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:cf6ae284b70d65989548a8143e1f463f31126f5650ad45ce6af05b83e4afb3e7", size = 3329524, upload-time = "2026-05-17T10:32:44.607Z" },
{ url = "https://files.pythonhosted.org/packages/f0/d2/f9b1c01535a0ce994d30e86cf49616023246134d2a406b74c5dd49df7825/fastokens-0.2.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:40fa091ff12aa8ac00fa8e2133c7256b96209827b88de5120eb1361600d7f68f", size = 3149194, upload-time = "2026-05-17T10:32:47.596Z" },
{ url = "https://files.pythonhosted.org/packages/bd/0b/95b2e5d25efc684988918658c90445e0e5f1dc4fee7dae5edd586b4feaba/fastokens-0.2.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:f643f4739b20c86ed21e2c46e7fe203e6a621e21124074f138819423882e3aba", size = 3401011, upload-time = "2026-05-17T10:32:50.13Z" },
{ url = "https://files.pythonhosted.org/packages/9b/31/80b74196524d7a9576fa96685a39ee1f333ffd12eb29dbeb5e65c6e3dcb2/fastokens-0.2.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:3cd4effdc6610cbee0be717032652a1997976f1a2f21949435d925c7982cf6f3", size = 3593240, upload-time = "2026-05-17T10:32:52.661Z" },
{ url = "https://files.pythonhosted.org/packages/59/96/12814aa955b7277adb07a8b36176181f247f3b9cf973d05b34294df6a72c/fastokens-0.2.0-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:d29eb1d608977d63fc4679d6ce2b360fdb8b0ea8d66a0eaf804f7ac31ba52a3a", size = 3089011, upload-time = "2026-05-17T10:32:43.16Z" },
{ url = "https://files.pythonhosted.org/packages/c0/05/553b59c6a8542ad7d443306fc1fd7bb012e4aae459ccf9ab422ea4c681b7/fastokens-0.2.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:f8ec7a20322aafe245201727c7a507b87333c51dc580940b9ee5456dbfe3963c", size = 2992964, upload-time = "2026-05-17T10:32:39.992Z" },
{ url = "https://files.pythonhosted.org/packages/13/66/a53c2309003510de7c189ba8a9d2ea5a1833e9b447d9f69b95449c3dfe34/fastokens-0.2.0-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:dc4c0a25726620b1cc4cfb7e9dc1a53b17bbe3f2f9adbaa57b8375b5f36ac5d4", size = 3316289, upload-time = "2026-05-17T10:32:34.557Z" },
{ url = "https://files.pythonhosted.org/packages/b4/54/e0e4318ee1ad0b5196df72cf93615bba0b81f7869d659a44ccc475969151/fastokens-0.2.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:160253f8d30747cf66e7ed895c513e16f7b173dd9e644fa641e2eecbd43a616a", size = 3303534, upload-time = "2026-05-17T10:32:37.462Z" },
{ url = "https://files.pythonhosted.org/packages/64/44/bfff90e4b1a43c17edf7305dafbd56dc992bbe832cc08da78f1f50104c2d/fastokens-0.2.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:b61b9fe5b41e0bb36ad86e7551dc53293c9833909ef07b1cdbaa2055b06c3b3e", size = 3254096, upload-time = "2026-05-17T10:32:28.489Z" },
{ url = "https://files.pythonhosted.org/packages/df/89/bec1a0368100c5f1134ab1ce588d71f88697fadbbad5f26bb130eda00fe8/fastokens-0.2.0-cp39-abi3-manylinux_2_28_armv7l.whl", hash = "sha256:8f138fc64e355589be43068e6996ac0bfcfd872cd75fb5793d11d06cb9c0ac9b", size = 3000177, upload-time = "2026-05-17T10:32:29.745Z" },
{ url = "https://files.pythonhosted.org/packages/f2/fd/cbe8a033e2ef565ce5aef4e02316054b04adad96ee9805cba74a50a84ed9/fastokens-0.2.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:c1a6cd93d16e880d81deb12519cc2eb20149d7423321cf00a34ce25ea9c9ef15", size = 3626561, upload-time = "2026-05-17T10:32:32.087Z" },
{ url = "https://files.pythonhosted.org/packages/05/bf/1cad7f0e8d03f5f5b2b417cda8859e4d968d2eebdca0cd336b23d7dbbdbb/fastokens-0.2.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:01b9bdba818d7b2c67d57d9917faf7a1dad32ece0734440130de94ad768b819f", size = 3336689, upload-time = "2026-05-17T10:32:46.21Z" },
{ url = "https://files.pythonhosted.org/packages/05/56/0030c6e67c60ee88b74336d1bb03eb556b2afa60445268921ad02d9cb3b3/fastokens-0.2.0-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:9aec70b85a06bf2ac95dd76e07e404040dbcfb06eb165f29bc61ef2ab68dc87a", size = 3154666, upload-time = "2026-05-17T10:32:48.835Z" },
{ url = "https://files.pythonhosted.org/packages/c1/5b/02cc5d501ccc2fbd4b068a7aa34a35347bdb3a4189b96af647ef0407af87/fastokens-0.2.0-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:8c41f5278ac53853249c1170d653ee0afaa0906c9bc32c8d25c9443b6d667298", size = 3406657, upload-time = "2026-05-17T10:32:51.392Z" },
{ url = "https://files.pythonhosted.org/packages/97/d7/f5fb2564e16b1f5733e05c41b090f95a3fe767f6b888ba7d864193bc5447/fastokens-0.2.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d068bc50082ad67d5d542847075f1f7b8d10f703274e56e241312f18b4d9e772", size = 3598064, upload-time = "2026-05-17T10:32:54.109Z" },
{ url = "https://files.pythonhosted.org/packages/0a/39/2098de2aa01c3e2ef62b066926d70015f88845e3ac1a976ba1cc3a363c05/fastokens-0.2.0-cp39-abi3-win_amd64.whl", hash = "sha256:5729c44ce1d60cb03e506731dcb17d8c2d69c267098c3ff35ca8be37d618714d", size = 2767905, upload-time = "2026-05-17T10:32:56.759Z" },
]
[[package]]
name = "filelock"
version = "3.29.0"
@@ -374,11 +407,11 @@ wheels = [
[[package]]
name = "idna"
version = "3.13"
version = "3.15"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/ce/cc/762dfb036166873f0059f3b7de4565e1b5bc3d6f28a414c13da27e442f99/idna-3.13.tar.gz", hash = "sha256:585ea8fe5d69b9181ec1afba340451fba6ba764af97026f92a91d4eef164a242", size = 194210, upload-time = "2026-04-22T16:42:42.314Z" }
sdist = { url = "https://files.pythonhosted.org/packages/82/77/7b3966d0b9d1d31a36ddf1746926a11dface89a83409bf1483f0237aa758/idna-3.15.tar.gz", hash = "sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc", size = 199245, upload-time = "2026-05-12T22:45:57.011Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5d/13/ad7d7ca3808a898b4612b6fe93cde56b53f3034dcde235acb1f0e1df24c6/idna-3.13-py3-none-any.whl", hash = "sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3", size = 68629, upload-time = "2026-04-22T16:42:40.909Z" },
{ url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" },
]
[[package]]
@@ -1041,6 +1074,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/80/6e/4b28b62ecb6aae56769c34a8ff1d661473ec1e9519e2d5f8b2c150086b26/pre_commit-4.6.0-py2.py3-none-any.whl", hash = "sha256:e2cf246f7299edcabcf15f9b0571fdce06058527f0a06535068a86d38089f29b", size = 226472, upload-time = "2026-04-21T20:31:40.092Z" },
]
[[package]]
name = "prime-pydantic-config"
version = "0.3.0.dev83"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pydantic" },
]
sdist = { url = "https://files.pythonhosted.org/packages/b3/4e/bcdb244336d3abae60c7767626aaf635ef724bdc3f2cb46e317d11b23d91/prime_pydantic_config-0.3.0.dev83.tar.gz", hash = "sha256:7446e6439ba6de2f2c332acb292ba5b53da7c1a4ad60e4a25b78393b17859fdd", size = 73322, upload-time = "2026-05-24T02:58:49.485Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/1a/6b/372380c6f5cc3a6f0b6690acb453e9aa9d848e8c1ec421e883c1c3c7a293/prime_pydantic_config-0.3.0.dev83-py3-none-any.whl", hash = "sha256:91a8d883181aff069a4a07f56b636c399c32f1814d8177b9e167a8398643e313", size = 26259, upload-time = "2026-05-24T02:58:48.432Z" },
]
[[package]]
name = "pydantic"
version = "2.13.3"
@@ -1335,11 +1380,13 @@ wheels = [
name = "renderers"
source = { editable = "." }
dependencies = [
{ name = "fastokens" },
{ name = "jinja2" },
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
{ name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
{ name = "openai" },
{ name = "openai-harmony" },
{ name = "prime-pydantic-config" },
{ name = "tiktoken" },
{ name = "transformers" },
]
@@ -1358,10 +1405,12 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "fastokens", specifier = ">=0.2.0" },
{ name = "jinja2" },
{ name = "numpy" },
{ name = "openai", specifier = ">=1.108.1" },
{ name = "openai-harmony", specifier = ">=0.0.8" },
{ name = "prime-pydantic-config", specifier = ">=0.3.0.dev83" },
{ name = "tiktoken" },
{ name = "transformers", specifier = ">=4.50.0" },
]