Compare commits

...
Author SHA1 Message Date
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
50 changed files with 6768 additions and 1415 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/
+38 -13
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"}],
@@ -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
)
+23 -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]
@@ -68,6 +80,12 @@ dev = [
[tool.uv]
exclude-newer = "7 days"
# 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.
exclude-newer-package = { fastokens = false, "prime-pydantic-config" = false }
[tool.ty.environment]
python-version = "3.13"
+93 -17
View File
@@ -28,6 +28,7 @@ from renderers.base import (
ToolCallParseStatus,
ToolSpec,
VideoPart,
attribute_text_segments,
build_training_sample,
build_trajectory_step,
create_renderer,
@@ -36,49 +37,122 @@ from renderers.base import (
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,
DeepSeekV3RendererConfig,
GLM45RendererConfig,
GLM51RendererConfig,
GLM5RendererConfig,
GptOssRendererConfig,
KimiK25RendererConfig,
KimiK2RendererConfig,
LagunaXS2RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
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] = {
"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",
"MiniMaxM2Renderer": "renderers.minimax_m2",
"Nemotron3Renderer": "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",
"DeepSeekV3Renderer",
"DeepSeekV3RendererConfig",
"DefaultRenderer",
"DefaultRendererConfig",
"GLM45Renderer",
"GLM45RendererConfig",
"GLM51Renderer",
"GLM51RendererConfig",
"GLM5Renderer",
"GLM5RendererConfig",
"GptOssRenderer",
"GptOssRendererConfig",
"ImagePart",
"KimiK2Renderer",
"KimiK25Renderer",
"KimiK25RendererConfig",
"KimiK2Renderer",
"KimiK2RendererConfig",
"LagunaXS2Renderer",
"LagunaXS2RendererConfig",
"MULTIMODAL_MODELS",
"Message",
"MiniMaxM2Renderer",
"MiniMaxM2RendererConfig",
"MultiModalData",
"MultimodalRenderer",
"Nemotron3Renderer",
"Nemotron3RendererConfig",
"OverlongPromptError",
"ParsedResponse",
"ParsedToolCall",
"PlaceholderRange",
"Qwen3Renderer",
"Qwen3VLRenderer",
"Qwen35Renderer",
"Qwen35RendererConfig",
"Qwen36Renderer",
"Qwen36RendererConfig",
"Qwen3Renderer",
"Qwen3RendererConfig",
"Qwen3VLRenderer",
"Qwen3VLRendererConfig",
"RenderedConversation",
"RenderedTokens",
"Renderer",
"RendererConfig",
"RendererPool",
"TextPart",
"ThinkingPart",
@@ -88,8 +162,10 @@ __all__ = [
"ToolSpec",
"VideoPart",
"__version__",
"attribute_text_segments",
"build_training_sample",
"build_trajectory_step",
"config_from_name",
"create_renderer",
"create_renderer_pool",
"is_multimodal",
+648 -119
View File
@@ -1,12 +1,25 @@
from __future__ import annotations
import contextlib
import enum
import io
import logging
import queue
import threading
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Literal, Protocol, TypedDict, runtime_checkable
from typing import (
TYPE_CHECKING,
Any,
Callable,
Literal,
Protocol,
TypedDict,
runtime_checkable,
)
if TYPE_CHECKING:
from renderers.configs import AutoRendererConfig, RendererConfig
logger = logging.getLogger("renderers.base")
@@ -169,6 +182,32 @@ class RenderedTokens:
masking. ``DefaultRenderer`` leaves it empty because the Jinja
template is opaque; hand-coded renderers populate it.
``is_content`` is a per-token signal generalizing the "scaffold vs
body" distinction across all roles: ``True`` iff the token was
produced from message-body bytes (caller-provided ``content`` /
``tool_calls`` / ``reasoning_content``, or the model's sampled
emission for the assistant role), ``False`` iff it is template
scaffolding the renderer added around message bodies — role-tag
openers, closers when not model-sampled, inter-turn separators,
tool-response wraps, the tools-header block, the generation prompt.
Generalises ``sampled_mask``: where ``sampled_mask`` answers "would
the model emit this?" (useful for assistant tokens; uniformly
``False`` elsewhere), ``is_content`` answers "is this from caller
or model data?" (meaningful on every role). By construction
``is_content[k] == sampled_mask[k]`` over every token attributed to
an assistant message; on other roles ``is_content`` carries new
information that ``sampled_mask`` does not.
The use case: SFT on tool response bodies while applying RL only to
assistant tokens. The trainer wants the model to anticipate tool
outputs but never to emit ``<|tool_response>`` itself (that would
interrupt the rollout), so the SFT loss mask is
``message_role == "tool" AND is_content``.
Empty ``is_content`` (``[]``) — like ``sampled_mask`` — means the
renderer doesn't provide the signal. ``DefaultRenderer`` leaves it
empty for the same reason.
``multi_modal_data`` is populated by multimodal renderers (e.g.
``Qwen3VLRenderer``) when image / video content parts are present;
text-only renderers leave it as ``None``.
@@ -177,8 +216,251 @@ class RenderedTokens:
token_ids: list[int] = field(default_factory=list)
message_indices: list[int] = field(default_factory=list)
sampled_mask: list[bool] = field(default_factory=list)
is_content: list[bool] = field(default_factory=list)
message_roles: list[str] = field(default_factory=list)
multi_modal_data: "MultiModalData | None" = None
def tokens_per_message(
self, n_messages: int | None = None, *, sampled_only: bool = False
) -> list[int]:
"""Count rendered tokens attributed to each caller-relative message.
``out[i]`` is the number of tokens with ``message_indices[k] == i``,
i.e. tokens the renderer attributed to ``messages[i]``. This
includes template scaffolding the renderer wraps around the
message — the ``<|im_start|>role\\n`` opener, the closing
``<|im_end|>\\n``, etc. — because those are the renderer's own
attribution decision and are preserved verbatim here. Tokens with
``message_indices[k] == -1`` (scaffolding outside any single
message, e.g. the trailing generation prompt) are not counted.
With ``sampled_only=True``, counts only tokens the model would
have emitted at inference (``sampled_mask[k] is True``). For
example, length-penalty signals in RL: the template wraps each
assistant turn in scaffolding tokens (e.g. ``<|im_start|>assistant\\n``,
``<|im_end|>\\n``) that are constant-size and not chosen by the
model, so they shouldn't enter the penalty. For roles the model
never samples (``user``, ``tool``, ``system``), the
``sampled_only`` count is zero by construction. Renderers that
don't populate ``sampled_mask`` (``DefaultRenderer`` — the Jinja
template is opaque) return all zeros under ``sampled_only=True``.
``n_messages`` defaults to ``len(self.message_roles)``, which
every Renderer populates with the caller-relative message list
(caller's ``messages`` for ``render()``; ``new_messages`` for
``bridge_to_next_turn()``). Pass it explicitly only to truncate
— indices outside ``[0, n_messages)`` are ignored, so passing a
smaller value won't raise; it just drops the tail. Values larger
than ``len(self.message_roles)`` are clamped, so the returned
list never claims more messages than the renderer attributed.
Works on results from both :meth:`Renderer.render` and
:meth:`Renderer.bridge_to_next_turn`. For a bridge result the
indices are relative to the new messages the bridge added, not
the full conversation history; the prior portion is uniformly
``-1`` (and ``sampled_mask`` uniformly ``False``), so it
contributes nothing to either count.
"""
if n_messages is None:
n_messages = len(self.message_roles)
else:
n_messages = min(n_messages, len(self.message_roles))
out = [0] * n_messages
if sampled_only:
if len(self.sampled_mask) != len(self.token_ids):
return out
for idx, sampled in zip(self.message_indices, self.sampled_mask):
if sampled and 0 <= idx < n_messages:
out[idx] += 1
else:
for idx in self.message_indices:
if 0 <= idx < n_messages:
out[idx] += 1
return out
def message_token_spans(self) -> list[tuple[int, int] | None]:
"""Per-message ``(start, end)`` slices into :attr:`token_ids`.
``out[i]`` is the half-open span ``[start, end)`` such that
``token_ids[start:end]`` are the tokens attributed to
``messages[i]`` (or ``new_messages[i]`` for a bridge result).
Messages that contributed no tokens get ``None``. Renderer
scaffolding outside any message (``message_indices[k] == -1``)
is not represented.
Hand-coded renderers emit each message's tokens contiguously,
so the span is well-defined. The implementation tolerates
non-contiguous attribution by returning the outer span
``(first_k, last_k + 1)``; if you suspect interleaving, slice
``message_indices`` yourself to verify.
Returns ``len(self.message_roles)`` entries when ``message_roles``
is populated. Otherwise infers the count from
``max(message_indices) + 1`` — useful for manually-constructed
``RenderedTokens`` in tests but only correct when the last
message contributed at least one token.
Cheap to call: single pass over ``message_indices``. Re-call
rather than caching the result if you mutate the dataclass.
"""
if self.message_roles:
n_messages = len(self.message_roles)
else:
max_idx = -1
for idx in self.message_indices:
if idx > max_idx:
max_idx = idx
n_messages = max_idx + 1
firsts: list[int] = [-1] * n_messages
lasts: list[int] = [-1] * n_messages
for k, idx in enumerate(self.message_indices):
if 0 <= idx < n_messages:
if firsts[idx] == -1:
firsts[idx] = k
lasts[idx] = k
out: list[tuple[int, int] | None] = []
for i in range(n_messages):
if firsts[i] == -1:
out.append(None)
else:
out.append((firsts[i], lasts[i] + 1))
return out
def role_token_spans(self) -> dict[str, list[tuple[int, int]]]:
""":meth:`message_token_spans` regrouped by ``message_roles``.
Maps each role appearing in :attr:`message_roles` to a list of
``(start, end)`` spans — one per occurrence of that role, in
message order. Messages with no contributed tokens are skipped.
Returns an empty dict if :attr:`message_roles` is empty.
Intended for per-role statistics that operate on per-token
signals — e.g. ``logprobs[start:end]`` for each assistant span
to compute per-turn perplexity, or
``attention[start:end]`` for tool-response attention analysis.
"""
spans = self.message_token_spans()
out: dict[str, list[tuple[int, int]]] = {}
for role, span in zip(self.message_roles, spans):
if span is None:
out.setdefault(role, [])
continue
out.setdefault(role, []).append(span)
return out
def tokens_by_role(self, *, sampled_only: bool = False) -> dict[str, int]:
"""Sum :meth:`tokens_per_message` grouped by ``message_roles``.
Convenience for length-penalty bookkeeping in RL trainers:
``rendered.tokens_by_role(sampled_only=True)["assistant"]`` is
the count of tokens the model actually emitted across all
assistant turns — template scaffolding excluded.
``rendered.tokens_by_role()["tool"]`` is the raw count of
tool-response tokens (``sampled_only`` is zero for ``tool`` by
construction since the model never samples those).
Roles present in :attr:`message_roles` always appear in the
returned dict, even with post-filter count ``0``, so callers
can index directly without ``KeyError`` on conversations that
happen to lack a role. Returns an empty dict if
:attr:`message_roles` is empty.
"""
counts = self.tokens_per_message(sampled_only=sampled_only)
out: dict[str, int] = {}
for role, n in zip(self.message_roles, counts):
out[role] = out.get(role, 0) + n
return out
def content_token_spans_by_role(self) -> dict[str, list[tuple[int, int]]]:
"""Per-role spans of contiguous body-only tokens (``is_content=True``).
Maps each role appearing in :attr:`message_roles` to a list of
half-open ``[start, end)`` slices into :attr:`token_ids` over
which every token satisfies ``is_content=True`` AND belongs to
a message of that role. Spans never cross message boundaries:
a tool message contributes its own runs; an immediately
adjacent assistant message contributes separate runs even when
the bodies abut on the token axis.
Returns an empty dict when :attr:`is_content` or
:attr:`message_roles` is empty (renderer didn't populate the
signal — e.g. ``DefaultRenderer``).
Intended for selective loss masking: SFT on tool response
bodies while RL acts only on assistant turns is the canonical
case::
spans = rendered.content_token_spans_by_role()
tool_sft_mask = [False] * len(rendered.token_ids)
for s, e in spans.get("tool", []):
for k in range(s, e):
tool_sft_mask[k] = True
See also :meth:`content_mask_for_roles` for the same
computation returned as a per-token bool list.
"""
out: dict[str, list[tuple[int, int]]] = {}
if not self.is_content or not self.message_roles:
return out
n = len(self.token_ids)
if len(self.is_content) != n or len(self.message_indices) != n:
return out
msg_spans = self.message_token_spans()
for role, span in zip(self.message_roles, msg_spans):
bucket = out.setdefault(role, [])
if span is None:
continue
start, end = span
run_start: int | None = None
for k in range(start, end):
if self.is_content[k]:
if run_start is None:
run_start = k
else:
if run_start is not None:
bucket.append((run_start, k))
run_start = None
if run_start is not None:
bucket.append((run_start, end))
return out
def content_mask_for_roles(self, roles: "set[str] | frozenset[str]") -> list[bool]:
"""Per-token bool list: ``True`` iff the token is body of a
message whose role is in ``roles``.
Length matches :attr:`token_ids`. Returns an all-``False``
list of that length when :attr:`is_content` or
:attr:`message_roles` is empty — consumers can AND this with
their own attribution masks without length checks.
``role_to_mask`` style helpers in :func:`build_training_sample`
cover the trainable-role question; this one covers the
complementary "body-only" question. The two compose: SFT mask
on tool body is
``rendered.content_mask_for_roles({"tool"})``; RL mask on
assistant tokens stays
``[s and (mi >= 0 and rendered.message_roles[mi] == "assistant")
for s, mi in zip(rendered.sampled_mask, rendered.message_indices)]``.
"""
n = len(self.token_ids)
mask = [False] * n
if not self.is_content or not self.message_roles:
return mask
if len(self.is_content) != n or len(self.message_indices) != n:
return mask
for k, msg_idx in enumerate(self.message_indices):
if msg_idx < 0:
continue
if msg_idx >= len(self.message_roles):
continue
if self.message_roles[msg_idx] in roles and self.is_content[k]:
mask[k] = True
return mask
class ToolCallParseStatus(str, enum.Enum):
"""Per-attempt outcome of parsing a single ``<tool_call>`` block.
@@ -358,6 +640,34 @@ class Renderer(Protocol):
list so far with ``add_generation_prompt=True`` — except prev
sampled tokens are kept verbatim rather than re-rendered).
Attribution on the returned ``RenderedTokens``:
- ``message_indices`` is ``-1`` over the entire prior portion
(length ``len(previous_ids)`` after :func:`trim_to_turn_close`)
because the bridge gets the prior as raw token lists with no
attribution. Over the bridge-added portion, indices are
relative to ``new_messages``: a token rendered as part of
``new_messages[i]`` carries ``i``, and inter-turn separators /
the trailing generation prompt carry ``-1``. So
``bridge.tokens_per_message(len(new_messages))`` gives the
per-new-message token count for length-penalty bookkeeping.
- ``sampled_mask`` is uniformly ``False`` across the entire
returned sequence. The bridge output is consumed as the next
turn's prompt; nothing it emits was model-sampled, and the
bridge has no way to recover which prior tokens were. If the
caller needs that distinction for the prior portion, they
have it directly: every token in ``prev_completion_ids`` was
sampled; every token in ``prev_prompt_ids`` was not.
- ``is_content`` mirrors ``sampled_mask``'s scheme for the
prior portion (uniformly ``False`` — body-vs-wrap
attribution can't be recovered from raw token ids), and on
the bridge-added portion the renderer populates it the same
way as in :meth:`render`: ``True`` over the body bytes of
each new message, ``False`` over the surrounding scaffold.
Consumers walk the trajectory and read each step's own
``is_content`` for full-conversation body masks; the bridge
output covers only the *new* tokens this turn adds.
Text-only renderers return :class:`RenderedTokens` with
``multi_modal_data=None``. Multimodal renderers (see
:class:`MultimodalRenderer`) populate ``multi_modal_data`` so
@@ -593,6 +903,8 @@ MODEL_RENDERER_MAP: dict[str, str] = {
"Qwen/Qwen3-14B": "qwen3",
"Qwen/Qwen3-32B": "qwen3",
"Qwen/Qwen3-30B-A3B": "qwen3",
"Qwen/Qwen3-30B-A3B-Instruct-2507": "qwen3",
"Qwen/Qwen3-30B-A3B-Thinking-2507": "qwen3",
"Qwen/Qwen3-235B-A22B": "qwen3",
# Qwen3.5. All seven sizes share the same renderer. The 4B / 9B /
# 35B-A3B / 122B-A10B / 397B-A17B chat template defaults
@@ -619,6 +931,7 @@ MODEL_RENDERER_MAP: dict[str, str] = {
"Qwen/Qwen3-VL-30B-A3B-Instruct": "qwen3-vl",
# GLM-5 family (GLM-4.7 reuses the GLM-5 template).
"zai-org/GLM-5": "glm-5",
"zai-org/GLM-5-FP8": "glm-5",
"zai-org/GLM-4.7-Flash": "glm-5",
"zai-org/GLM-5.1": "glm-5.1",
# GLM-4.5.
@@ -735,31 +1048,24 @@ TRUSTED_REVISIONS: dict[str, str] = {
# Models for which ``fastokens`` is known to diverge from vanilla
# ``transformers.AutoTokenizer`` and therefore must NOT be patched.
# Empirical audit ran each entry of ``MODEL_RENDERER_MAP`` through both
# backends; 31/35 passed byte-identical. The four below either fail to
# load under fastokens (DeepSeek-V3 family — Metaspace pretokenizer not
# yet implemented) or are kept defensively pending an upstream fastokens
# fix (MiniMax-M2 family — see per-entry comments).
# backends. The entries below fail to load under fastokens (DeepSeek-V3
# family — Metaspace pretokenizer not yet implemented).
FASTOKENS_INCOMPATIBLE: frozenset[str] = frozenset(
{
# fastokens 0.1.1: ``ValueError: pre-tokenizer error: unsupported
# fastokens: ``ValueError: pre-tokenizer error: unsupported
# pre-tokenizer type: Metaspace`` — DeepSeek's tokenizer uses
# SentencePiece-style Metaspace pretokenization which fastokens
# doesn't yet implement.
"deepseek-ai/DeepSeek-V3",
"deepseek-ai/DeepSeek-V3-Base",
# MiniMax: kept defensive pending upstream fastokens fix
# https://github.com/crusoecloud/fastokens/pull/32 — that PR
# removes a stray attribute leaked by ``unpatch_transformers``
# which steers MiniMax (declared ``tokenizer_class =
# 'GPT2Tokenizer'`` → slow→fast conversion path) down a different
# load path on subsequent vanilla loads. Once the upstream fix
# is released, these two entries can be dropped after re-audit.
"MiniMaxAI/MiniMax-M2",
"MiniMaxAI/MiniMax-M2.5",
}
)
_FASTOKENS_PATCH_LOCK = threading.Lock()
_FASTOKENS_ANNOUNCED = False
def _patched_load(model_name_or_path: str, **kwargs):
"""Run ``AutoTokenizer.from_pretrained`` with fastokens patched in
process-locally — patch around the load, unpatch right after.
@@ -769,15 +1075,38 @@ def _patched_load(model_name_or_path: str, **kwargs):
fastokens for ``encode``/``decode`` while subsequent
``AutoTokenizer.from_pretrained`` calls (outside our control) go
back to vanilla. This keeps the global side effect minimal.
fastokens itself prints ``[fastokens] patch_transformers: ...`` to
stdout on every patch/unpatch call. Building a pool of size N would
therefore emit ~N lines (more under thread contention, where some
threads see ``already patched``). We swallow those prints under a
lock — ``contextlib.redirect_stdout`` swaps ``sys.stdout``
process-wide, so the lock keeps unrelated stdout writes from other
threads from disappearing into our buffer. The patch/unpatch calls
are cheap; only the brief patch+unpatch is serialized, the actual
``from_pretrained`` still runs concurrently across pool slots. A
single ``logger.info`` is emitted on the first patch so the fast
path is still discoverable in logs.
"""
import fastokens
from transformers import AutoTokenizer
fastokens.patch_transformers()
global _FASTOKENS_ANNOUNCED
with _FASTOKENS_PATCH_LOCK:
with contextlib.redirect_stdout(io.StringIO()):
fastokens.patch_transformers()
if not _FASTOKENS_ANNOUNCED:
logger.info(
"fastokens enabled — tokenizers load through the Rust BPE fast path (~10x encode speedup)."
)
_FASTOKENS_ANNOUNCED = True
try:
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
finally:
fastokens.unpatch_transformers()
with _FASTOKENS_PATCH_LOCK:
with contextlib.redirect_stdout(io.StringIO()):
fastokens.unpatch_transformers()
def load_tokenizer(
@@ -799,10 +1128,10 @@ def load_tokenizer(
immediately after, so global ``AutoTokenizer.from_pretrained`` calls
elsewhere in the user's process are not affected.
Models in ``FASTOKENS_INCOMPATIBLE`` (DeepSeek-V3 family, MiniMax-M2
family) skip the patch — fastokens 0.1.1 either fails to load them
or produces token-divergent output. Pass ``use_fastokens=False`` to
force the vanilla backend for any other model.
Models in ``FASTOKENS_INCOMPATIBLE`` (DeepSeek-V3 family) skip the
patch — fastokens currently fails to load them. Pass
``use_fastokens=False`` to force the vanilla backend for any other
model.
Unknown / fine-tuned model paths fall through to
``trust_remote_code=False`` and the patched-load fast path. If
@@ -839,8 +1168,8 @@ def load_tokenizer(
def _populate_registry():
if RENDERER_REGISTRY:
return
from renderers.default import DefaultRenderer
from renderers.deepseek_v3 import DeepSeekV3Renderer
from renderers.default import DefaultRenderer
from renderers.glm5 import GLM5Renderer, GLM51Renderer
from renderers.glm45 import GLM45Renderer
from renderers.gpt_oss import GptOssRenderer
@@ -877,27 +1206,22 @@ def _populate_registry():
def create_renderer_pool(
tokenizer_name_or_path: str,
renderer: str = "auto",
size: int = 16,
config: RendererConfig | None = None,
*,
tool_parser: str | None = None,
reasoning_parser: str | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
size: int = 16,
) -> RendererPool:
"""Create a RendererPool with *size* independent tokenizer copies.
Each slot loads its own tokenizer so threads never share mutable state.
HuggingFace fast tokenizers release the GIL during Rust encoding, so
threads achieve real parallelism.
Each slot loads its own tokenizer so threads never share mutable
state. HuggingFace fast tokenizers release the GIL during Rust
encoding, so threads achieve real parallelism.
``tool_parser`` and ``reasoning_parser`` are forwarded to
``create_renderer`` when the pool falls back to ``DefaultRenderer``.
``preserve_all_thinking`` and ``preserve_thinking_between_tool_calls``
are forwarded to each pooled renderer's constructor — every slot in
the pool shares one configuration. To run with a different
configuration, build a different pool.
``config`` is the typed renderer config (one of the variants of
:data:`renderers.RendererConfig`). Defaults to
:class:`AutoRendererConfig`, which resolves to a concrete renderer
via ``MODEL_RENDERER_MAP`` at construction time using the loaded
tokenizer's name. Every slot in the pool shares the same config; to
run a different config, build a different pool.
Tokenizers load via ``load_tokenizer`` — see its docstring for the
``trust_remote_code`` policy (default off; Moonshot Kimi-K2 family
@@ -906,92 +1230,75 @@ def create_renderer_pool(
def factory() -> Renderer:
tokenizer = load_tokenizer(tokenizer_name_or_path)
return create_renderer(
tokenizer,
renderer=renderer,
tool_parser=tool_parser,
reasoning_parser=reasoning_parser,
preserve_all_thinking=preserve_all_thinking,
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
)
return create_renderer(tokenizer, config)
return RendererPool(factory, size=size)
def create_renderer(
tokenizer,
renderer: str = "auto",
*,
tool_parser: str | None = None,
reasoning_parser: str | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: RendererConfig | None = None,
) -> Renderer:
"""Create a Renderer by name, or auto-detect from the tokenizer's model name.
"""Create a Renderer from a typed config.
Args:
tokenizer: HuggingFace tokenizer instance.
renderer: Renderer name ('qwen3', 'qwen3-vl', 'qwen3.5', 'qwen3.6',
'glm-5', 'glm-5.1', 'glm-4.5', 'minimax-m2', 'deepseek-v3',
'kimi-k2', 'kimi-k2.5', 'laguna-xs.2', 'nemotron-3',
'gpt-oss', 'default') or 'auto' to detect from model name.
tool_parser: Name of a tool parser registered in ``renderers.parsers``.
Only consumed by DefaultRenderer. Model-specific renderers
have their own parsing wired in.
reasoning_parser: Name of a reasoning parser registered in
``renderers.parsers``. Only consumed by DefaultRenderer.
preserve_all_thinking: Forwarded to the renderer's constructor.
When ``True``, the instance restores ``reasoning_content``
the chat template would otherwise drop on historical
assistants — useful when a downstream pass (e.g.
compaction prompts the model with a fresh ``user`` turn
asking for a summary) would lose the trajectory's
reasoning. See ``Renderer.render`` and
``should_preserve_past_thinking``.
preserve_thinking_between_tool_calls: Forwarded to the renderer's
constructor. ``True`` keeps reasoning on in-flight
tool-cycle assistants when the template would drop them.
See ``Renderer.render`` for semantics.
config: Typed renderer config — one of the variants of
:data:`renderers.RendererConfig`. ``None`` defaults to
:class:`AutoRendererConfig`, which resolves to a concrete
renderer using ``tokenizer.name_or_path`` against
``MODEL_RENDERER_MAP``. To enable structured-output parsing
on the default renderer, pass :class:`DefaultRendererConfig`
with ``tool_parser`` / ``reasoning_parser`` set. To override
template-control kwargs (e.g. ``enable_thinking``), pass
the specific :class:`Qwen3RendererConfig`,
:class:`GLM5RendererConfig` etc. and set those fields.
Selecting the auto-renderer for a model without a registered
renderer falls back to :class:`DefaultRenderer` for text-only models
and raises for VLMs (where ``apply_chat_template`` would silently
drop images).
"""
from renderers.configs import AutoRendererConfig
_populate_registry()
default_kwargs: dict = {}
if tool_parser is not None:
default_kwargs["tool_parser"] = tool_parser
if reasoning_parser is not None:
default_kwargs["reasoning_parser"] = reasoning_parser
if config is None:
config = AutoRendererConfig()
preserve_kwargs: dict = {
"preserve_all_thinking": preserve_all_thinking,
"preserve_thinking_between_tool_calls": preserve_thinking_between_tool_calls,
}
if renderer != "auto":
cls = RENDERER_REGISTRY.get(renderer)
if not isinstance(config, AutoRendererConfig):
cls = RENDERER_REGISTRY.get(config.name)
if cls is None:
raise ValueError(
f"Unknown renderer {renderer!r}. Available: {', '.join(sorted(RENDERER_REGISTRY))}"
f"Unknown renderer {config.name!r}. Available: {', '.join(sorted(RENDERER_REGISTRY))}"
)
if renderer == "default":
return cls(tokenizer, **default_kwargs, **preserve_kwargs)
if default_kwargs:
logger.info(
"tool_parser / reasoning_parser are only consumed by "
"DefaultRenderer; ignoring for renderer=%r which has "
"built-in behavior.",
renderer,
)
return cls(tokenizer, **preserve_kwargs)
return cls(tokenizer, config)
return _resolve_auto(tokenizer, config)
def _resolve_auto(tokenizer, auto: AutoRendererConfig) -> Renderer:
"""Map ``AutoRendererConfig`` → concrete typed config via the
tokenizer's ``name_or_path``, then instantiate the matching renderer.
Fine-tunes and renamed checkpoints miss on purpose — their chat
template may differ from the original even when the architecture
matches, so silently mapping them would produce template-parity
bugs. Set ``config=<typed renderer config>`` explicitly for those.
"""
from renderers.configs import DefaultRendererConfig, _config_class_for
# Auto-detect from model name via exact match on the canonical HF id.
# Fine-tunes and renamed checkpoints miss on purpose — their chat
# template may differ from the original even when the architecture
# matches, so silently mapping them would produce template-parity
# bugs. Set ``renderer=<name>`` explicitly for those.
model_name = getattr(tokenizer, "name_or_path", "")
renderer_name = MODEL_RENDERER_MAP.get(model_name)
preserve_carry = {
"preserve_all_thinking": auto.preserve_all_thinking,
"preserve_thinking_between_tool_calls": auto.preserve_thinking_between_tool_calls,
}
if renderer_name is not None:
return RENDERER_REGISTRY[renderer_name](tokenizer, **preserve_kwargs)
cfg_cls = _config_class_for(renderer_name)
return RENDERER_REGISTRY[renderer_name](tokenizer, cfg_cls(**preserve_carry))
# No match. For VLMs this must be fatal: DefaultRenderer only knows
# ``apply_chat_template`` + text tokens, so it would silently drop
@@ -1005,20 +1312,26 @@ def create_renderer(
f"No multimodal renderer registered for {model_name!r}, and "
f"DefaultRenderer would silently drop images. Register a "
f"renderer in MODEL_RENDERER_MAP (currently supported VLMs: "
f"{supported_vlms}), or pass ``renderer='<name>'`` explicitly "
f"if you know what you're doing."
f"{supported_vlms}), or pass an explicit typed renderer "
f"config if you know what you're doing."
)
# Text-only fall back to default (apply_chat_template). For fine-tunes
# with customized chat templates this is the *correct* choice, so we don't
# warn. Note the pick at INFO and advertise the parser knobs.
# with customized chat templates this is the *correct* choice, so we
# don't warn. Note the pick at INFO and advertise the parser knobs.
if auto.preserve_all_thinking or auto.preserve_thinking_between_tool_calls:
raise NotImplementedError(
"Auto-resolved DefaultRenderer can't selectively re-emit "
"dropped reasoning_content. Pass an explicit typed renderer "
"config (model-specific) if you need preserve_*_thinking."
)
logger.info(
"No model-specific renderer matched %r. Using DefaultRenderer "
"(apply_chat_template). Pass tool_parser=<name> or "
"reasoning_parser=<name> to enable structured output parsing.",
"(apply_chat_template). Pass DefaultRendererConfig(tool_parser=..., "
"reasoning_parser=...) to enable structured output parsing.",
model_name or "<unnamed tokenizer>",
)
return RENDERER_REGISTRY["default"](tokenizer, **default_kwargs, **preserve_kwargs)
return RENDERER_REGISTRY["default"](tokenizer, DefaultRendererConfig())
# ---------------------------------------------------------------------------
@@ -1030,34 +1343,99 @@ def build_training_sample(
renderer: Renderer,
messages: list[Message],
*,
role_to_mask: Callable[[Message], bool],
role_to_mask: Callable[[Message], bool] | None = None,
tools: list[ToolSpec] | None = None,
content_sft_roles: "set[str] | frozenset[str] | None" = None,
) -> tuple[list[int], list[bool]]:
"""Build (token_ids, loss_mask) for supervised training.
Single render() call + message_indices → per-token mask.
Replaces build_incremental_token_mask (O(N) renders → O(1)).
When the renderer populates ``rendered.sampled_mask``, the loss mask
is the AND of role-based attribution and the sampled signal: only
tokens the model would have produced at inference are trainable.
This keeps SFT byte-aligned with the RL trajectory mask (where the
prompt / completion split achieves the same effect structurally).
When ``role_to_mask`` is omitted, ``loss_mask`` is the renderer's
``sampled_mask`` directly: every token the model would have
produced at inference is trainable, regardless of which message
it's attributed to. This is the recommended default for renderer
callers — the renderer owns the per-token "is this model output"
signal, so role-level filtering becomes a downstream constraint
rather than a precondition. (Some role markers — e.g. GLM
``<|user|>`` / ``<|observation|>`` after a tool-calling assistant
turn — *are* sampled by the model at inference and live inside the
next message's span; ``sampled_mask`` captures that, but a
naive role filter would mask them out.)
When ``role_to_mask`` is provided, ``loss_mask`` is the AND of the
role-based attribution and the sampled signal: only tokens the
model would have produced at inference AND attributed to a
trainable role pass through. Useful when the caller needs to
restrict training to a specific role (e.g. assistant-only) even on
a renderer whose ``sampled_mask`` already covers other roles.
Renderers that don't populate ``sampled_mask`` (empty list) fall
back to attribution-only masking — every token attributed to a
trainable role is trained on, including template-injected
``<|im_start|>role\\n`` openers.
``<|im_start|>role\\n`` openers. In this fallback mode
``role_to_mask`` is required; calling without it raises
``ValueError``.
``content_sft_roles`` opts in additional roles for "body-only"
supervision: for every message whose role is in this set, tokens
with ``is_content=True`` are marked trainable even though the
``sampled_mask`` gate excludes them (the model never samples
tool / user / system tokens). Template scaffolding around those
messages — ``<|im_start|>role\\n`` openers, ``<|im_end|>``
closers, ``<|tool_response>`` wraps, inter-turn ``\\n`` — stays
masked out, so the model learns to anticipate the body text
without producing the surrounding special tokens (which would
interrupt a real rollout). The canonical use case is RL on
assistant tokens (``role_to_mask=lambda m: m["role"] ==
"assistant"``) plus SFT on tool response bodies
(``content_sft_roles={"tool"}``).
Requires the renderer to populate ``is_content`` for the body-only
path to fire. Renderers that leave it empty (``DefaultRenderer``,
or hand-coded renderers that haven't been wired up yet) ignore
``content_sft_roles`` silently — falling back to the original
``role_to_mask`` + ``sampled_mask`` behaviour.
"""
rendered = renderer.render(messages, tools=tools)
has_sampled_info = len(rendered.sampled_mask) == len(rendered.token_ids)
has_content_info = len(rendered.is_content) == len(rendered.token_ids)
body_roles: "frozenset[str]"
if content_sft_roles and has_content_info:
body_roles = frozenset(content_sft_roles)
else:
body_roles = frozenset()
if role_to_mask is None and not has_sampled_info:
raise ValueError(
"role_to_mask is required when the renderer does not populate "
"sampled_mask. Pass an explicit role filter (e.g. "
"lambda m: m['role'] == 'assistant') for this renderer."
)
loss_mask: list[bool] = []
for k, msg_idx in enumerate(rendered.message_indices):
if msg_idx < 0:
loss_mask.append(False)
elif has_sampled_info and not rendered.sampled_mask[k]:
continue
msg = messages[msg_idx]
# Body-only path for opt-in roles. Fires only on tokens whose
# is_content bit is set; never adds the scaffolding around the
# message, so the model isn't supervised on emitting the role
# tags / wraps that would derail a rollout.
if body_roles and msg.get("role") in body_roles:
loss_mask.append(rendered.is_content[k])
continue
if has_sampled_info and not rendered.sampled_mask[k]:
loss_mask.append(False)
elif role_to_mask is None:
# sampled_mask alone gates the loss when no role filter is
# supplied. ``sampled_mask[k]`` is True here (handled by the
# branch above), so this token is trainable.
loss_mask.append(True)
else:
loss_mask.append(role_to_mask(messages[msg_idx]))
loss_mask.append(role_to_mask(msg))
return rendered.token_ids, loss_mask
@@ -1104,6 +1482,157 @@ def trim_to_turn_close(
return previous_ids
# Per-model offset-aware tokenizer cache. ``attribute_text_segments``
# uses the fast HuggingFace tokenizer's ``offset_mapping`` to attribute
# each token to its source text segment under one BPE pass. Fastokens
# (the Rust BPE we patch in by default for ~10x faster encode) does not
# track character offsets — the patched tokenizer's
# ``return_offsets_mapping=True`` raises ``NotImplementedError``. So we
# keep a parallel vanilla tokenizer per model purely for offset queries.
# Memory cost is one extra tokenizer per *unique* model name across all
# pools / renderers (the cache is process-global), independent of pool
# size.
_offset_tokenizers: dict[str, Any] = {}
_offset_tokenizers_lock = threading.Lock()
def _get_offset_tokenizer(tokenizer):
"""Return a tokenizer that supports ``return_offsets_mapping=True``.
If ``tokenizer`` itself supports offsets, returns it unchanged.
Otherwise loads a vanilla (non-fastokens) tokenizer from
``tokenizer.name_or_path`` and caches it. Raises if the tokenizer
has no usable ``name_or_path`` — hand-coded renderers always pass
a tokenizer loaded via ``load_tokenizer`` which does set it.
"""
# Cheap probe: does this tokenizer already provide offsets?
try:
tokenizer("a", add_special_tokens=False, return_offsets_mapping=True)
return tokenizer
except (NotImplementedError, ValueError, TypeError):
pass
name_or_path = getattr(tokenizer, "name_or_path", "")
if not name_or_path:
raise RuntimeError(
"Cannot construct an offset-aware tokenizer: the supplied "
"tokenizer has no ``name_or_path`` to fall back on. Pass a "
"tokenizer loaded via ``renderers.base.load_tokenizer``."
)
with _offset_tokenizers_lock:
cached = _offset_tokenizers.get(name_or_path)
if cached is not None:
return cached
from transformers import AutoTokenizer
kwargs: dict[str, Any] = {}
revision = TRUSTED_REVISIONS.get(name_or_path)
if revision is not None:
kwargs = {"trust_remote_code": True, "revision": revision}
else:
kwargs = {"trust_remote_code": False}
# Explicitly vanilla — we want HF's Rust tokenizer with offset
# tracking, not the fastokens shim. ``load_tokenizer`` would
# patch fastokens in by default; calling
# ``AutoTokenizer.from_pretrained`` directly here keeps the
# fastokens patch out of this code path entirely.
offset_tok = AutoTokenizer.from_pretrained(name_or_path, **kwargs)
if not getattr(offset_tok, "is_fast", False):
raise RuntimeError(
f"Vanilla tokenizer for {name_or_path!r} is not a fast "
"tokenizer; offset_mapping is unavailable. Hand-coded "
"renderers require a fast tokenizer for body/scaffold "
"attribution."
)
_offset_tokenizers[name_or_path] = offset_tok
return offset_tok
def attribute_text_segments(
tokenizer,
segments: "list[tuple[str, bool]]",
) -> "list[tuple[int, bool]]":
"""Tokenize concatenated segments as a single BPE pass and return
``(token_id, is_content)`` pairs.
``segments`` is a list of ``(text, is_content)`` chunks the renderer
wants to emit contiguously — for example ``[("user\\n", False),
(content, True)]`` for a user message. Concatenation is done before
encoding to preserve BPE merges across the wrap/body boundary; the
resulting tokens are then attributed back to their source segment
via the fast tokenizer's ``offset_mapping``.
A token is attributed to the segment containing its first source
character (``offset_mapping[k][0]``). Tokens whose first character
falls exactly on a segment boundary are attributed to the segment
that *starts* at that offset (the "later" segment). Zero-length
tokens (rare; usually pre-tokenizer artefacts) are attributed to
the most recently entered segment.
Requires a HuggingFace fast tokenizer with offset tracking. The
``fastokens`` patch ``load_tokenizer`` applies by default does
**not** track offsets — when that's the case we transparently load
a vanilla offset-capable tokenizer for the same model and cache it
(see :func:`_get_offset_tokenizer`). Hand-coded renderers are only
registered for model families that ship a fast tokenizer, so a
silent slow-tokenizer fallback isn't supported — BPE drift at the
wrap/body boundary would defeat the whole point.
Empty input or empty joined text returns an empty list.
"""
if not segments:
return []
full_text = "".join(text for text, _ in segments)
if not full_text:
return []
offset_tokenizer = _get_offset_tokenizer(tokenizer)
encoding = offset_tokenizer(
full_text,
add_special_tokens=False,
return_offsets_mapping=True,
)
token_ids = list(encoding["input_ids"])
offsets = list(encoding["offset_mapping"])
# Build segment char-span lookup. Track the half-open span
# [seg_start, seg_end) of each segment and its is_content bit.
spans: list[tuple[int, int, bool]] = []
pos = 0
for text, is_content in segments:
spans.append((pos, pos + len(text), is_content))
pos += len(text)
total_len = pos
out: list[tuple[int, bool]] = []
last_is_content = spans[-1][2] if spans else False
for tok_id, (start, _end) in zip(token_ids, offsets):
if start >= total_len:
# Token's character offset is past every segment (shouldn't
# normally happen for add_special_tokens=False, but defensive
# against tokenizer-specific edge cases).
out.append((tok_id, last_is_content))
continue
# Find the segment that contains `start`. Segments are
# contiguous and ordered, so a linear scan is fine — the inner
# loop runs at most len(segments) times per token and segments
# is typically 2-3 in practice.
is_content = last_is_content
for seg_start, seg_end, seg_is_content in spans:
if seg_start <= start < seg_end:
is_content = seg_is_content
break
else:
# start == total_len handled above; the remaining case is
# an empty segment in the middle. Empty segments emit no
# characters, so no token can land in them; fall through to
# the last non-empty segment's bit.
pass
out.append((tok_id, is_content))
return out
def reject_assistant_in_extension(new_messages: list[Message]) -> bool:
"""Return True if any message in ``new_messages`` is an assistant turn.
+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,
)
+468
View File
@@ -0,0 +1,468 @@
"""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 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 renderer config."""
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."""
class DeepSeekV3RendererConfig(BaseRendererConfig):
"""DeepSeek V3 renderer config.
``enable_thinking`` is renderer-internal here — DeepSeek-V3's chat
template does not reference any thinking variable, so passing it to
``apply_chat_template`` upstream is a no-op. The renderer uses it
to control the ``<think>`` prefill at the generation prompt (R1
distill convention).
"""
name: Literal["deepseek-v3"] = "deepseek-v3"
enable_thinking: bool = True
"""Renderer convention for the R1-distill family: when ``True``,
prefill ``<think>`` at the generation prompt. The DeepSeek-V3 Jinja
template ignores this kwarg upstream; it's not a chat-template
kwarg in the strict sense."""
_internal_fields = frozenset({"enable_thinking"})
RendererConfig = Annotated[
Union[
AutoRendererConfig,
DefaultRendererConfig,
Qwen3RendererConfig,
Qwen35RendererConfig,
Qwen36RendererConfig,
Qwen3VLRendererConfig,
GLM5RendererConfig,
GLM51RendererConfig,
GLM45RendererConfig,
GptOssRendererConfig,
KimiK2RendererConfig,
KimiK25RendererConfig,
LagunaXS2RendererConfig,
MiniMaxM2RendererConfig,
Nemotron3RendererConfig,
DeepSeekV3RendererConfig,
],
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,
"minimax-m2": MiniMaxM2RendererConfig,
"nemotron-3": Nemotron3RendererConfig,
"deepseek-v3": DeepSeekV3RendererConfig,
}
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",
"DeepSeekV3RendererConfig",
"GLM45RendererConfig",
"GLM51RendererConfig",
"GLM5RendererConfig",
"GptOssRendererConfig",
"KimiK25RendererConfig",
"KimiK2RendererConfig",
"LagunaXS2RendererConfig",
"MiniMaxM2RendererConfig",
"Nemotron3RendererConfig",
"Qwen35RendererConfig",
"Qwen36RendererConfig",
"Qwen3RendererConfig",
"Qwen3VLRendererConfig",
"RendererConfig",
"config_from_name",
]
+146 -59
View File
@@ -21,9 +21,11 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
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 +40,25 @@ 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's chat template does not consult any thinking-related
variable; the ``enable_thinking`` field on the typed config controls
the renderer's ``<think>\\n`` prefill at the generation prompt
(R1-distill convention) and is intentionally not forwarded to
``apply_chat_template`` upstream — that would be a no-op. The
template also always emits ``<think>{reasoning}</think>`` when
``reasoning_content`` is provided, so ``preserve_*`` flags are
no-ops here too; stored for protocol uniformity.
"""
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 DeepSeekV3RendererConfig()
# ── BOS / EOS ────────────────────────────────────────────────
self._bos = self._get_special_token(f"begin{_US}of{_US}sentence")
@@ -114,22 +116,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 +178,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 +194,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 +208,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 +218,7 @@ class DeepSeekV3Renderer:
messages,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
@@ -198,6 +227,7 @@ class DeepSeekV3Renderer:
i,
emit_special=emit_special,
emit_text=emit_text,
emit_text_segments=emit_text_segments,
)
# ── 4. Generation prompt ──────────────────────────────────────
@@ -205,12 +235,18 @@ 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.config.enable_thinking:
emit_text("<think>\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],
)
def render_ids(
@@ -271,22 +307,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 +353,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 +367,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,10 +380,17 @@ 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:
if self.config.enable_thinking:
emit_text("<think>\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],
)
# ------------------------------------------------------------------
# Assistant rendering
@@ -343,6 +404,7 @@ 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
@@ -375,18 +437,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 +465,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 +499,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 +516,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
)
+19 -21
View File
@@ -19,9 +19,8 @@ from renderers.base import (
RenderedTokens,
ToolSpec,
)
from renderers.configs import DefaultRendererConfig
from renderers.parsers import (
ReasoningParser,
ToolParser,
get_reasoning_parser,
get_tool_parser,
)
@@ -82,36 +81,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 +136,15 @@ 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,
)
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:
+240 -77
View File
@@ -20,9 +20,11 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
reject_assistant_in_extension,
should_preserve_past_thinking,
)
from renderers.configs import GLM45RendererConfig
from renderers.parsing import parse_glm
_TOOLS_HEADER = (
@@ -52,17 +54,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 +123,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 +184,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 +238,33 @@ 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],
)
def render_ids(
@@ -271,54 +332,120 @@ 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],
)
def _render_assistant(
self,
@@ -330,6 +457,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 +485,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 +517,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 +529,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 +565,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,
)
+241 -73
View File
@@ -21,9 +21,11 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
reject_assistant_in_extension,
should_preserve_past_thinking,
)
from renderers.configs import GLM5RendererConfig, GLM51RendererConfig
from renderers.parsing import parse_glm
_TOOLS_HEADER = (
@@ -53,20 +55,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 +143,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 +207,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 +251,36 @@ 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],
)
def render_ids(
@@ -292,23 +352,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 +425,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 +437,26 @@ 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],
)
def _render_assistant(
self,
@@ -352,6 +468,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 +487,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 +513,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 +566,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 +600,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 +645,7 @@ class GLM51Renderer(GLM5Renderer):
"""
empty_think_on_last_assistant = True
_config_cls = GLM51RendererConfig
@staticmethod
def _format_tool_spec(tool: ToolSpec) -> str:
+230 -51
View File
@@ -60,6 +60,7 @@ from renderers.base import (
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import GptOssRendererConfig
from renderers.parsing import parse_gpt_oss
@@ -121,44 +122,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 +168,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 +267,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 +297,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 +357,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 +396,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 +424,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 +453,18 @@ 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],
)
def render_ids(
@@ -400,22 +531,70 @@ 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 conversion ───────────────────────────────────────────────────
+199 -88
View File
@@ -26,31 +26,29 @@ from renderers.base import (
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 +116,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 +169,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 +223,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 +276,35 @@ 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],
)
def render_ids(
@@ -331,21 +365,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 +420,41 @@ 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],
)
def _render_assistant(
self,
@@ -404,23 +470,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 +509,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 +552,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)
+230 -92
View File
@@ -40,6 +40,7 @@ from renderers.base import (
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import KimiK25RendererConfig
from renderers.parsing import parse_kimi_k2_section
from renderers.qwen3_vl import (
_image_hash,
@@ -213,7 +214,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 +286,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 (
@@ -564,8 +563,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 +579,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 +626,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 +677,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 +745,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 +795,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 +840,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 +860,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 +875,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 +888,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 +905,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 +915,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 +944,8 @@ 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],
multi_modal_data=mm_data,
)
@@ -995,44 +1035,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 +1150,7 @@ class KimiK25Renderer:
emit_ids,
emit_image=emit_image,
is_sampled=False,
is_content=True,
)
emit_special(self._im_end, i)
@@ -1085,7 +1159,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 +1187,15 @@ 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]
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,
)
mm_data = MultiModalData(
mm_hashes=merged_hashes,
@@ -1123,7 +1204,10 @@ 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,
multi_modal_data=mm_data,
)
@@ -1141,6 +1225,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 +1240,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 +1261,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 +1347,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 +1381,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 +1432,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 +1452,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]:
+226 -68
View File
@@ -35,8 +35,10 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
reject_assistant_in_extension,
)
from renderers.configs import LagunaXS2RendererConfig
from renderers.parsing import parse_laguna_xs2
_DEFAULT_SYSTEM_MESSAGE = (
@@ -78,20 +80,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 +146,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 +198,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 +231,50 @@ 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],
)
def render_ids(
@@ -302,42 +339,94 @@ 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],
)
def _render_assistant(
self,
@@ -347,7 +436,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 +462,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 +498,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 +508,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)
+255 -80
View File
@@ -21,16 +21,14 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
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 +56,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 +110,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 +180,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 +226,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 +250,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 +261,23 @@ 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],
)
def render_ids(
@@ -277,22 +338,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 +418,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 +440,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 +452,14 @@ 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],
)
def _render_assistant(
self,
@@ -340,6 +471,7 @@ class MiniMaxM2Renderer:
preserve_thinking: bool = False,
emit_special,
emit_text,
emit_text_segments,
):
content = self._visible_text(msg.get("content"))
@@ -358,12 +490,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 +508,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 +529,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 +573,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 +595,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 +611,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 +621,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)
+207 -84
View File
@@ -24,10 +24,12 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.configs import Nemotron3RendererConfig
from renderers.parsing import parse_qwen35
# ---------------------------------------------------------------------------
@@ -78,17 +80,10 @@ class Nemotron3Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
config: Nemotron3RendererConfig | 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 Nemotron3RendererConfig()
# Look up special token IDs from the tokenizer (not hardcoded).
# <|endoftext|> is optional: Nemotron-3 Nano / Super tokenizers ship
@@ -241,19 +236,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,8 +282,7 @@ 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
if first_is_system:
@@ -282,22 +301,27 @@ 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)
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
@@ -322,18 +346,25 @@ 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))
emit_text_segments(user_segments, msg_orig_idx, is_sampled=False)
emit_special(
self._im_end, msg_orig_idx, is_sampled=False, is_content=False
)
emit_text("\n", msg_orig_idx, is_sampled=False, is_content=False)
elif role == "assistant":
is_last_turn = i >= last_plain_assistant_idx
preserve_thinking = msg_orig_idx >= 0 and should_preserve_past_thinking(
original_messages,
msg_orig_idx,
preserve_all_thinking=self._preserve_all_thinking,
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
preserve_all_thinking=self.config.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
)
self._render_assistant(
msg,
@@ -344,6 +375,7 @@ class Nemotron3Renderer:
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
emit_text_segments=emit_text_segments,
)
elif role == "tool":
@@ -355,6 +387,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 +395,22 @@ 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],
)
def render_ids(
@@ -393,7 +430,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 +443,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]:
@@ -442,22 +480,54 @@ 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)
@@ -466,12 +536,18 @@ class Nemotron3Renderer:
content = self._render_content(msg.get("content")).strip()
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 +559,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 +567,21 @@ 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],
)
# ------------------------------------------------------------------
# Assistant message rendering
@@ -514,6 +598,7 @@ class Nemotron3Renderer:
emit_special,
emit_text,
emit_ids,
emit_text_segments,
) -> None:
# Extract reasoning_content
reasoning_content = ""
@@ -534,9 +619,10 @@ class Nemotron3Renderer:
# 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
@@ -550,24 +636,48 @@ class Nemotron3Renderer:
# <tool_call>, whether the content is empty or not.
content_suffix = "\n" if tool_calls else ""
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)
if reasoning_content and (
is_last_turn
or preserve_thinking
or not self.config.truncate_history_thinking
):
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)
# Single \n separator (not \n\n like Qwen3.5)
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=True)
emit_text(
"\n" + content + content_suffix,
msg_idx,
is_sampled=True,
is_content=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)
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)
emit_text(
"\n" + content + content_suffix,
msg_idx,
is_sampled=True,
is_content=True,
)
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)
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)
emit_text(
content + content_suffix,
msg_idx,
is_sampled=True,
is_content=True,
)
# Tool calls (leading \n was glued to the content above; each
# iteration's trailing \n after </tool_call> handles the
@@ -578,8 +688,13 @@ class Nemotron3Renderer:
name = func.get("name", "")
arguments = func.get("arguments", {})
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
@@ -603,18 +718,21 @@ class Nemotron3Renderer:
+ "\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
)
# Trailing \n after </tool_call> (Nemotron 3 specific)
emit_text("\n", msg_idx, is_sampled=True)
emit_text("\n", 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)
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
@@ -630,10 +748,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 +762,19 @@ 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)
+16 -10
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:
+204 -83
View File
@@ -18,10 +18,12 @@ from renderers.base import (
ParsedResponse,
RenderedTokens,
ToolSpec,
attribute_text_segments,
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 +49,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|>")
@@ -108,43 +103,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 +186,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 +219,34 @@ 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],
)
def render_ids(
@@ -258,22 +304,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 +365,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 +386,24 @@ 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],
)
def _render_assistant(
self,
@@ -322,6 +416,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 +434,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 +465,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 +480,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 +512,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)
+337 -133
View File
@@ -26,10 +26,12 @@ from renderers.base import (
PlaceholderRange,
RenderedTokens,
ToolSpec,
attribute_text_segments,
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,
@@ -102,25 +104,27 @@ def _detect_enable_thinking_default(tokenizer: PreTrainedTokenizer) -> bool:
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 tokenizer's chat-template
# default (Instruct → off, Thinking → on). 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": _detect_enable_thinking_default(tokenizer)}
)
self.config = cfg
# Look up special token IDs from the tokenizer (not hardcoded)
self._im_start = self._token_id("<|im_start|>")
@@ -141,7 +145,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 +189,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 +294,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 +395,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 +426,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 +443,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 +493,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 +517,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 +527,7 @@ class Qwen35Renderer:
emit_special=emit_special,
emit_text=emit_text,
emit_image=emit_image,
emit_text_segments=emit_text_segments,
)
else:
@@ -457,16 +535,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 +558,8 @@ 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],
multi_modal_data=mm_data,
)
@@ -541,36 +621,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 +728,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 +771,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 +795,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 +803,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 +835,15 @@ 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]
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,
)
mm_data = MultiModalData(
mm_hashes=merged_hashes,
@@ -690,7 +852,10 @@ 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,
multi_modal_data=mm_data,
)
@@ -732,6 +897,7 @@ class Qwen35Renderer:
emit_special,
emit_text,
emit_ids,
emit_text_segments,
) -> None:
# Extract reasoning_content
reasoning_content = ""
@@ -754,26 +920,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 +962,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 +994,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 +1021,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 +1029,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 +1041,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 +1055,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 +1080,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):
+263 -118
View File
@@ -42,9 +42,11 @@ from renderers.base import (
PlaceholderRange,
RenderedTokens,
ToolSpec,
attribute_text_segments,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.configs import Qwen3VLRendererConfig
from renderers.parsing import parse_qwen3
_TOOLS_HEADER = (
@@ -70,9 +72,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 +88,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 +179,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 +213,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 +292,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|>")
@@ -288,7 +338,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 +426,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 +443,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 +491,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 +517,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 +525,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 +567,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 +585,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 +602,8 @@ 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],
multi_modal_data=mm_data,
)
@@ -584,30 +671,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 +752,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 +772,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 +835,10 @@ 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],
multi_modal_data=mm_data,
)
@@ -712,20 +851,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 +877,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 +900,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)
+2 -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")
#
@@ -44,7 +45,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]
+2 -1
View File
@@ -41,9 +41,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
+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
+44 -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,6 @@ def test_fastokens_incompatible_is_explicit_set():
{
"deepseek-ai/DeepSeek-V3",
"deepseek-ai/DeepSeek-V3-Base",
"MiniMaxAI/MiniMax-M2",
"MiniMaxAI/MiniMax-M2.5",
}
)
@@ -108,7 +105,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 +167,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"},
+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})
+2 -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
@@ -101,7 +101,7 @@ def test_qwen3_vl_malformed_tool_call_surfaces_as_invalid_json():
@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
+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)
+52 -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
@@ -379,17 +387,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 +409,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 +437,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]
+5 -5
View File
@@ -19,7 +19,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
@@ -78,11 +78,11 @@ def test_qwen35_enable_thinking_polarity_autodetected(qwen35_model, expected_def
own default when no explicit flag is passed — 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}"
)
@@ -148,7 +148,7 @@ def test_qwen35_size_parity_with_apply_chat_template(
share ``Qwen35Renderer`` across all seven sizes — the polarity
flip on 0.8B / 2B is absorbed by the constructor's auto-detect."""
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"
+513
View File
@@ -0,0 +1,513 @@
"""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"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-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],
# 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)})"
)
+3 -3
View File
@@ -51,11 +51,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):
@@ -316,7 +316,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" },
]