Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9619bf8f0 | ||
|
|
bdb96b0c84 | ||
|
|
201f88516c | ||
|
|
b6635d261c | ||
|
|
fa04acd916 | ||
|
|
33c8e6f897 | ||
|
|
0d104d82e3 | ||
|
|
defaf8fe2e | ||
|
|
4472b743a6 | ||
|
|
5904fa24aa | ||
|
|
db8698aaa8 | ||
|
|
a5efbb97e4 | ||
|
|
082836b5a8 | ||
|
|
42d6ee930b | ||
|
|
1933293372 | ||
|
|
0dc19a060e | ||
|
|
fe1dcdaed7 | ||
|
|
20d89be418 | ||
|
|
67568f79cf | ||
|
|
a3bf7e88b4 |
@@ -1,12 +1,11 @@
|
||||
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.
|
||||
# Every push to main publishes a pre-release wheel to PyPI. The version
|
||||
# is derived at build time by hatch-vcs from ``git describe`` distance
|
||||
# to the latest stable ``renderers-v<MAJOR>.<MINOR>.<PATCH>`` tag (see
|
||||
# ``[tool.hatch.version.raw-options]`` in pyproject.toml) — no per-commit
|
||||
# tag is created. ``local_scheme = "no-local-version"`` strips the
|
||||
# ``+gHASH`` segment so PyPI accepts the wheel directly.
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -17,68 +16,30 @@ concurrency:
|
||||
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 (no OIDC) → publish (OIDC only). The build job runs ``uv build``
|
||||
# with ``contents: read`` only so a poisoned build-time dep cannot mint
|
||||
# the OIDC token. The publish job has ``id-token: write`` and the
|
||||
# pypi-prod environment but no source checkout — it only downloads the
|
||||
# prebuilt artifact and runs the SHA-pinned pypa publish action.
|
||||
build:
|
||||
needs: tag
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# hatch-vcs needs the full tag history to resolve the version
|
||||
# from the latest stable tag's distance.
|
||||
fetch-depth: 0
|
||||
ref: refs/tags/${{ needs.tag.outputs.tag }}
|
||||
|
||||
- uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Build renderers
|
||||
run: uv build
|
||||
|
||||
- name: Show derived version
|
||||
run: ls -1 dist/
|
||||
|
||||
- name: Upload dist artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -102,3 +63,5 @@ jobs:
|
||||
|
||||
- name: Publish to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
|
||||
with:
|
||||
skip-existing: true
|
||||
|
||||
@@ -40,7 +40,7 @@ next_prompt_ids = r.bridge_to_next_turn(
|
||||
)
|
||||
```
|
||||
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.6`, `glm-5`, `glm-5.1`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `deepseek-r1`, `kimi-k2`, `kimi-k2.5` / `kimi-k2.6`, `nemotron-3`, `nemotron-3-ultra`, `llama-3`, `gpt-oss`, `hy3`, and `prime-qwen3`. Anything else falls back to `DefaultRenderer`, a generic `apply_chat_template` wrapper.
|
||||
|
||||
## API
|
||||
|
||||
@@ -74,7 +74,7 @@ Each hand-coded bridge:
|
||||
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 an explicit typed config (e.g. `Qwen3RendererConfig()`); unknown names fall back to `DefaultRenderer`.
|
||||
Auto-detect matches `tokenizer.name_or_path` against `MODEL_RENDERER_MAP` by **exact match**. Prefix matching is intentionally off — same architecture can ship different chat templates (base vs instruct, fine-tune renames). Fine-tunes must pass an explicit typed config (e.g. `Qwen3RendererConfig()`). Unknown text-only names fall back to `DefaultRenderer`, unless `AutoRendererConfig(thinking_retention=...)` was set; the default renderer cannot implement that bridge policy.
|
||||
|
||||
### Pools
|
||||
|
||||
@@ -95,7 +95,6 @@ For RL the trainer must see the exact token ids the sampler saw. The standard al
|
||||
- **Boolean round-trip.** Engine emits `false`; client parses to Python `bool(False)`; `apply_chat_template` re-renders via `str(False)` → `"False"`. Capital F. Reproducible on Qwen3.5-35B-A3B + mini-swe-agent-plus at ~50% break rate per rollout.
|
||||
- **BPE retokenization drift.** The same substring tokenizes differently depending on neighbouring bytes. `json` + `p` + `enderer` (3 tokens) vs `jsonp` + `enderer` (2 tokens) when whitespace shifts by one character. Every subsequent token is shifted from there on.
|
||||
- **Tool-call XML drift.** The engine emits a no-arg call with a stylistic empty `</parameter>`; the Jinja re-render of the reconstructed dict drops it. Extension property broken at every such call.
|
||||
- **Thinking stripped from non-latest assistants.** Some templates strip `<think>…</think>` blocks from prior assistant turns when re-rendering. The recorded stream has the thinking; the next prompt does not.
|
||||
- **Max-seq-len truncation zeroing the anchor.** Client-side `max_seq_len` enforcement zeros `completion_ids` when `prompt_len > max_seq_len`. The bridge anchor is empty, falling back to full re-render — triggering every mode above.
|
||||
- **Scaffold-level history rewriting.** Some agent scaffolds (e.g. opencode's `experimental_repairToolCall`) rewrite tool calls before sending them back as history. The next turn's prompt contains a tool call the model never emitted. *A renderer cannot fix this — the drift happens before rendering.*
|
||||
|
||||
@@ -110,7 +109,7 @@ Each break fragments a rollout into multiple training samples — every fragment
|
||||
|
||||
## Typed renderer configs
|
||||
|
||||
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:
|
||||
Each renderer accepts a typed pydantic config at construction. Some fields mirror chat-template kwargs; others configure renderer-only behavior such as image caching, parsers, or Harmony preamble construction. `create_renderer` and `create_renderer_pool` take one positional `config` argument and an optional keyword-only `chat_template_kwargs` mapping:
|
||||
|
||||
```python
|
||||
from renderers import (
|
||||
@@ -121,13 +120,15 @@ from renderers import (
|
||||
DefaultRendererConfig,
|
||||
)
|
||||
|
||||
# Auto-resolve renderer from the tokenizer's model name. Carries the
|
||||
# shared preserve_* flags; template kwargs require an explicit choice.
|
||||
# Auto-resolve renderer from the tokenizer's model name.
|
||||
renderer = create_renderer(tokenizer)
|
||||
renderer = create_renderer(tokenizer, AutoRendererConfig(preserve_all_thinking=True))
|
||||
renderer = create_renderer(tokenizer, AutoRendererConfig(thinking_retention="all"))
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
# Explicit choice — the typed config exposes exactly the fields that
|
||||
# renderer's chat template honours.
|
||||
# Explicit choice — use the renderer-specific fields it exposes.
|
||||
renderer = create_renderer(tokenizer, Qwen3RendererConfig(enable_thinking=False))
|
||||
renderer = create_renderer(tokenizer, GLM5RendererConfig(clear_thinking=False))
|
||||
|
||||
@@ -142,21 +143,24 @@ renderer = create_renderer(
|
||||
|
||||
Discriminated union: every per-renderer config is a variant of `RendererConfig`, dispatched on the `name` field. Bogus combinations (e.g. `add_vision_id` under `name="qwen3"`) error at construction with a `pydantic.ValidationError`. Downstream pydantic configs (prime-rl orchestrator, verifiers `ClientConfig`) hold a single field typed as `RendererConfig` and inherit the same strict-per-variant validation.
|
||||
|
||||
Two shared behaviour flags live on every variant via `_BaseRendererConfig`:
|
||||
When `chat_template_kwargs` is passed with `config=None` / `AutoRendererConfig`, renderers first resolves the concrete renderer from the model name, then validates those kwargs against that renderer's config. `Auto + unknown model + chat_template_kwargs` fails loudly; use an explicit typed config or explicit `DefaultRendererConfig` for opaque fallback templates.
|
||||
|
||||
- `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.
|
||||
One shared behaviour flag lives on typed renderer configs: `thinking_retention`, an optional bridge-policy override. Leave it unset to derive bridge behaviour from the chat template and its renderer-exposed kwargs.
|
||||
|
||||
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.
|
||||
- `thinking_retention=None` (default) — derive from the chat template / renderer kwargs.
|
||||
- `thinking_retention="tool_cycle"` — bridge within the in-flight tool cycle; a new user query falls back to a full re-render.
|
||||
- `thinking_retention="all"` — bridge across user-query boundaries when the bridge is otherwise structurally valid.
|
||||
|
||||
Generic `thinking_retention` does **not** change full `render()` output: a full re-render always follows the Python chat-template implementation. Only real template knobs can change full-render thinking behaviour. GLM-5 `clear_thinking=False`, Nemotron-3 `truncate_history_thinking=False`, Qwen3.6 `preserve_thinking=True`, and GPT-OSS `auto_drop_analysis=False` all imply bridge policy `"all"`; no-thinking generation knobs also imply `"all"` when `thinking_retention` is unset. Setting a direct keep/drop template knob and a contradictory `thinking_retention` raises at config-load. The full per-renderer mapping lives in [`docs/renderer-config.md`](docs/renderer-config.md).
|
||||
|
||||
## `DefaultRenderer`
|
||||
|
||||
Fallback for unsupported models. Wraps `apply_chat_template` and accepts `tool_parser` / `reasoning_parser` (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.
|
||||
Fallback for unsupported text-only models. Wraps `apply_chat_template` and accepts `tool_parser` / `reasoning_parser` (vLLM convention) plus arbitrary Jinja kwargs via `DefaultRendererConfig`'s `extra="allow"`. Explicit `thinking_retention` is rejected: `bridge_to_next_turn` returns `None` because the template's close is unknown, so multi-turn rollouts fall back to full re-render. Implementing a hand-coded renderer is a few hundred lines of Python (`render_ids` + `parse_response` + `bridge_to_next_turn`) and is the only path that closes the failure modes above by construction.
|
||||
|
||||
## Roadmap
|
||||
|
||||
- **VLM support.** `ContentPart` is text-only today; `Qwen3VLRenderer` ships only because Qwen3-VL's text-only chat template differs from Qwen3's. Plan: add `ImagePart` / `VideoPart`, multimodal bridges, validate against a Qwen3-VL RL run.
|
||||
- **Patched chat templates.** Some shipped templates re-tokenize history, normalize JSON, or auto-strip thinking — each breaks the extension property. Plan: a `use_patched` opt-in per renderer that renders the same surface form while avoiding known-bad patterns.
|
||||
- **VLM expansion.** `ImagePart` support exists for Qwen3-VL and Qwen3.5-family multimodal templates. Remaining work: video support, broader VLM coverage, and more RL validation.
|
||||
- **Patched chat templates.** Some shipped templates re-tokenize history or normalize JSON in ways that break token identity. Plan: a `use_patched` opt-in per renderer that renders the same surface form while avoiding known-bad patterns. (Auto-stripping thinking from past turns is *not* one of these — that's intended template behaviour the renderer reproduces; use `thinking_retention` to override it.)
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
+147
-89
@@ -1,104 +1,161 @@
|
||||
# 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.
|
||||
`create_renderer_pool`. It pins the renderer choice and its config at
|
||||
construction time.
|
||||
|
||||
```python
|
||||
from renderers import create_renderer, Qwen35RendererConfig
|
||||
|
||||
r = create_renderer(tokenizer, Qwen35RendererConfig(enable_thinking=False))
|
||||
r = create_renderer(tokenizer, chat_template_kwargs={"enable_thinking": False})
|
||||
```
|
||||
|
||||
`RendererConfig` is a pydantic discriminated union (one variant per renderer,
|
||||
dispatched on the `name` field). Selecting a variant exposes exactly the
|
||||
fields that renderer's chat template honours; anything else raises a
|
||||
`pydantic.ValidationError` at construction.
|
||||
`RendererConfig` is a pydantic discriminated union, one variant per renderer,
|
||||
dispatched on the `name` field. Most variants reject unknown fields at
|
||||
construction. A field can either mirror a chat-template kwarg or configure a
|
||||
renderer-only behavior such as parsing, image caching, or Harmony preamble
|
||||
construction.
|
||||
|
||||
## Per-renderer configs
|
||||
|
||||
Each hand-coded renderer has a typed config class with the template kwargs
|
||||
its Jinja chat template reads. For example:
|
||||
Use `type(config).template_field_names()` to inspect the fields that mirror
|
||||
chat-template kwargs. Those fields are covered by parity tests against
|
||||
`apply_chat_template` in `tests/test_renderer_config_parity.py`.
|
||||
|
||||
| Renderer | Config class | Template fields |
|
||||
|----------------|--------------------------|----------------------------------------------------------------|
|
||||
| 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` |
|
||||
| Renderer | Config class | Template fields | Renderer-only fields |
|
||||
| --- | --- | --- | --- |
|
||||
| Qwen3 | `Qwen3RendererConfig` | `enable_thinking` | - |
|
||||
| PrimeIntellect Qwen3 | `PrimeQwen3RendererConfig` | - | - |
|
||||
| Qwen3.5 | `Qwen35RendererConfig` | `enable_thinking`, `add_vision_id` | `image_cache_max` |
|
||||
| Qwen3.6 | `Qwen36RendererConfig` | `enable_thinking`, `add_vision_id`, `preserve_thinking` | `image_cache_max` |
|
||||
| Qwen3-VL | `Qwen3VLRendererConfig` | `add_vision_id` | `image_cache_max` |
|
||||
| GLM-5 / 5.1 | `GLM5RendererConfig` / `GLM51RendererConfig` | `enable_thinking`, `clear_thinking` | - |
|
||||
| GLM-4.5 | `GLM45RendererConfig` | `enable_thinking` | - |
|
||||
| gpt-oss | `GptOssRendererConfig` | `reasoning_effort`, `conversation_start_date` | `use_system_prompt`, `knowledge_cutoff`, `model_identity`, `auto_drop_analysis` |
|
||||
| Hy3 | `Hy3RendererConfig` | `reasoning_effort`, `preserved_thinking`, `is_training`, `raw_last_assistant`, `fallback_strategy` | - |
|
||||
| Kimi K2 | `KimiK2RendererConfig` | - | `enable_thinking` |
|
||||
| Kimi K2.5 / 2.6 | `KimiK25RendererConfig` | `thinking` | `image_cache_max` |
|
||||
| Laguna XS.2 | `LagunaXS2RendererConfig` | `enable_thinking`, `render_assistant_messages_raw` | - |
|
||||
| Laguna XS-2.1 | `LagunaXS21RendererConfig` | `enable_thinking` | - |
|
||||
| Llama 3 | `Llama3RendererConfig` | `date_string`, `tools_in_user_message` | - |
|
||||
| MiniMax M2 | `MiniMaxM2RendererConfig` | `model_identity` | - |
|
||||
| Nemotron-3 Nano / Super | `Nemotron3RendererConfig` | `enable_thinking`, `truncate_history_thinking`, `low_effort` | - |
|
||||
| Nemotron-3 Ultra | `Nemotron3UltraRendererConfig` | `enable_thinking`, `truncate_history_thinking`, `medium_effort` | - |
|
||||
| DeepSeek V3 | `DeepSeekV3RendererConfig` | - | - |
|
||||
| DeepSeek R1 | `DeepSeekR1RendererConfig` | - | - |
|
||||
|
||||
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={...})`.
|
||||
Configs are frozen value objects. 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`:
|
||||
`create_renderer(tokenizer)` 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))
|
||||
```
|
||||
from renderers import AutoRendererConfig, GLM5RendererConfig
|
||||
|
||||
`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)
|
||||
r = create_renderer(tokenizer, AutoRendererConfig(thinking_retention="all"))
|
||||
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.
|
||||
`AutoRendererConfig` carries only the shared `thinking_retention` override.
|
||||
Callers that receive run-scoped chat-template kwargs can pass them separately:
|
||||
|
||||
## `preserve_*` flags
|
||||
```python
|
||||
r = create_renderer(
|
||||
tokenizer,
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
pool = create_renderer_pool(
|
||||
"Qwen/Qwen3-8B",
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
```
|
||||
|
||||
Every variant carries two renderer-agnostic flags on `_BaseRendererConfig`:
|
||||
Renderers resolves auto configs before applying `chat_template_kwargs`, so the
|
||||
kwargs validate against the concrete renderer config. Unknown kwargs, or kwargs
|
||||
that conflict with an explicit `thinking_retention`, fail at construction.
|
||||
|
||||
- `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.
|
||||
Auto-resolution fails loudly for VLMs without an exact registered renderer.
|
||||
Text-only unknown models fall back to `DefaultRenderer`, unless
|
||||
`AutoRendererConfig(thinking_retention=...)` was set. The default renderer
|
||||
cannot implement selective bridge retention, so that combination raises.
|
||||
`AutoRendererConfig` with `chat_template_kwargs` also raises for unknown models,
|
||||
because renderers cannot validate those kwargs without a concrete renderer.
|
||||
Use an explicit model-specific config, or `DefaultRendererConfig(...)` when you
|
||||
intentionally want opaque `apply_chat_template` kwargs.
|
||||
|
||||
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:
|
||||
## `thinking_retention`
|
||||
|
||||
| `clear_thinking` | `preserve_all_thinking` | past thinking? |
|
||||
|------------------|-------------------------|----------------|
|
||||
| `True` (default — drop) | `False` (default) | dropped |
|
||||
| `True` | `True` | kept |
|
||||
| `False` (keep) | `False` | kept |
|
||||
| `False` | `True` | kept |
|
||||
Every typed renderer config carries one shared optional bridge-policy override:
|
||||
|
||||
`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.
|
||||
```python
|
||||
thinking_retention: Literal["tool_cycle", "all"] | None = None
|
||||
```
|
||||
|
||||
## `DefaultRendererConfig` accepts arbitrary Jinja kwargs
|
||||
| Value | Meaning |
|
||||
| --- | --- |
|
||||
| `None` | Derive the effective bridge policy from the renderer's template knobs and defaults. |
|
||||
| `"tool_cycle"` | Bridge within the current tool cycle; re-render when the extension opens a new user query. |
|
||||
| `"all"` | Allow bridging across user-query boundaries when the bridge is otherwise structurally valid. |
|
||||
|
||||
`DefaultRenderer` wraps `tokenizer.apply_chat_template` for any model that
|
||||
doesn't have a hand-coded renderer. Its config sets `extra="allow"`:
|
||||
`thinking_retention` affects `bridge_to_next_turn`, not full `render()`.
|
||||
A full render always follows the Python chat-template implementation. Only real
|
||||
template fields, such as `clear_thinking`, `preserve_thinking`, or
|
||||
`truncate_history_thinking`, can change full-render historical thinking.
|
||||
|
||||
Internally, renderers resolve an `effective_thinking_retention` at construction:
|
||||
|
||||
| Internal policy | Bridge behavior |
|
||||
| --- | --- |
|
||||
| `"template"` | Decline bridging; caller falls back to a full re-render. |
|
||||
| `"tool_cycle"` | Bridge unless `new_messages` introduces a user query. |
|
||||
| `"all"` | Do not block bridging for thinking retention. |
|
||||
|
||||
`"template"` is not a public config value. Leave `thinking_retention` unset to
|
||||
get template-derived behavior.
|
||||
|
||||
## Derived retention defaults
|
||||
|
||||
When `thinking_retention` is unset, each renderer derives its bridge policy from
|
||||
the knobs its template actually exposes:
|
||||
|
||||
| Renderer | Derived policy |
|
||||
| --- | --- |
|
||||
| Qwen3 | `enable_thinking=False -> all`, else `tool_cycle` |
|
||||
| Qwen3.5 | `enable_thinking=False -> all`, else `tool_cycle` |
|
||||
| Qwen3.6 | `preserve_thinking=True -> all`; else `enable_thinking=False -> all`; else `tool_cycle` |
|
||||
| GLM-5 / 5.1 | `clear_thinking=False -> all`; else `enable_thinking=False -> all`; else `tool_cycle` |
|
||||
| GLM-4.5 | `enable_thinking=False -> all`, else `tool_cycle` |
|
||||
| gpt-oss | `auto_drop_analysis=False -> all`, else `tool_cycle` |
|
||||
| Hy3 | `preserved_thinking=True -> all`, else `tool_cycle` |
|
||||
| Kimi K2.5 / 2.6 | `thinking=False -> all`, else `tool_cycle` |
|
||||
| Nemotron-3 | `truncate_history_thinking=False -> all`; else `enable_thinking=False -> all`; else `tool_cycle` |
|
||||
| DeepSeek R1 | `template` |
|
||||
| MiniMax M2 | `tool_cycle` |
|
||||
| DeepSeek V3, Qwen3-VL, Kimi K2, Laguna XS.2 / XS-2.1, Llama 3 | `all` |
|
||||
| PrimeIntellect Qwen3 | `all` |
|
||||
|
||||
Config construction raises when an explicit template knob directly contradicts
|
||||
an explicit generic bridge policy. For example:
|
||||
|
||||
```python
|
||||
GLM5RendererConfig(clear_thinking=False, thinking_retention="tool_cycle")
|
||||
# ValueError: clear_thinking=False implies thinking_retention="all"
|
||||
```
|
||||
|
||||
Generation-only no-thinking knobs, such as `enable_thinking=False`, do not
|
||||
conflict with an explicit conservative `thinking_retention="tool_cycle"`. They
|
||||
only change the derived default when `thinking_retention` is unset.
|
||||
|
||||
## `DefaultRendererConfig`
|
||||
|
||||
`DefaultRenderer` wraps `tokenizer.apply_chat_template` for unsupported
|
||||
text-only models. Its config sets `extra="allow"` so unknown fields are
|
||||
forwarded as Jinja kwargs:
|
||||
|
||||
```python
|
||||
from renderers import create_renderer, DefaultRendererConfig
|
||||
@@ -106,58 +163,59 @@ from renderers import create_renderer, DefaultRendererConfig
|
||||
r = create_renderer(
|
||||
tokenizer,
|
||||
DefaultRendererConfig(
|
||||
tool_parser="qwen3", # registered in renderers.parsers
|
||||
tool_parser="qwen3",
|
||||
reasoning_parser="think",
|
||||
enable_thinking=False, # forwarded to apply_chat_template
|
||||
custom_jinja_kwarg=True, # ditto
|
||||
enable_thinking=False,
|
||||
custom_jinja_kwarg=True,
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
`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`.
|
||||
`tool_parser` and `reasoning_parser` configure `DefaultRenderer` itself. Every
|
||||
other extra field lands in `model_extra` and is forwarded to
|
||||
`apply_chat_template`.
|
||||
|
||||
`DefaultRenderer` rejects explicit `thinking_retention` and the removed
|
||||
`preserve_*` flags. Its bridge always returns `None`, because the template's
|
||||
turn-close structure is opaque to the renderer.
|
||||
|
||||
## Downstream integration
|
||||
|
||||
Downstream pydantic configs (`prime-rl` orchestrator, `verifiers`
|
||||
`ClientConfig`) hold a single field typed as `RendererConfig`:
|
||||
Downstream pydantic configs can hold a single field typed as `RendererConfig`:
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
|
||||
class ClientConfig(BaseModel):
|
||||
renderer: RendererConfig = Field(default_factory=AutoRendererConfig)
|
||||
```
|
||||
|
||||
In TOML / YAML, the discriminator routes deserialization:
|
||||
In TOML or YAML, the `name` discriminator selects the variant:
|
||||
|
||||
```toml
|
||||
[client.renderer]
|
||||
name = "qwen3.5"
|
||||
enable_thinking = false
|
||||
add_vision_id = true
|
||||
preserve_all_thinking = true
|
||||
thinking_retention = "all"
|
||||
```
|
||||
|
||||
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.
|
||||
Bogus combinations, such as `add_vision_id` under `name = "qwen3"`, raise at
|
||||
config load with a pydantic validation error.
|
||||
|
||||
To construct a config from a renderer name string (e.g. from a CLI flag):
|
||||
To construct a config from a renderer name string:
|
||||
|
||||
```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
|
||||
cfg = config_from_name("glm-5") # GLM5RendererConfig()
|
||||
cfg = config_from_name("auto") # None, the implicit auto form
|
||||
```
|
||||
|
||||
## Renaming a renderer is a breaking change
|
||||
|
||||
The discriminator key is the renderer name string. Renaming `"qwen3.5"` to
|
||||
something else would break any downstream config that references it by
|
||||
name. Add new renderers; don't rename existing ones.
|
||||
something else would break downstream configs that reference it by name. Add
|
||||
new renderers instead of renaming existing ones.
|
||||
|
||||
+16
-12
@@ -31,12 +31,6 @@ dependencies = [
|
||||
# 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). 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
|
||||
@@ -57,6 +51,22 @@ tag-pattern = '^renderers-v(?P<version>.+)$'
|
||||
# only fires when the resolver has nothing to go on.
|
||||
fallback-version = "0.0.0"
|
||||
|
||||
[tool.hatch.version.raw-options]
|
||||
# Only stable ``renderers-v<MAJOR>.<MINOR>.<PATCH>`` tags participate in
|
||||
# version resolution; legacy per-commit ``.devN`` tags are excluded.
|
||||
# Untagged commits get a clean PEP 440 dev version derived from distance
|
||||
# to the latest stable tag (e.g. ``0.1.8.dev46``), with no ``+gHASH``
|
||||
# local segment so PyPI accepts the wheel directly. setuptools-scm
|
||||
# refuses to bump a pre-existing ``.devN`` tag, so matching only stable
|
||||
# tags also unblocks local ``uv lock`` / ``uv build`` on untagged
|
||||
# branches. Mirrors verifiers' setup.
|
||||
local_scheme = "no-local-version"
|
||||
git_describe_command = [
|
||||
"git", "describe", "--tags", "--long",
|
||||
"--match", "renderers-v[0-9]*.[0-9]*.[0-9]*",
|
||||
"--exclude", "*dev*",
|
||||
]
|
||||
|
||||
[tool.hatch.build.hooks.vcs]
|
||||
# Write the resolved version to a Python file so it can be inspected
|
||||
# at runtime via ``renderers.__version__`` without re-parsing the
|
||||
@@ -87,12 +97,6 @@ required-version = ">=0.11.1"
|
||||
exclude-newer = "7 days"
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# fastokens 0.2.0 was published on 2026-05-17 and contains the
|
||||
# ``unpatch_transformers`` fix (crusoecloud/fastokens#32) needed for
|
||||
# MiniMax-M2's slow→fast tokenizer conversion path. Exempting it from
|
||||
# the project-wide 7-day cutoff lets the lockfile pick it up immediately
|
||||
# while the rest of the dependency graph stays gated.
|
||||
fastokens = false
|
||||
# PrimeIntellect-published packages in this project's dependency closure —
|
||||
# fast-track so first-party releases can land same-day. Only packages that
|
||||
# appear in `uv tree` are listed.
|
||||
|
||||
@@ -19,6 +19,7 @@ from renderers.base import (
|
||||
PlaceholderRange,
|
||||
RenderedConversation,
|
||||
RenderedTokens,
|
||||
RenderedTrainingSample,
|
||||
Renderer,
|
||||
RendererPool,
|
||||
TextPart,
|
||||
@@ -50,12 +51,16 @@ from renderers.configs import (
|
||||
GLM51RendererConfig,
|
||||
GLM5RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
Hy3RendererConfig,
|
||||
KimiK25RendererConfig,
|
||||
KimiK2RendererConfig,
|
||||
LagunaXS2RendererConfig,
|
||||
LagunaXS21RendererConfig,
|
||||
Llama3RendererConfig,
|
||||
MiniMaxM2RendererConfig,
|
||||
Nemotron3RendererConfig,
|
||||
Nemotron3UltraRendererConfig,
|
||||
PrimeQwen3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
Qwen36RendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
@@ -82,12 +87,16 @@ _LAZY_RENDERERS: dict[str, str] = {
|
||||
"GLM51Renderer": "renderers.glm5",
|
||||
"GLM5Renderer": "renderers.glm5",
|
||||
"GptOssRenderer": "renderers.gpt_oss",
|
||||
"Hy3Renderer": "renderers.hy3",
|
||||
"KimiK25Renderer": "renderers.kimi_k25",
|
||||
"KimiK2Renderer": "renderers.kimi_k2",
|
||||
"LagunaXS21Renderer": "renderers.laguna_xs2",
|
||||
"LagunaXS2Renderer": "renderers.laguna_xs2",
|
||||
"Llama3Renderer": "renderers.llama_3",
|
||||
"MiniMaxM2Renderer": "renderers.minimax_m2",
|
||||
"Nemotron3Renderer": "renderers.nemotron3",
|
||||
"Nemotron3UltraRenderer": "renderers.nemotron3",
|
||||
"PrimeQwen3Renderer": "renderers.prime_qwen3",
|
||||
"Qwen35Renderer": "renderers.qwen35",
|
||||
"Qwen36Renderer": "renderers.qwen36",
|
||||
"Qwen3Renderer": "renderers.qwen3",
|
||||
@@ -129,6 +138,8 @@ __all__ = [
|
||||
"GLM5RendererConfig",
|
||||
"GptOssRenderer",
|
||||
"GptOssRendererConfig",
|
||||
"Hy3Renderer",
|
||||
"Hy3RendererConfig",
|
||||
"ImagePart",
|
||||
"KimiK25Renderer",
|
||||
"KimiK25RendererConfig",
|
||||
@@ -136,6 +147,8 @@ __all__ = [
|
||||
"KimiK2RendererConfig",
|
||||
"LagunaXS2Renderer",
|
||||
"LagunaXS2RendererConfig",
|
||||
"LagunaXS21Renderer",
|
||||
"LagunaXS21RendererConfig",
|
||||
"Llama3Renderer",
|
||||
"Llama3RendererConfig",
|
||||
"MULTIMODAL_MODELS",
|
||||
@@ -146,10 +159,14 @@ __all__ = [
|
||||
"MultimodalRenderer",
|
||||
"Nemotron3Renderer",
|
||||
"Nemotron3RendererConfig",
|
||||
"Nemotron3UltraRenderer",
|
||||
"Nemotron3UltraRendererConfig",
|
||||
"OverlongPromptError",
|
||||
"ParsedResponse",
|
||||
"ParsedToolCall",
|
||||
"PlaceholderRange",
|
||||
"PrimeQwen3Renderer",
|
||||
"PrimeQwen3RendererConfig",
|
||||
"Qwen35Renderer",
|
||||
"Qwen35RendererConfig",
|
||||
"Qwen36Renderer",
|
||||
@@ -160,6 +177,7 @@ __all__ = [
|
||||
"Qwen3VLRendererConfig",
|
||||
"RenderedConversation",
|
||||
"RenderedTokens",
|
||||
"RenderedTrainingSample",
|
||||
"Renderer",
|
||||
"RendererConfig",
|
||||
"RendererPool",
|
||||
|
||||
+364
-258
@@ -1,8 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import enum
|
||||
import io
|
||||
import logging
|
||||
import queue
|
||||
import threading
|
||||
@@ -20,7 +18,11 @@ from typing import (
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers.configs import AutoRendererConfig, RendererConfig
|
||||
from renderers.configs import (
|
||||
AutoRendererConfig,
|
||||
RendererConfig,
|
||||
ResolvedThinkingRetention,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("renderers.base")
|
||||
|
||||
@@ -666,15 +668,12 @@ class Renderer(Protocol):
|
||||
"""Render messages to token IDs with per-token message attribution.
|
||||
|
||||
Behaviour around historical ``reasoning_content`` is owned by the
|
||||
renderer instance — the ``preserve_all_thinking`` and
|
||||
``preserve_thinking_between_tool_calls`` flags are constructor
|
||||
kwargs, not call-site kwargs. To render with a different
|
||||
configuration, build a different renderer (or different pool).
|
||||
Defaults preserve byte-identity with each model's chat template;
|
||||
flipping a flag at construction restores ``reasoning_content``
|
||||
the template would otherwise drop. See
|
||||
``should_preserve_past_thinking`` for the per-message
|
||||
classification.
|
||||
renderer instance — the ``thinking_retention`` level is resolved at
|
||||
construction, not passed per call. To render with a different
|
||||
configuration, build a different renderer (or different pool). When
|
||||
``thinking_retention`` is left unset, full renders follow the model's
|
||||
chat template and bridge policy is derived from that template's own
|
||||
history-retention knobs.
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -769,8 +768,12 @@ class Renderer(Protocol):
|
||||
Return ``None`` whenever the renderer can't prove that contract
|
||||
holds — the caller falls back to a full re-render. In particular,
|
||||
bridges refuse assistant messages in ``new_messages`` (those would
|
||||
re-tokenize model-sampled content). Hand-coded renderers know their
|
||||
canonical close and synthesise it on truncated priors;
|
||||
re-tokenize model-sampled content). They also follow the renderer's
|
||||
resolved thinking-retention bridge policy: ``"template"`` always
|
||||
re-renders, ``"tool_cycle"`` re-renders at a new user-query boundary,
|
||||
and ``"all"`` allows extension when the rest of the structural bridge
|
||||
checks pass. Hand-coded renderers know their canonical close and
|
||||
synthesise it on truncated priors;
|
||||
DefaultRenderer always returns ``None`` because the template's
|
||||
close is unknown.
|
||||
"""
|
||||
@@ -996,6 +999,10 @@ MODEL_RENDERER_MAP: dict[str, str] = {
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "qwen3",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "qwen3",
|
||||
"Qwen/Qwen3-235B-A22B": "qwen3",
|
||||
# PrimeIntellect Qwen3 — both sizes share the same Qwen3-Coder-style
|
||||
# template with XML tool definitions and calls.
|
||||
"PrimeIntellect/Qwen3-0.6B": "prime-qwen3",
|
||||
"PrimeIntellect/Qwen3-1.7B": "prime-qwen3",
|
||||
# Qwen3.5. All seven sizes share the same renderer. The 4B / 9B /
|
||||
# 35B-A3B / 122B-A10B / 397B-A17B chat template defaults
|
||||
# ``enable_thinking=true`` (open ``<think>\n`` at the gen prompt);
|
||||
@@ -1040,14 +1047,15 @@ MODEL_RENDERER_MAP: dict[str, str] = {
|
||||
"moonshotai/Kimi-K2-Instruct": "kimi-k2",
|
||||
"moonshotai/Kimi-K2.5": "kimi-k2.5",
|
||||
"moonshotai/Kimi-K2.6": "kimi-k2.5",
|
||||
# Nemotron 3. Nano / Super share one chat-template variant; the Ultra
|
||||
# checkpoints use the Ultra variant — the renderer auto-selects it from
|
||||
# the model name (see ``nemotron3._ULTRA_DEFAULTS``). BF16 and FP8 share the
|
||||
# Nemotron 3. Nano / Super share one chat-template variant (``nemotron-3``);
|
||||
# the Ultra checkpoints use the Ultra variant (``nemotron-3-ultra``, distinct
|
||||
# ``</think>`` glue). Both route to the same Nemotron3Renderer, which selects
|
||||
# the variant from the resolved config's ``name``. BF16 and FP8 share the
|
||||
# same tokenizer and template.
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "nemotron-3",
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "nemotron-3",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16": "nemotron-3",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8": "nemotron-3",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16": "nemotron-3-ultra",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8": "nemotron-3-ultra",
|
||||
# Llama 3.2 (Instruct). Tested against the gated meta-llama repos and
|
||||
# the unrestricted unsloth/... mirror, which ships a byte-identical
|
||||
# chat template. ``Llama3Renderer`` defaults ``date_string`` to
|
||||
@@ -1056,11 +1064,19 @@ MODEL_RENDERER_MAP: dict[str, str] = {
|
||||
# construction to pin a different date.
|
||||
"meta-llama/Llama-3.2-1B-Instruct": "llama-3",
|
||||
"meta-llama/Llama-3.2-3B-Instruct": "llama-3",
|
||||
# Poolside Laguna.
|
||||
# Poolside Laguna. The two checkpoints ship different chat templates,
|
||||
# each mirrored by its own renderer class.
|
||||
"poolside/Laguna-XS.2": "laguna-xs.2",
|
||||
"poolside/Laguna-XS-2.1": "laguna-xs-2.1",
|
||||
# GPT-OSS.
|
||||
"openai/gpt-oss-20b": "gpt-oss",
|
||||
"openai/gpt-oss-120b": "gpt-oss",
|
||||
# Tencent Hunyuan Hy3 (295B-A21B MoE). The FP8 checkpoint shares the same
|
||||
# tokenizer and chat template. Hy3-preview is deliberately unmapped: it
|
||||
# ships an older, incompatible template (un-suffixed special tokens,
|
||||
# ``interleaved_thinking`` instead of ``preserved_thinking``).
|
||||
"tencent/Hy3": "hy3",
|
||||
"tencent/Hy3-FP8": "hy3",
|
||||
}
|
||||
|
||||
|
||||
@@ -1151,69 +1167,51 @@ 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. The entries below fail to load under fastokens (DeepSeek-V3
|
||||
# family — Metaspace pretokenizer not yet implemented).
|
||||
FASTOKENS_INCOMPATIBLE: frozenset[str] = frozenset(
|
||||
{
|
||||
# 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",
|
||||
"deepseek-ai/DeepSeek-R1",
|
||||
"deepseek-ai/DeepSeek-R1-0528",
|
||||
}
|
||||
)
|
||||
# Tokenizer repos to use when a canonical model repo is gated but an
|
||||
# audited unrestricted mirror ships byte-identical tokenizer files and
|
||||
# chat_template. The returned tokenizer keeps the caller's original
|
||||
# ``name_or_path`` so exact-match renderer resolution still uses
|
||||
# ``MODEL_RENDERER_MAP``.
|
||||
TOKENIZER_SOURCE_OVERRIDES: dict[str, str] = {
|
||||
"meta-llama/Llama-3.2-1B-Instruct": "unsloth/Llama-3.2-1B-Instruct",
|
||||
"meta-llama/Llama-3.2-3B-Instruct": "unsloth/Llama-3.2-3B-Instruct",
|
||||
}
|
||||
|
||||
|
||||
_FASTOKENS_PATCH_LOCK = threading.Lock()
|
||||
_FASTOKENS_ANNOUNCED = False
|
||||
def _tokenizer_source_for(model_name_or_path: str) -> str:
|
||||
return TOKENIZER_SOURCE_OVERRIDES.get(model_name_or_path, model_name_or_path)
|
||||
|
||||
|
||||
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.
|
||||
def _tokenizer_load_kwargs(model_name_or_path: str) -> dict[str, Any]:
|
||||
revision = TRUSTED_REVISIONS.get(model_name_or_path)
|
||||
if revision is not None:
|
||||
return {"trust_remote_code": True, "revision": revision}
|
||||
return {"trust_remote_code": False}
|
||||
|
||||
fastokens captures the loaded backend on a per-tokenizer basis, so
|
||||
after we unpatch the returned tokenizer object continues to use
|
||||
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
|
||||
def _preserve_requested_tokenizer_name(
|
||||
tokenizer,
|
||||
*,
|
||||
requested_name_or_path: str,
|
||||
loaded_name_or_path: str,
|
||||
):
|
||||
if requested_name_or_path == loaded_name_or_path:
|
||||
return tokenizer
|
||||
|
||||
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 _load_tokenizer_via_auto(model_name_or_path, **kwargs)
|
||||
finally:
|
||||
with _FASTOKENS_PATCH_LOCK:
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
fastokens.unpatch_transformers()
|
||||
tokenizer.name_or_path = requested_name_or_path
|
||||
except Exception:
|
||||
init_kwargs = getattr(tokenizer, "init_kwargs", None)
|
||||
if isinstance(init_kwargs, dict):
|
||||
init_kwargs["name_or_path"] = requested_name_or_path
|
||||
|
||||
if getattr(tokenizer, "name_or_path", "") != requested_name_or_path:
|
||||
raise RuntimeError(
|
||||
f"Loaded tokenizer for {requested_name_or_path!r} from "
|
||||
f"{loaded_name_or_path!r}, but could not preserve the requested "
|
||||
"name_or_path for renderer auto-resolution."
|
||||
)
|
||||
return tokenizer
|
||||
|
||||
|
||||
def _load_fast_tokenizer_directly(
|
||||
@@ -1275,65 +1273,34 @@ def _load_tokenizer_via_auto(model_name_or_path: str, **kwargs) -> Any:
|
||||
return tok
|
||||
|
||||
|
||||
def load_tokenizer(
|
||||
model_name_or_path: str,
|
||||
*,
|
||||
use_fastokens: bool = True,
|
||||
):
|
||||
"""Load a tokenizer with the renderers-package security + perf policy.
|
||||
def load_tokenizer(model_name_or_path: str):
|
||||
"""Load a tokenizer with the renderers-package security policy.
|
||||
|
||||
**Security** — default ``trust_remote_code=False``. Models listed in
|
||||
Default ``trust_remote_code=False``. Models listed in
|
||||
``TRUSTED_REVISIONS`` (Moonshot Kimi-K2 family) load with
|
||||
``trust_remote_code=True`` AND a pinned ``revision=<sha>`` so
|
||||
transformers only executes the reviewed commit's tokenizer Python.
|
||||
|
||||
**Performance** — ``use_fastokens=True`` (default) routes the load
|
||||
through ``fastokens.patch_transformers()`` so the resulting tokenizer
|
||||
encodes ~10x faster than vanilla ``tokenizers``. The patch is
|
||||
bracketed: it's applied before ``from_pretrained`` and removed
|
||||
immediately after, so global ``AutoTokenizer.from_pretrained`` calls
|
||||
elsewhere in the user's process are not affected.
|
||||
|
||||
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
|
||||
fastokens raises during the patched load (e.g. an unknown
|
||||
pre-tokenizer type), we automatically retry with the vanilla
|
||||
backend and emit an INFO log.
|
||||
|
||||
``AutoTokenizer.from_pretrained`` eagerly builds the model config to
|
||||
resolve the tokenizer class. If that construction raises on a
|
||||
modeling-only concern the tokenizer doesn't need (e.g. RoPE
|
||||
validation for configs with nested ``rope_parameters``), we fall
|
||||
back to loading the repo's self-contained ``tokenizer.json``
|
||||
directly — see ``_load_tokenizer_via_auto``.
|
||||
|
||||
Canonical Meta Llama-3.2 Instruct repos are gated on HuggingFace. For
|
||||
those exact IDs we load tokenizer files from the audited unrestricted
|
||||
``unsloth`` mirrors instead, then restore ``tokenizer.name_or_path`` to
|
||||
the requested Meta ID so auto-resolution still selects ``Llama3Renderer``.
|
||||
"""
|
||||
kwargs: dict[str, Any] = {}
|
||||
revision = TRUSTED_REVISIONS.get(model_name_or_path)
|
||||
if revision is not None:
|
||||
kwargs = {"trust_remote_code": True, "revision": revision}
|
||||
else:
|
||||
kwargs = {"trust_remote_code": False}
|
||||
|
||||
if not use_fastokens or model_name_or_path in FASTOKENS_INCOMPATIBLE:
|
||||
return _load_tokenizer_via_auto(model_name_or_path, **kwargs)
|
||||
|
||||
try:
|
||||
return _patched_load(model_name_or_path, **kwargs)
|
||||
except Exception as exc:
|
||||
logger.info(
|
||||
"fastokens could not load %r (%s: %s); falling back to vanilla "
|
||||
"AutoTokenizer. Add this model to FASTOKENS_INCOMPATIBLE in "
|
||||
"renderers.base to suppress the retry.",
|
||||
model_name_or_path,
|
||||
type(exc).__name__,
|
||||
str(exc)[:160],
|
||||
)
|
||||
return _load_tokenizer_via_auto(model_name_or_path, **kwargs)
|
||||
load_name_or_path = _tokenizer_source_for(model_name_or_path)
|
||||
kwargs = _tokenizer_load_kwargs(load_name_or_path)
|
||||
tok = _load_tokenizer_via_auto(load_name_or_path, **kwargs)
|
||||
return _preserve_requested_tokenizer_name(
|
||||
tok,
|
||||
requested_name_or_path=model_name_or_path,
|
||||
loaded_name_or_path=load_name_or_path,
|
||||
)
|
||||
|
||||
|
||||
def _populate_registry():
|
||||
@@ -1345,12 +1312,14 @@ def _populate_registry():
|
||||
from renderers.glm5 import GLM5Renderer, GLM51Renderer
|
||||
from renderers.glm45 import GLM45Renderer
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.hy3 import Hy3Renderer
|
||||
from renderers.kimi_k2 import KimiK2Renderer
|
||||
from renderers.kimi_k25 import KimiK25Renderer
|
||||
from renderers.laguna_xs2 import LagunaXS2Renderer
|
||||
from renderers.laguna_xs2 import LagunaXS2Renderer, LagunaXS21Renderer
|
||||
from renderers.llama_3 import Llama3Renderer
|
||||
from renderers.minimax_m2 import MiniMaxM2Renderer
|
||||
from renderers.nemotron3 import Nemotron3Renderer
|
||||
from renderers.nemotron3 import Nemotron3Renderer, Nemotron3UltraRenderer
|
||||
from renderers.prime_qwen3 import PrimeQwen3Renderer
|
||||
from renderers.qwen3 import Qwen3Renderer
|
||||
from renderers.qwen3_vl import Qwen3VLRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
@@ -1360,6 +1329,7 @@ def _populate_registry():
|
||||
{
|
||||
"default": DefaultRenderer,
|
||||
"qwen3": Qwen3Renderer,
|
||||
"prime-qwen3": PrimeQwen3Renderer,
|
||||
"qwen3-vl": Qwen3VLRenderer,
|
||||
"qwen3.5": Qwen35Renderer,
|
||||
"qwen3.6": Qwen36Renderer,
|
||||
@@ -1369,11 +1339,14 @@ def _populate_registry():
|
||||
"minimax-m2": MiniMaxM2Renderer,
|
||||
"deepseek-v3": DeepSeekV3Renderer,
|
||||
"deepseek-r1": DeepSeekR1Renderer,
|
||||
"hy3": Hy3Renderer,
|
||||
"kimi-k2": KimiK2Renderer,
|
||||
"kimi-k2.5": KimiK25Renderer,
|
||||
"laguna-xs.2": LagunaXS2Renderer,
|
||||
"laguna-xs-2.1": LagunaXS21Renderer,
|
||||
"llama-3": Llama3Renderer,
|
||||
"nemotron-3": Nemotron3Renderer,
|
||||
"nemotron-3-ultra": Nemotron3UltraRenderer,
|
||||
"gpt-oss": GptOssRenderer,
|
||||
}
|
||||
)
|
||||
@@ -1384,6 +1357,7 @@ def create_renderer_pool(
|
||||
config: RendererConfig | None = None,
|
||||
*,
|
||||
size: int = 16,
|
||||
chat_template_kwargs: Mapping[str, Any] | None = None,
|
||||
) -> RendererPool:
|
||||
"""Create a RendererPool with *size* independent tokenizer copies.
|
||||
|
||||
@@ -1395,8 +1369,10 @@ def create_renderer_pool(
|
||||
: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.
|
||||
tokenizer's name. ``chat_template_kwargs`` are merged into the
|
||||
resolved concrete config and validated before renderer construction.
|
||||
Every slot in the pool shares the same config; to run a different
|
||||
config, build a different pool.
|
||||
|
||||
Tokenizers load via ``load_tokenizer`` — see its docstring for the
|
||||
``trust_remote_code`` policy (default off; Moonshot Kimi-K2 family
|
||||
@@ -1405,7 +1381,11 @@ def create_renderer_pool(
|
||||
|
||||
def factory() -> Renderer:
|
||||
tokenizer = load_tokenizer(tokenizer_name_or_path)
|
||||
return create_renderer(tokenizer, config)
|
||||
return create_renderer(
|
||||
tokenizer,
|
||||
config,
|
||||
chat_template_kwargs=chat_template_kwargs,
|
||||
)
|
||||
|
||||
return RendererPool(factory, size=size)
|
||||
|
||||
@@ -1413,6 +1393,8 @@ def create_renderer_pool(
|
||||
def create_renderer(
|
||||
tokenizer,
|
||||
config: RendererConfig | None = None,
|
||||
*,
|
||||
chat_template_kwargs: Mapping[str, Any] | None = None,
|
||||
) -> Renderer:
|
||||
"""Create a Renderer from a typed config.
|
||||
|
||||
@@ -1428,33 +1410,77 @@ def create_renderer(
|
||||
template-control kwargs (e.g. ``enable_thinking``), pass
|
||||
the specific :class:`Qwen3RendererConfig`,
|
||||
:class:`GLM5RendererConfig` etc. and set those fields.
|
||||
chat_template_kwargs: Optional per-run chat-template kwargs. When
|
||||
``config`` is auto/``None``, renderers first resolves the concrete
|
||||
config from ``tokenizer.name_or_path`` and then validates these
|
||||
kwargs against that config.
|
||||
|
||||
Selecting the auto-renderer for a model without a registered
|
||||
renderer falls back to :class:`DefaultRenderer` for text-only models
|
||||
and raises for VLMs (where ``apply_chat_template`` would silently
|
||||
drop images).
|
||||
"""
|
||||
from renderers.configs import AutoRendererConfig
|
||||
|
||||
_populate_registry()
|
||||
|
||||
config = _resolve_renderer_config(
|
||||
tokenizer,
|
||||
config,
|
||||
chat_template_kwargs=chat_template_kwargs,
|
||||
)
|
||||
cls = RENDERER_REGISTRY.get(config.name)
|
||||
if cls is None:
|
||||
raise ValueError(
|
||||
f"Unknown renderer {config.name!r}. Available: {', '.join(sorted(RENDERER_REGISTRY))}"
|
||||
)
|
||||
return cls(tokenizer, config)
|
||||
|
||||
|
||||
def _merge_chat_template_kwargs(
|
||||
config: RendererConfig,
|
||||
chat_template_kwargs: Mapping[str, Any] | None,
|
||||
) -> RendererConfig:
|
||||
if not chat_template_kwargs:
|
||||
return config
|
||||
if not isinstance(chat_template_kwargs, Mapping):
|
||||
raise TypeError("chat_template_kwargs must be a mapping.")
|
||||
data: dict[str, Any] = {"name": config.name}
|
||||
for field_name in config.__pydantic_fields_set__:
|
||||
data[field_name] = getattr(config, field_name)
|
||||
data.update(getattr(config, "model_extra", None) or {})
|
||||
data.update(dict(chat_template_kwargs))
|
||||
return type(config).model_validate(data)
|
||||
|
||||
|
||||
def _resolve_renderer_config(
|
||||
tokenizer,
|
||||
config: RendererConfig | None,
|
||||
*,
|
||||
chat_template_kwargs: Mapping[str, Any] | None = None,
|
||||
) -> RendererConfig:
|
||||
"""Resolve auto/default config and merge chat-template kwargs."""
|
||||
from renderers.configs import AutoRendererConfig
|
||||
|
||||
if config is None:
|
||||
config = AutoRendererConfig()
|
||||
|
||||
if not isinstance(config, AutoRendererConfig):
|
||||
cls = RENDERER_REGISTRY.get(config.name)
|
||||
if cls is None:
|
||||
raise ValueError(
|
||||
f"Unknown renderer {config.name!r}. Available: {', '.join(sorted(RENDERER_REGISTRY))}"
|
||||
)
|
||||
return cls(tokenizer, config)
|
||||
if isinstance(config, AutoRendererConfig):
|
||||
return _resolve_auto_config(
|
||||
tokenizer,
|
||||
config,
|
||||
chat_template_kwargs=chat_template_kwargs,
|
||||
)
|
||||
|
||||
return _resolve_auto(tokenizer, config)
|
||||
return _merge_chat_template_kwargs(config, chat_template_kwargs)
|
||||
|
||||
|
||||
def _resolve_auto(tokenizer, auto: AutoRendererConfig) -> Renderer:
|
||||
def _resolve_auto_config(
|
||||
tokenizer,
|
||||
auto: AutoRendererConfig,
|
||||
*,
|
||||
chat_template_kwargs: Mapping[str, Any] | None = None,
|
||||
) -> RendererConfig:
|
||||
"""Map ``AutoRendererConfig`` → concrete typed config via the
|
||||
tokenizer's ``name_or_path``, then instantiate the matching renderer.
|
||||
tokenizer's ``name_or_path``.
|
||||
|
||||
Fine-tunes and renamed checkpoints miss on purpose — their chat
|
||||
template may differ from the original even when the architecture
|
||||
@@ -1466,14 +1492,24 @@ def _resolve_auto(tokenizer, auto: AutoRendererConfig) -> Renderer:
|
||||
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,
|
||||
}
|
||||
preserve_carry = {}
|
||||
if auto.thinking_retention is not None:
|
||||
preserve_carry["thinking_retention"] = auto.thinking_retention
|
||||
|
||||
if renderer_name is not None:
|
||||
cfg_cls = _config_class_for(renderer_name)
|
||||
return RENDERER_REGISTRY[renderer_name](tokenizer, cfg_cls(**preserve_carry))
|
||||
return _merge_chat_template_kwargs(
|
||||
cfg_cls(**preserve_carry),
|
||||
chat_template_kwargs,
|
||||
)
|
||||
|
||||
if chat_template_kwargs:
|
||||
raise ValueError(
|
||||
"AutoRendererConfig cannot apply chat_template_kwargs for unknown "
|
||||
f"model {model_name!r}. Pass an explicit model-specific renderer "
|
||||
"config, or use DefaultRendererConfig explicitly for opaque "
|
||||
"apply_chat_template kwargs."
|
||||
)
|
||||
|
||||
# No match. For VLMs this must be fatal: DefaultRenderer only knows
|
||||
# ``apply_chat_template`` + text tokens, so it would silently drop
|
||||
@@ -1494,11 +1530,12 @@ def _resolve_auto(tokenizer, auto: AutoRendererConfig) -> Renderer:
|
||||
# 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.
|
||||
if auto.preserve_all_thinking or auto.preserve_thinking_between_tool_calls:
|
||||
if auto.thinking_retention is not None:
|
||||
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."
|
||||
"config (model-specific) if you need thinking_retention != "
|
||||
"'template'."
|
||||
)
|
||||
logger.info(
|
||||
"No model-specific renderer matched %r. Using DefaultRenderer "
|
||||
@@ -1506,7 +1543,7 @@ def _resolve_auto(tokenizer, auto: AutoRendererConfig) -> Renderer:
|
||||
"reasoning_parser=...) to enable structured output parsing.",
|
||||
model_name or "<unnamed tokenizer>",
|
||||
)
|
||||
return RENDERER_REGISTRY["default"](tokenizer, DefaultRendererConfig())
|
||||
return DefaultRendererConfig()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1514,6 +1551,42 @@ def _resolve_auto(tokenizer, auto: AutoRendererConfig) -> Renderer:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
# Match prime-rl's multimodal token type convention: 0=text, 1=image, 2=video.
|
||||
_MM_TYPE_ID: dict[str, int] = {"image": 1, "video": 2}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RenderedTrainingSample:
|
||||
"""Output of :func:`build_training_sample`.
|
||||
|
||||
``token_ids`` and ``loss_mask`` are always populated. ``multi_modal_data``
|
||||
and ``mm_token_type_ids`` are populated only when a multimodal renderer
|
||||
actually emitted media (both ``None`` for text-only renderers and for
|
||||
text-only samples through a VLM renderer), so the text path is unchanged.
|
||||
"""
|
||||
|
||||
token_ids: list[int]
|
||||
loss_mask: list[bool]
|
||||
multi_modal_data: "MultiModalData | None" = None
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
|
||||
|
||||
def _build_mm_token_type_ids(
|
||||
mm_placeholders: dict[str, list[PlaceholderRange]], length: int
|
||||
) -> list[int]:
|
||||
"""Per-token modality flags (0=text, 1=image, 2=video) from placeholder ranges."""
|
||||
ids = [0] * length
|
||||
for modality, ranges in mm_placeholders.items():
|
||||
type_id = _MM_TYPE_ID.get(modality, 0)
|
||||
if type_id == 0:
|
||||
continue
|
||||
for r in ranges:
|
||||
end = min(r.offset + r.length, length)
|
||||
for i in range(r.offset, end):
|
||||
ids[i] = type_id
|
||||
return ids
|
||||
|
||||
|
||||
def build_training_sample(
|
||||
renderer: Renderer,
|
||||
messages: list[Message],
|
||||
@@ -1521,8 +1594,13 @@ def build_training_sample(
|
||||
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.
|
||||
ensure_final_stop: bool = False,
|
||||
) -> RenderedTrainingSample:
|
||||
"""Build a :class:`RenderedTrainingSample` for supervised training.
|
||||
|
||||
Returns ``token_ids`` + ``loss_mask`` (always), plus ``multi_modal_data``
|
||||
and ``mm_token_type_ids`` when the renderer emitted media (``None`` for
|
||||
text — the text token_ids/loss_mask are byte-identical to before).
|
||||
|
||||
Single render() call + message_indices → per-token mask.
|
||||
Replaces build_incremental_token_mask (O(N) renders → O(1)).
|
||||
@@ -1572,6 +1650,17 @@ def build_training_sample(
|
||||
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.
|
||||
|
||||
``ensure_final_stop`` appends the renderer's canonical stop token
|
||||
when the sample ends with an assistant message that the template
|
||||
leaves unterminated. Some templates close an assistant turn only
|
||||
via the *next* message's role marker (e.g. GLM's ``<|user|>`` /
|
||||
``<|observation|>``), so a final assistant message renders with no
|
||||
stop token at all. No-op when the template already closes the turn
|
||||
in-message (ChatML ``<|im_end|>``, Llama ``<|eot_id|>``); where it
|
||||
fires, the output intentionally diverges from ``apply_chat_template``.
|
||||
Ignored for renderers without ``sampled_mask`` (``DefaultRenderer``) —
|
||||
the close of an opaque template can't be located reliably.
|
||||
"""
|
||||
rendered = renderer.render(messages, tools=tools)
|
||||
has_sampled_info = len(rendered.sampled_mask) == len(rendered.token_ids)
|
||||
@@ -1611,7 +1700,43 @@ def build_training_sample(
|
||||
loss_mask.append(True)
|
||||
else:
|
||||
loss_mask.append(role_to_mask(msg))
|
||||
return rendered.token_ids, loss_mask
|
||||
|
||||
token_ids = list(rendered.token_ids)
|
||||
# Requires sampled_mask (opaque templates hide the assistant close)
|
||||
# and a final assistant message the role filter trains.
|
||||
if (
|
||||
ensure_final_stop
|
||||
and has_sampled_info
|
||||
and messages[-1].get("role") == "assistant"
|
||||
and (role_to_mask is None or role_to_mask(messages[-1]))
|
||||
):
|
||||
stop_ids = set(renderer.get_stop_token_ids())
|
||||
last_trainable = next(
|
||||
(k for k in range(len(loss_mask) - 1, -1, -1) if loss_mask[k]), None
|
||||
)
|
||||
if last_trainable is None or token_ids[last_trainable] not in stop_ids:
|
||||
token_ids.append(renderer.get_stop_token_ids()[0])
|
||||
# loss_mask=True marks the token as trainable — the appended
|
||||
# stop is a training target, like any sampled token.
|
||||
loss_mask.append(True)
|
||||
|
||||
# Surface the multimodal payload for VLM renderers. ``None`` for text
|
||||
# renderers and for text-only samples (empty media) so downstream
|
||||
# ``multi_modal_data is not None`` is a reliable "has media" check.
|
||||
mm = rendered.multi_modal_data
|
||||
if mm is not None and mm.is_empty():
|
||||
mm = None
|
||||
mm_token_type_ids = (
|
||||
_build_mm_token_type_ids(mm.mm_placeholders, len(token_ids))
|
||||
if mm is not None and mm.mm_placeholders
|
||||
else None
|
||||
)
|
||||
return RenderedTrainingSample(
|
||||
token_ids=token_ids,
|
||||
loss_mask=loss_mask,
|
||||
multi_modal_data=mm,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
)
|
||||
|
||||
|
||||
def _common_prefix_len(a: list[int], b: list[int]) -> int:
|
||||
@@ -1657,77 +1782,35 @@ 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``.
|
||||
"""Assert ``tokenizer`` 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.
|
||||
Hand-coded renderers concatenate scaffold + body in one BPE pass to
|
||||
preserve cross-boundary merges, then attribute each resulting token
|
||||
back to its source segment via the fast tokenizer's
|
||||
``offset_mapping`` (see :func:`attribute_text_segments`). The
|
||||
contract: every BYO tokenizer must be a fast tokenizer with offset
|
||||
support. Tokenizers loaded via :func:`load_tokenizer` are
|
||||
``PreTrainedTokenizerFast`` instances that satisfy this trivially.
|
||||
"""
|
||||
# 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:
|
||||
except (NotImplementedError, ValueError, TypeError) as exc:
|
||||
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
|
||||
|
||||
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; routing through
|
||||
# ``_load_tokenizer_via_auto`` keeps the fastokens patch out
|
||||
# of this code path while still applying the config-build
|
||||
# fallback (RoPE-validation failures on nested
|
||||
# ``rope_parameters``, etc.).
|
||||
offset_tok = _load_tokenizer_via_auto(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
|
||||
"Hand-coded renderers require a fast tokenizer with "
|
||||
"``return_offsets_mapping=True`` support for body/scaffold "
|
||||
"attribution. Pass a tokenizer loaded via "
|
||||
"``renderers.base.load_tokenizer``, or any "
|
||||
"``transformers.PreTrainedTokenizerFast`` instance."
|
||||
) from exc
|
||||
return tokenizer
|
||||
|
||||
|
||||
def attribute_text_segments(
|
||||
tokenizer,
|
||||
segments: "list[tuple[str, bool]]",
|
||||
*,
|
||||
overlap_is_content: bool = False,
|
||||
) -> "list[tuple[int, bool]]":
|
||||
"""Tokenize concatenated segments as a single BPE pass and return
|
||||
``(token_id, is_content)`` pairs.
|
||||
@@ -1746,14 +1829,23 @@ def attribute_text_segments(
|
||||
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.
|
||||
``overlap_is_content=True`` widens the content bit: a token counts
|
||||
as content when *any* of its source characters fall in a content
|
||||
segment, not just its first. Templates whose wrap glues directly
|
||||
onto the body with no whitespace (e.g. ``<user>{content}</user>``)
|
||||
can merge wrap and body bytes into one token; under the first-char
|
||||
policy such a token would land on the wrap side and the body would
|
||||
no longer be recoverable from the content run. Over-inclusion keeps
|
||||
every body byte inside the ``is_content=True`` run at the cost of a
|
||||
few adjacent wrap bytes.
|
||||
|
||||
Requires a HuggingFace fast tokenizer with offset tracking. Every
|
||||
model in ``MODEL_RENDERER_MAP`` ships one, so the offset lookup
|
||||
always succeeds for tokenizers obtained via :func:`load_tokenizer`.
|
||||
BYO tokenizers must be a ``PreTrainedTokenizerFast`` (or anything
|
||||
else exposing ``return_offsets_mapping=True``); slow tokenizers
|
||||
aren't supported — BPE drift at the wrap/body boundary would
|
||||
defeat the whole point.
|
||||
|
||||
Empty input or empty joined text returns an empty list.
|
||||
"""
|
||||
@@ -1783,13 +1875,25 @@ def attribute_text_segments(
|
||||
|
||||
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):
|
||||
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
|
||||
if overlap_is_content and end > start:
|
||||
out.append(
|
||||
(
|
||||
tok_id,
|
||||
any(
|
||||
seg_is_content
|
||||
for seg_start, seg_end, seg_is_content in spans
|
||||
if seg_start < end and start < seg_end
|
||||
),
|
||||
)
|
||||
)
|
||||
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
|
||||
@@ -1819,51 +1923,52 @@ def reject_assistant_in_extension(new_messages: list[Message]) -> bool:
|
||||
return any(m.get("role") == "assistant" for m in new_messages)
|
||||
|
||||
|
||||
def should_preserve_past_thinking(
|
||||
messages: list[Message],
|
||||
msg_idx: int,
|
||||
def _is_user_message(message: Message) -> bool:
|
||||
return message.get("role") == "user"
|
||||
|
||||
|
||||
def introduces_user_query(
|
||||
new_messages: list[Message],
|
||||
*,
|
||||
preserve_all_thinking: bool,
|
||||
preserve_thinking_between_tool_calls: bool,
|
||||
is_user_query: Callable[[Message], bool] = _is_user_message,
|
||||
) -> bool:
|
||||
"""Should ``messages[msg_idx]``'s ``reasoning_content`` be emitted as
|
||||
thinking even when the chat template would drop it?
|
||||
"""Return True if ``new_messages`` opens a new user-query turn.
|
||||
|
||||
Returns ``True`` only as an override above the template default. Each
|
||||
renderer ORs this into its own "render thinking?" condition; a result
|
||||
of ``False`` means "follow the template" (drop or keep as the template
|
||||
decides), not "force-drop".
|
||||
|
||||
Override rules:
|
||||
|
||||
- ``preserve_all_thinking`` — every past-asst's thinking is kept.
|
||||
- ``preserve_thinking_between_tool_calls`` — keeps thinking only
|
||||
inside the *current* tool cycle: the contiguous A-T-...-A block
|
||||
after the most recent ``user`` message, and only if that block
|
||||
contains at least one ``tool`` response. As soon as a new
|
||||
``user`` turn arrives, the previous block becomes "older" and
|
||||
its thinking is dropped (template default), matching how most
|
||||
chat templates already handle multi-turn contexts. Use
|
||||
``preserve_all_thinking`` if you need thinking on older blocks
|
||||
to survive the user-turn boundary too.
|
||||
The generic boundary is any ``role="user"`` message. Renderers whose
|
||||
chat templates define a narrower notion of query boundary can pass their
|
||||
own predicate, but the shared default stays role-based.
|
||||
"""
|
||||
if preserve_all_thinking:
|
||||
return any(is_user_query(m) for m in new_messages)
|
||||
|
||||
|
||||
def resolve_thinking_retention(
|
||||
config: Any,
|
||||
implied: ResolvedThinkingRetention,
|
||||
) -> ResolvedThinkingRetention:
|
||||
"""Resolve the effective bridge policy for a renderer instance.
|
||||
|
||||
``config.thinking_retention is None`` means "derive from template knobs";
|
||||
otherwise the explicit generic bridge policy wins. Conflicting explicit
|
||||
template/generic knobs are rejected by the typed config validators.
|
||||
"""
|
||||
requested = getattr(config, "thinking_retention", None)
|
||||
if requested is None:
|
||||
return implied
|
||||
return requested
|
||||
|
||||
|
||||
def should_rerender_for_thinking_retention(
|
||||
thinking_retention: ResolvedThinkingRetention,
|
||||
new_messages: list[Message],
|
||||
*,
|
||||
is_user_query: Callable[[Message], bool] = _is_user_message,
|
||||
) -> bool:
|
||||
"""Return True when the resolved policy requires a full re-render."""
|
||||
if thinking_retention == "template":
|
||||
return True
|
||||
if not preserve_thinking_between_tool_calls:
|
||||
if thinking_retention == "all":
|
||||
return False
|
||||
# Most recent user message (or -1 if none).
|
||||
last_user = -1
|
||||
for j in range(len(messages) - 1, -1, -1):
|
||||
if messages[j].get("role") == "user":
|
||||
last_user = j
|
||||
break
|
||||
if msg_idx <= last_user:
|
||||
return False
|
||||
# The current segment must contain a tool response for it to count
|
||||
# as an in-flight tool cycle.
|
||||
return any(
|
||||
messages[j].get("role") == "tool" for j in range(last_user + 1, len(messages))
|
||||
)
|
||||
return introduces_user_query(new_messages, is_user_query=is_user_query)
|
||||
|
||||
|
||||
def build_trajectory_step(
|
||||
@@ -1901,6 +2006,7 @@ def build_trajectory_step(
|
||||
"completion_mask": [True] * len(completion_ids),
|
||||
"completion_logprobs": [0.0] * len(completion_ids),
|
||||
"routed_experts": None,
|
||||
"kept_tokens": None,
|
||||
}
|
||||
if (
|
||||
full_rendered.multi_modal_data is not None
|
||||
|
||||
+17
-6
@@ -32,6 +32,7 @@ from renderers.base import (
|
||||
|
||||
_request_logger = logging.getLogger("renderers.client")
|
||||
ROUTED_EXPERTS_DATA_PREFIX = b'"routed_experts":{"data":"'
|
||||
KEPT_TOKENS_IDS_PREFIX = b'"kept_tokens":{"ids":"'
|
||||
|
||||
|
||||
class OverlongPromptError(Exception):
|
||||
@@ -121,23 +122,31 @@ 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)
|
||||
def _strip_base64_field(raw: bytes, prefix: bytes) -> tuple[bytes, memoryview | None]:
|
||||
"""Splice a large base64 string field out of raw JSON bytes.
|
||||
|
||||
Avoids json-decoding megabytes of base64; the returned memoryview
|
||||
references ``raw`` and is re-inserted into the parsed payload.
|
||||
"""
|
||||
data_start = raw.find(prefix)
|
||||
if data_start < 0:
|
||||
return raw, None
|
||||
|
||||
data_start += len(ROUTED_EXPERTS_DATA_PREFIX)
|
||||
data_start += len(prefix)
|
||||
data_end = raw.index(b'"', data_start)
|
||||
routed_data = memoryview(raw)[data_start:data_end]
|
||||
data = memoryview(raw)[data_start:data_end]
|
||||
stripped = raw[:data_start] + raw[data_end:]
|
||||
return stripped, routed_data
|
||||
return stripped, data
|
||||
|
||||
|
||||
def parse_generate_response(raw: bytes) -> dict[str, Any]:
|
||||
stripped, routed_data = strip_routed_experts_data(raw)
|
||||
stripped, routed_data = _strip_base64_field(raw, ROUTED_EXPERTS_DATA_PREFIX)
|
||||
stripped, kept_ids_data = _strip_base64_field(stripped, KEPT_TOKENS_IDS_PREFIX)
|
||||
payload: dict[str, Any] = json.loads(stripped)
|
||||
if routed_data is not None:
|
||||
payload["choices"][0]["routed_experts"]["data"] = routed_data
|
||||
if kept_ids_data is not None:
|
||||
payload["choices"][0]["kept_tokens"]["ids"] = kept_ids_data
|
||||
return payload
|
||||
|
||||
|
||||
@@ -293,6 +302,7 @@ async def generate(
|
||||
completion_logprobs = [float(c.get("logprob") or 0.0) for c in content_lp or []]
|
||||
|
||||
routed_experts = choice.get("routed_experts")
|
||||
kept_tokens = choice.get("kept_tokens")
|
||||
|
||||
# /inference/v1/generate returns finish_reason in {"stop","length",...} —
|
||||
# never "tool_calls" (a chat-completions concept). Promote stop→tool_calls
|
||||
@@ -319,6 +329,7 @@ async def generate(
|
||||
"tool_calls": parsed.tool_calls,
|
||||
"finish_reason": finish_reason,
|
||||
"routed_experts": routed_experts,
|
||||
"kept_tokens": kept_tokens,
|
||||
# The mm sidecar consumed on the request side, surfaced back so
|
||||
# callers can persist it on the trajectory step for downstream
|
||||
# multi-turn bridging and training-sample construction.
|
||||
|
||||
+308
-70
@@ -4,14 +4,14 @@ 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.
|
||||
check. The shared ``thinking_retention`` flag is optional: ``None`` means
|
||||
"derive bridge policy from this renderer's chat-template knobs"; an
|
||||
explicit value is a bridge-policy override.
|
||||
|
||||
``AutoRendererConfig`` is a placeholder variant: ``create_renderer``
|
||||
resolves it via ``MODEL_RENDERER_MAP`` and constructs the matching
|
||||
typed config with the auto config's ``preserve_*`` fields carried over.
|
||||
typed config with the auto config's ``thinking_retention`` field carried
|
||||
over when one was explicitly supplied.
|
||||
|
||||
``DefaultRendererConfig`` uses ``extra="allow"`` to accept arbitrary
|
||||
Jinja kwargs as ``model_extra`` — ``DefaultRenderer`` doesn't know which
|
||||
@@ -22,10 +22,40 @@ from __future__ import annotations
|
||||
|
||||
from typing import Annotated, ClassVar, Literal, Union
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
from pydantic import ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
|
||||
def _reject_thinking_retention_conflict(
|
||||
config: BaseConfig,
|
||||
kwarg_name: str,
|
||||
*,
|
||||
true_implies: "ResolvedThinkingRetention",
|
||||
false_implies: "ResolvedThinkingRetention",
|
||||
) -> None:
|
||||
"""Raise if explicit template and renderer retention knobs disagree."""
|
||||
fields_set = config.__pydantic_fields_set__
|
||||
requested = getattr(config, "thinking_retention", None)
|
||||
if kwarg_name in fields_set and requested is not None:
|
||||
implied = (
|
||||
false_implies if getattr(config, kwarg_name) is False else true_implies
|
||||
)
|
||||
if requested == implied:
|
||||
return
|
||||
raise ValueError(
|
||||
f"{kwarg_name}={getattr(config, kwarg_name)!r} implies "
|
||||
f"thinking_retention={implied!r}, which conflicts with explicit "
|
||||
f"thinking_retention={requested!r}."
|
||||
)
|
||||
|
||||
|
||||
ThinkingRetention = Literal["tool_cycle", "all"]
|
||||
"""User-facing historical thinking/analysis retention override."""
|
||||
|
||||
ResolvedThinkingRetention = Literal["template", "tool_cycle", "all"]
|
||||
"""Internal bridge policy after template kwargs have been resolved."""
|
||||
|
||||
|
||||
class BaseRendererConfig(BaseConfig):
|
||||
"""Shared fields and config for every renderer config variant.
|
||||
|
||||
@@ -35,28 +65,27 @@ class BaseRendererConfig(BaseConfig):
|
||||
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``.
|
||||
``thinking_retention`` is an optional renderer-level retention override.
|
||||
Leave it ``None`` to derive the effective policy from the renderer's own
|
||||
chat-template knobs. Set it explicitly to request retention beyond the
|
||||
template default; renderers fail loudly when an explicit template knob says
|
||||
the opposite thing.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
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``."""
|
||||
thinking_retention: ThinkingRetention | None = None
|
||||
"""Explicit retention override, or ``None`` to derive from template knobs:
|
||||
|
||||
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)."""
|
||||
- ``None`` — derive the effective bridge policy from this renderer's
|
||||
chat-template knobs while keeping full renders template-faithful.
|
||||
- ``"tool_cycle"`` — bridge within the current tool cycle; re-render when
|
||||
a new user query arrives.
|
||||
- ``"all"`` — allow bridges across user-query boundaries.
|
||||
|
||||
This does not change full ``render()`` output; full renders stay faithful
|
||||
to the Python chat-template implementation and its explicit template
|
||||
kwargs."""
|
||||
|
||||
# Fields that are renderer-internal — not forwarded to (or mirrored
|
||||
# by) ``apply_chat_template``. Override in subclasses that hold
|
||||
@@ -87,9 +116,10 @@ class BaseRendererConfig(BaseConfig):
|
||||
|
||||
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."""
|
||||
time via ``MODEL_RENDERER_MAP``. Carries only the shared
|
||||
``thinking_retention`` field when explicitly set; template kwargs require
|
||||
an explicit renderer choice so template-dependent behaviour stays visible
|
||||
at the call site."""
|
||||
|
||||
name: Literal["auto"] = "auto"
|
||||
|
||||
@@ -119,6 +149,26 @@ class DefaultRendererConfig(BaseRendererConfig):
|
||||
# template. Jinja kwargs live in ``model_extra`` (extra="allow").
|
||||
_internal_fields = frozenset({"tool_parser", "reasoning_parser"})
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _reject_legacy_preserve_flags(self):
|
||||
# ``extra="allow"`` would otherwise swallow the removed ``preserve_*``
|
||||
# bools into ``model_extra`` and forward them to apply_chat_template,
|
||||
# silently dropping the user's intent (DefaultRenderer can't
|
||||
# selectively re-emit reasoning_content). Reject them like every other
|
||||
# config's ``extra="forbid"`` does, pointing at the replacement.
|
||||
legacy = {
|
||||
"preserve_all_thinking",
|
||||
"preserve_thinking_between_tool_calls",
|
||||
} & set(self.model_extra or {})
|
||||
if legacy:
|
||||
raise ValueError(
|
||||
f"{sorted(legacy)} were replaced by thinking_retention. "
|
||||
"DefaultRenderer falls back to apply_chat_template and can't "
|
||||
"selectively re-emit reasoning_content — use thinking_retention "
|
||||
"on a model-specific renderer."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class Qwen3RendererConfig(BaseRendererConfig):
|
||||
"""Qwen3 (text-only) renderer config."""
|
||||
@@ -131,6 +181,12 @@ class Qwen3RendererConfig(BaseRendererConfig):
|
||||
``enable_thinking`` kwarg."""
|
||||
|
||||
|
||||
class PrimeQwen3RendererConfig(BaseRendererConfig):
|
||||
"""PrimeIntellect Qwen3 renderer config."""
|
||||
|
||||
name: Literal["prime-qwen3"] = "prime-qwen3"
|
||||
|
||||
|
||||
class Qwen35RendererConfig(BaseRendererConfig):
|
||||
"""Qwen3.5 renderer config."""
|
||||
|
||||
@@ -166,11 +222,26 @@ class Qwen36RendererConfig(BaseRendererConfig):
|
||||
add_vision_id: bool = False
|
||||
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
|
||||
|
||||
preserve_thinking: bool = False
|
||||
"""When ``True``, keep historical ``<think>`` blocks even before the
|
||||
last real user query. Mirrors the Qwen3.6 chat template's native
|
||||
``preserve_thinking`` kwarg."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"preserve_thinking",
|
||||
true_implies="all",
|
||||
false_implies="tool_cycle",
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class Qwen3VLRendererConfig(BaseRendererConfig):
|
||||
"""Qwen3-VL renderer config."""
|
||||
@@ -198,9 +269,18 @@ class GLM5RendererConfig(BaseRendererConfig):
|
||||
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."""
|
||||
chat template's ``clear_thinking`` toggle and resolves bridge policy
|
||||
to ``"all"``."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"clear_thinking",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class GLM51RendererConfig(BaseRendererConfig):
|
||||
@@ -215,6 +295,16 @@ class GLM51RendererConfig(BaseRendererConfig):
|
||||
clear_thinking: bool = True
|
||||
"""See :class:`GLM5RendererConfig.clear_thinking`."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"clear_thinking",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class GLM45RendererConfig(BaseRendererConfig):
|
||||
"""GLM-4.5 Air renderer config."""
|
||||
@@ -226,6 +316,70 @@ class GLM45RendererConfig(BaseRendererConfig):
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
|
||||
class Hy3RendererConfig(BaseRendererConfig):
|
||||
"""Tencent Hunyuan Hy3 renderer config.
|
||||
|
||||
Hy3 reasons via a ``reasoning_effort`` gate rather than a boolean
|
||||
``enable_thinking``. ``"no_think"`` (the template default) prefills an
|
||||
empty ``<think></think>`` at the generation prompt so the model answers
|
||||
directly; ``"low"`` / ``"high"`` prefill only the ``<think>`` opener so
|
||||
the model streams reasoning up to a ``</think>`` it emits itself.
|
||||
|
||||
``preserved_thinking`` mirrors the template kwarg of the same name:
|
||||
``True`` keeps ``<think>{reasoning}</think>`` on every historical
|
||||
assistant turn; ``False`` collapses past-cycle reasoning to
|
||||
``<think></think>``, keeping it only on the in-flight turn (after the
|
||||
last user query). ``None`` (default) follows the template's own
|
||||
default — ``True`` when ``tools`` are supplied at render time, ``False``
|
||||
otherwise. Bridge policy tracks the same resolution: ``"all"`` whenever
|
||||
``preserved_thinking`` resolves to ``True`` for the tools at hand,
|
||||
``"tool_cycle"`` otherwise.
|
||||
"""
|
||||
|
||||
name: Literal["hy3"] = "hy3"
|
||||
|
||||
reasoning_effort: Literal["no_think", "low", "high"] = "no_think"
|
||||
"""Reasoning gate. Mirrors the chat template's ``reasoning_effort`` kwarg.
|
||||
``"no_think"`` prefills ``<think></think>`` at the generation prompt;
|
||||
``"low"`` / ``"high"`` prefill just ``<think>``."""
|
||||
|
||||
preserved_thinking: bool | None = None
|
||||
"""Keep historical assistant reasoning. Mirrors the template's
|
||||
``preserved_thinking`` kwarg. ``None`` defers to the template default
|
||||
(``True`` with tools, ``False`` without). Bridge policy is ``"all"``
|
||||
whenever this resolves to ``True`` for the tools at hand."""
|
||||
|
||||
is_training: bool = False
|
||||
"""Mirrors the template's ``is_training`` kwarg. ``True`` renders SFT
|
||||
targets: reasoning is kept on every assistant turn (regardless of
|
||||
``preserved_thinking`` / position) and the final assistant is terminated
|
||||
with ``<|hy_eos|>``. Leave ``False`` for inference-faithful renders;
|
||||
the training loss mask is normally derived via ``build_training_sample``
|
||||
rather than this flag."""
|
||||
|
||||
raw_last_assistant: bool = False
|
||||
"""Mirrors the template's ``raw_last_assistant`` kwarg. When ``True`` a
|
||||
trailing non-tool assistant message is emitted as raw visible content —
|
||||
no ``<think>`` wrap, no ``<|hy_eos|>`` — for prefill / continuation."""
|
||||
|
||||
fallback_strategy: Literal["reasoning_toolcall_retry"] | None = None
|
||||
"""Mirrors the template's ``fallback_strategy`` kwarg. The sole active
|
||||
value, ``"reasoning_toolcall_retry"``, forces ``reasoning_effort="high"``
|
||||
and suppresses the generation prompt (``add_generation_prompt=False``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
if self.preserved_thinking is not None and self.thinking_retention is not None:
|
||||
implied = "all" if self.preserved_thinking else "tool_cycle"
|
||||
if self.thinking_retention != implied:
|
||||
raise ValueError(
|
||||
f"preserved_thinking={self.preserved_thinking!r} implies "
|
||||
f"thinking_retention={implied!r}, which conflicts with "
|
||||
f"explicit thinking_retention={self.thinking_retention!r}."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class GptOssRendererConfig(BaseRendererConfig):
|
||||
"""OpenAI gpt-oss (harmony) renderer config.
|
||||
|
||||
@@ -260,10 +414,30 @@ class GptOssRendererConfig(BaseRendererConfig):
|
||||
"""Override the model-identity line in the preamble. ``None`` uses
|
||||
harmony's built-in default."""
|
||||
|
||||
auto_drop_analysis: bool = True
|
||||
"""Harmony ``RenderConversationConfig.auto_drop_analysis`` behaviour.
|
||||
``True`` keeps live tool-cycle analysis but drops stale analysis from
|
||||
history; ``False`` keeps analysis in all history."""
|
||||
|
||||
_internal_fields = frozenset(
|
||||
{"use_system_prompt", "knowledge_cutoff", "model_identity"}
|
||||
{
|
||||
"use_system_prompt",
|
||||
"knowledge_cutoff",
|
||||
"model_identity",
|
||||
"auto_drop_analysis",
|
||||
}
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"auto_drop_analysis",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class KimiK2RendererConfig(BaseRendererConfig):
|
||||
"""Kimi K2 renderer config.
|
||||
@@ -318,13 +492,33 @@ class LagunaXS2RendererConfig(BaseRendererConfig):
|
||||
chat template's ``render_assistant_messages_raw`` gate."""
|
||||
|
||||
|
||||
class LagunaXS21RendererConfig(BaseRendererConfig):
|
||||
"""Laguna XS-2.1 renderer config.
|
||||
|
||||
XS-2.1's chat template reads a single kwarg, ``enable_thinking``,
|
||||
which gates both the generation prompt (``<think>`` vs ``</think>``)
|
||||
and whether assistant reasoning is rendered into the history at all.
|
||||
Served by :class:`renderers.laguna_xs2.LagunaXS21Renderer`.
|
||||
"""
|
||||
|
||||
name: Literal["laguna-xs-2.1"] = "laguna-xs-2.1"
|
||||
|
||||
enable_thinking: bool = False
|
||||
"""When ``True``, the generation prompt ends with ``<think>`` and
|
||||
every assistant turn renders ``<think>{reasoning}</think>``; when
|
||||
``False``, turns open with a bare ``</think>`` and reasoning is not
|
||||
rendered. Mirrors the template's ``enable_thinking`` kwarg and its
|
||||
upstream default."""
|
||||
|
||||
|
||||
class Llama3RendererConfig(BaseRendererConfig):
|
||||
"""Llama-3.x Instruct renderer config.
|
||||
|
||||
Llama-3 ships no reasoning channel, so the base ``preserve_*_thinking``
|
||||
flags don't apply: ``Llama3Renderer`` raises ``NotImplementedError``
|
||||
if either is set (matching ``DefaultRenderer``'s contract for the
|
||||
same case). Both fields below mirror real ``apply_chat_template``
|
||||
Llama-3 ships no reasoning channel, so the base ``thinking_retention``
|
||||
flag is a no-op: there's never any past-assistant thinking to retain
|
||||
or drop, so any level leaves the token stream unchanged (same contract
|
||||
as Kimi-K2 / Qwen3-VL). Both fields below mirror real
|
||||
``apply_chat_template``
|
||||
kwargs.
|
||||
"""
|
||||
|
||||
@@ -354,7 +548,14 @@ class MiniMaxM2RendererConfig(BaseRendererConfig):
|
||||
|
||||
|
||||
class Nemotron3RendererConfig(BaseRendererConfig):
|
||||
"""Nemotron 3 renderer config."""
|
||||
"""Nemotron-3 **Nano / Super** renderer config.
|
||||
|
||||
Nano and Super share one chat-template variant; the renderer routes both
|
||||
through :class:`renderers.nemotron3.Nemotron3Renderer`. The Ultra variant
|
||||
has its own template (different reasoning-block glue) and config —
|
||||
:class:`Nemotron3UltraRendererConfig` — and is reached via the
|
||||
``nemotron-3-ultra`` discriminator.
|
||||
"""
|
||||
|
||||
name: Literal["nemotron-3"] = "nemotron-3"
|
||||
|
||||
@@ -362,41 +563,63 @@ class Nemotron3RendererConfig(BaseRendererConfig):
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
ultra: bool | None = None
|
||||
"""Select the Nemotron-3 **Ultra** chat-template variant.
|
||||
|
||||
``None`` (default) auto-detects from the model name (see
|
||||
``renderers.nemotron3._ULTRA_DEFAULTS``): the Ultra checkpoints resolve
|
||||
to ``True``; Nano / Super and unknown checkpoints to ``False``. Set
|
||||
explicitly to force a variant — e.g. an Ultra fine-tune or a
|
||||
locally-pathed checkpoint whose ``name_or_path`` isn't in the table.
|
||||
|
||||
Ultra's template differs from Nano/Super: the reasoning block is glued
|
||||
as ``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around
|
||||
``</think>``), truncated historical turns collapse to
|
||||
``<think></think>{content}`` (no ``\\n``), and the thinking-truncation
|
||||
boundary follows the template's ``loop.index0 < last_user_idx`` rule
|
||||
(drop thinking on every assistant turn before the last user message).
|
||||
|
||||
Not a chat-template kwarg — it picks which template the renderer
|
||||
mirrors, not a variable passed into one — so it's listed in
|
||||
``_internal_fields`` and excluded from ``template_field_names()``."""
|
||||
|
||||
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."""
|
||||
template's ``truncate_history_thinking`` toggle and resolves bridge
|
||||
policy to ``"all"``."""
|
||||
|
||||
# ``ultra`` is a template-variant SELECTOR — it picks which template the
|
||||
# renderer mirrors (Ultra vs Nano/Super), not a variable passed into one;
|
||||
# there is no ``ultra`` Jinja variable. Marked internal so the parity
|
||||
# matrix doesn't cross it as a template field. Same ``_internal_fields``
|
||||
# mechanism DeepSeek-V3 uses for its no-op ``enable_thinking``, for a
|
||||
# different underlying reason (theirs is an ignored kwarg, this is a
|
||||
# variant switch).
|
||||
_internal_fields = frozenset({"ultra"})
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"truncate_history_thinking",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
low_effort: bool = False
|
||||
"""When ``True``, append ``\\n\\n{reasoning effort: low}`` to the last user
|
||||
message, nudging the model toward shorter reasoning. Mirrors the **Super**
|
||||
chat template's ``low_effort`` kwarg. A no-op on **Nano** (its template
|
||||
doesn't define it) — exactly as ``apply_chat_template`` ignores an undefined
|
||||
template variable; the renderer distinguishes the two by model name (see
|
||||
``renderers.nemotron3._is_super``)."""
|
||||
|
||||
|
||||
class Nemotron3UltraRendererConfig(BaseRendererConfig):
|
||||
"""Nemotron-3 **Ultra** renderer config — distinct discriminator so the
|
||||
registry routes Ultra checkpoints to the Ultra template variant.
|
||||
|
||||
Ultra's template differs from Nano/Super: the reasoning block is glued as
|
||||
``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around ``</think>``)
|
||||
and truncated historical turns collapse to ``<think></think>{content}``
|
||||
(no ``\\n``). It shares the :class:`renderers.nemotron3.Nemotron3Renderer`
|
||||
implementation, which selects the variant from ``config.name``.
|
||||
"""
|
||||
|
||||
name: Literal["nemotron-3-ultra"] = "nemotron-3-ultra"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""See :class:`Nemotron3RendererConfig.enable_thinking`."""
|
||||
|
||||
truncate_history_thinking: bool = True
|
||||
"""See :class:`Nemotron3RendererConfig.truncate_history_thinking`."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_thinking_retention(self):
|
||||
_reject_thinking_retention_conflict(
|
||||
self,
|
||||
"truncate_history_thinking",
|
||||
true_implies="tool_cycle",
|
||||
false_implies="all",
|
||||
)
|
||||
return self
|
||||
|
||||
medium_effort: bool = False
|
||||
"""When ``True``, append ``\\n\\n{reasoning effort: efficient}`` to the last
|
||||
user message. Mirrors the Ultra chat template's ``medium_effort`` kwarg."""
|
||||
|
||||
|
||||
class DeepSeekV3RendererConfig(BaseRendererConfig):
|
||||
@@ -416,9 +639,10 @@ class DeepSeekR1RendererConfig(BaseRendererConfig):
|
||||
R1 always reasons — its chat template unconditionally prefills
|
||||
``<think>\\n`` at the generation prompt and strips ``</think>`` from
|
||||
historical assistant turns. There is therefore no ``enable_thinking``
|
||||
knob (thinking is not optional), and ``preserve_*`` flags are no-ops
|
||||
(history reasoning is always dropped); both stored for protocol
|
||||
uniformity. Applies to full ``deepseek-ai/DeepSeek-R1`` / ``-R1-0528``
|
||||
knob (thinking is not optional). With ``thinking_retention=None`` the
|
||||
resolved bridge policy is ``"template"``; explicit ``"tool_cycle"`` /
|
||||
``"all"`` are bridge-policy overrides. Applies to full
|
||||
``deepseek-ai/DeepSeek-R1`` / ``-R1-0528``
|
||||
— NOT the R1-Distill-Qwen/Llama models, which use those base
|
||||
tokenizers and route to the Qwen3 / Llama-3 renderers.
|
||||
"""
|
||||
@@ -431,6 +655,7 @@ RendererConfig = Annotated[
|
||||
AutoRendererConfig,
|
||||
DefaultRendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
PrimeQwen3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
Qwen36RendererConfig,
|
||||
Qwen3VLRendererConfig,
|
||||
@@ -438,12 +663,15 @@ RendererConfig = Annotated[
|
||||
GLM51RendererConfig,
|
||||
GLM45RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
Hy3RendererConfig,
|
||||
KimiK2RendererConfig,
|
||||
KimiK25RendererConfig,
|
||||
LagunaXS2RendererConfig,
|
||||
LagunaXS21RendererConfig,
|
||||
Llama3RendererConfig,
|
||||
MiniMaxM2RendererConfig,
|
||||
Nemotron3RendererConfig,
|
||||
Nemotron3UltraRendererConfig,
|
||||
DeepSeekV3RendererConfig,
|
||||
DeepSeekR1RendererConfig,
|
||||
],
|
||||
@@ -462,11 +690,12 @@ that renderer supports. Bogus combinations (e.g. ``add_vision_id`` under
|
||||
# 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.
|
||||
# auto config's ``thinking_retention`` field is carried over.
|
||||
_CONFIG_BY_NAME: dict[str, type[BaseRendererConfig]] = {
|
||||
"auto": AutoRendererConfig,
|
||||
"default": DefaultRendererConfig,
|
||||
"qwen3": Qwen3RendererConfig,
|
||||
"prime-qwen3": PrimeQwen3RendererConfig,
|
||||
"qwen3.5": Qwen35RendererConfig,
|
||||
"qwen3.6": Qwen36RendererConfig,
|
||||
"qwen3-vl": Qwen3VLRendererConfig,
|
||||
@@ -474,12 +703,15 @@ _CONFIG_BY_NAME: dict[str, type[BaseRendererConfig]] = {
|
||||
"glm-5.1": GLM51RendererConfig,
|
||||
"glm-4.5": GLM45RendererConfig,
|
||||
"gpt-oss": GptOssRendererConfig,
|
||||
"hy3": Hy3RendererConfig,
|
||||
"kimi-k2": KimiK2RendererConfig,
|
||||
"kimi-k2.5": KimiK25RendererConfig,
|
||||
"laguna-xs.2": LagunaXS2RendererConfig,
|
||||
"laguna-xs-2.1": LagunaXS21RendererConfig,
|
||||
"llama-3": Llama3RendererConfig,
|
||||
"minimax-m2": MiniMaxM2RendererConfig,
|
||||
"nemotron-3": Nemotron3RendererConfig,
|
||||
"nemotron-3-ultra": Nemotron3UltraRendererConfig,
|
||||
"deepseek-v3": DeepSeekV3RendererConfig,
|
||||
"deepseek-r1": DeepSeekR1RendererConfig,
|
||||
}
|
||||
@@ -519,16 +751,22 @@ __all__ = [
|
||||
"GLM51RendererConfig",
|
||||
"GLM5RendererConfig",
|
||||
"GptOssRendererConfig",
|
||||
"Hy3RendererConfig",
|
||||
"KimiK25RendererConfig",
|
||||
"KimiK2RendererConfig",
|
||||
"LagunaXS2RendererConfig",
|
||||
"LagunaXS21RendererConfig",
|
||||
"Llama3RendererConfig",
|
||||
"MiniMaxM2RendererConfig",
|
||||
"Nemotron3RendererConfig",
|
||||
"Nemotron3UltraRendererConfig",
|
||||
"PrimeQwen3RendererConfig",
|
||||
"Qwen35RendererConfig",
|
||||
"Qwen36RendererConfig",
|
||||
"Qwen3RendererConfig",
|
||||
"Qwen3VLRendererConfig",
|
||||
"RendererConfig",
|
||||
"ResolvedThinkingRetention",
|
||||
"ThinkingRetention",
|
||||
"config_from_name",
|
||||
]
|
||||
|
||||
@@ -31,6 +31,7 @@ class DeepSeekR1Renderer(DeepSeekV3Renderer):
|
||||
"""Deterministic message → token renderer for DeepSeek-R1 models."""
|
||||
|
||||
_config_cls: type = DeepSeekR1RendererConfig
|
||||
_implied_thinking_retention = "template"
|
||||
_GEN_THINK_PREFILL: str = "<think>\n"
|
||||
|
||||
def _prepare_assistant_content(self, msg: Message) -> str:
|
||||
|
||||
@@ -24,6 +24,8 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import DeepSeekV3RendererConfig
|
||||
@@ -48,12 +50,13 @@ class DeepSeekV3Renderer:
|
||||
assistant content is emitted verbatim. The reasoning variant
|
||||
(``<think>``-prefilled prompt, history reasoning stripped) lives in
|
||||
:class:`renderers.deepseek_r1.DeepSeekR1Renderer`, which subclasses
|
||||
this one. ``preserve_*`` flags are no-ops here (no reasoning channel),
|
||||
this one. ``thinking_retention`` is a no-op here (no reasoning channel),
|
||||
stored for protocol uniformity.
|
||||
"""
|
||||
|
||||
#: Default typed config; the R1 subclass overrides this.
|
||||
_config_cls: type = DeepSeekV3RendererConfig
|
||||
_implied_thinking_retention = "all"
|
||||
#: Generation-prompt reasoning prefill. Empty for V3 (bare
|
||||
#: ``<|Assistant|>``); the R1 subclass overrides to ``"<think>\n"``.
|
||||
_GEN_THINK_PREFILL: str = ""
|
||||
@@ -65,6 +68,10 @@ class DeepSeekV3Renderer:
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or type(self)._config_cls()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
self._implied_thinking_retention,
|
||||
)
|
||||
|
||||
# ── BOS / EOS ────────────────────────────────────────────────
|
||||
self._bos = self._get_special_token(f"begin{_US}of{_US}sentence")
|
||||
@@ -305,6 +312,11 @@ class DeepSeekV3Renderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
|
||||
+13
-5
@@ -19,8 +19,10 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
resolve_thinking_retention,
|
||||
)
|
||||
from renderers.configs import DefaultRendererConfig
|
||||
from renderers.hermes import HermesToolParser
|
||||
from renderers.parsers import (
|
||||
get_reasoning_parser,
|
||||
get_tool_parser,
|
||||
@@ -95,15 +97,21 @@ class DefaultRenderer:
|
||||
config: DefaultRendererConfig | None = None,
|
||||
):
|
||||
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."
|
||||
if cfg.thinking_retention is not None:
|
||||
raise ValueError(
|
||||
"DefaultRenderer cannot implement explicit thinking_retention "
|
||||
"bridge policy because its template close/turn structure is "
|
||||
"opaque. Use a typed renderer for this model."
|
||||
)
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
cfg,
|
||||
"template",
|
||||
)
|
||||
self._tokenizer = tokenizer
|
||||
self.config = cfg
|
||||
self._tool_parser = _resolve_parser(cfg.tool_parser, tokenizer, get_tool_parser)
|
||||
if isinstance(self._tool_parser, HermesToolParser):
|
||||
self._tool_parser.configure_prefill(dict(cfg.model_extra or {}))
|
||||
self._reasoning_parser = _resolve_parser(
|
||||
cfg.reasoning_parser, tokenizer, get_reasoning_parser
|
||||
)
|
||||
|
||||
+13
-10
@@ -23,7 +23,8 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
)
|
||||
from renderers.configs import GLM45RendererConfig
|
||||
from renderers.parsing import parse_glm
|
||||
@@ -59,6 +60,10 @@ class GLM45Renderer:
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or GLM45RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all" if not self.config.enable_thinking else "tool_cycle",
|
||||
)
|
||||
|
||||
self._gmask = self._token_id("[gMASK]")
|
||||
self._sop = self._token_id("<sop>")
|
||||
@@ -225,18 +230,11 @@ class GLM45Renderer:
|
||||
emit_text_segments(user_segments, i, is_sampled=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
last_ui,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
@@ -321,6 +319,12 @@ class GLM45Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# Same next-turn-marker scheme as GLM-5, but role markers are
|
||||
# followed by a literal ``\n`` in the prompt text.
|
||||
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
|
||||
@@ -457,7 +461,6 @@ class GLM45Renderer:
|
||||
content,
|
||||
last_user_index,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
@@ -495,7 +498,7 @@ class GLM45Renderer:
|
||||
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:
|
||||
if msg_idx > last_user_index and reasoning_content:
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
reasoning_content.strip(), msg_idx, is_sampled=True, is_content=True
|
||||
|
||||
+20
-16
@@ -24,7 +24,8 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
)
|
||||
from renderers.configs import GLM5RendererConfig, GLM51RendererConfig
|
||||
from renderers.parsing import parse_glm
|
||||
@@ -68,6 +69,16 @@ class GLM5Renderer:
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or type(self)._config_cls()
|
||||
if not self.config.clear_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
elif not self.config.enable_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
else:
|
||||
implied_thinking_retention = "tool_cycle"
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
implied_thinking_retention,
|
||||
)
|
||||
|
||||
self._gmask = self._token_id("[gMASK]")
|
||||
self._sop = self._token_id("<sop>")
|
||||
@@ -238,18 +249,11 @@ class GLM5Renderer:
|
||||
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.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
last_ui,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
@@ -337,6 +341,12 @@ class GLM5Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# GLM has no per-turn close token. An assistant turn ends when the
|
||||
# next turn's role marker appears, OR the model emits <|endoftext|>.
|
||||
# vLLM includes these in ``stop_token_ids`` so a clean stop leaves
|
||||
@@ -468,7 +478,6 @@ class GLM5Renderer:
|
||||
content,
|
||||
last_user_index,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
@@ -498,17 +507,12 @@ class GLM5Renderer:
|
||||
|
||||
# Chat-template default: keep ``<think>`` only on the in-flight cycle
|
||||
# (post-last-user). Past-cycle assistants drop their reasoning.
|
||||
# ``preserve_thinking`` is the override output of
|
||||
# ``should_preserve_past_thinking`` — it adds historical assistants
|
||||
# back when the renderer was constructed with
|
||||
# ``preserve_all_thinking=True``. ``clear_thinking=False`` mirrors
|
||||
# ``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
|
||||
or not self.config.clear_thinking
|
||||
msg_idx > last_user_index or not self.config.clear_thinking
|
||||
) and reasoning_content
|
||||
|
||||
if include_thinking:
|
||||
|
||||
+36
-11
@@ -58,7 +58,8 @@ from renderers.base import (
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import GptOssRendererConfig
|
||||
@@ -134,6 +135,10 @@ class GptOssRenderer:
|
||||
"""
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or GptOssRendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"tool_cycle" if self.config.auto_drop_analysis else "all",
|
||||
)
|
||||
self._enc: HarmonyEncoding = load_harmony_encoding(
|
||||
HarmonyEncodingName.HARMONY_GPT_OSS
|
||||
)
|
||||
@@ -421,14 +426,7 @@ class GptOssRenderer:
|
||||
if i == first_system_idx:
|
||||
continue # already emitted as developer
|
||||
is_assistant = msg.get("role") == "assistant"
|
||||
preserve_thinking = is_assistant and (
|
||||
should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
)
|
||||
preserve_thinking = is_assistant and self._should_emit_analysis(messages, i)
|
||||
for hm in self._to_harmony_messages(
|
||||
msg, preserve_thinking=preserve_thinking
|
||||
):
|
||||
@@ -524,6 +522,12 @@ class GptOssRenderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
@@ -601,6 +605,26 @@ class GptOssRenderer:
|
||||
|
||||
# ── message conversion ───────────────────────────────────────────────────
|
||||
|
||||
def _should_emit_analysis(self, messages: list[Message], msg_idx: int) -> bool:
|
||||
"""Whether to render ``reasoning_content`` as a harmony analysis message."""
|
||||
if not self.config.auto_drop_analysis:
|
||||
return True
|
||||
|
||||
msg = messages[msg_idx]
|
||||
if not msg.get("tool_calls"):
|
||||
return False
|
||||
|
||||
# Harmony keeps analysis for an unfinished tool-call cycle, but once a
|
||||
# later final assistant answer is present it drops the stale analysis.
|
||||
for later in messages[msg_idx + 1 :]:
|
||||
if later.get("role") != "assistant":
|
||||
continue
|
||||
if later.get("tool_calls"):
|
||||
continue
|
||||
if _content_text(later.get("content")):
|
||||
return False
|
||||
return True
|
||||
|
||||
def _to_harmony_messages(
|
||||
self, msg: Message, *, preserve_thinking: bool = False
|
||||
) -> list[HarmonyMessage]:
|
||||
@@ -670,8 +694,9 @@ class GptOssRenderer:
|
||||
its analysis block is dropped from context.
|
||||
|
||||
``preserve_thinking=True``: prepend an analysis-channel message
|
||||
carrying ``reasoning_content`` so callers that want the trace in
|
||||
history (e.g. tool-call-chain training) see it surface.
|
||||
carrying ``reasoning_content``. The render path sets this from
|
||||
harmony's own ``auto_drop_analysis`` behaviour, not from generic
|
||||
``thinking_retention``.
|
||||
"""
|
||||
out: list[HarmonyMessage] = []
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Text-level Hermes calls, excluding reasoning and Markdown code examples."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from renderers.base import ParsedToolCall, ToolCallParseStatus
|
||||
|
||||
_THINK = re.compile(r"</?think>", re.IGNORECASE)
|
||||
_OPEN = "<tool_call>"
|
||||
_CLOSE = "</tool_call>"
|
||||
|
||||
|
||||
def _reject_constant(value: str) -> None:
|
||||
raise ValueError(f"Non-JSON numeric constant: {value}")
|
||||
|
||||
|
||||
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError(f"Duplicate JSON key: {key}")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
_JSON = json.JSONDecoder(parse_constant=_reject_constant, object_pairs_hook=_unique_object)
|
||||
|
||||
|
||||
def _token_boundary(tokenizer, ids: list[int], offset: int, *, end: bool) -> int:
|
||||
"""Cover every token overlapping the character span, including boundary merges."""
|
||||
low, high = 0, len(ids)
|
||||
while low < high:
|
||||
mid = (low + high) // 2
|
||||
if len(tokenizer.decode(ids[:mid], skip_special_tokens=False)) < offset:
|
||||
low = mid + 1
|
||||
else:
|
||||
high = mid
|
||||
if not end and len(tokenizer.decode(ids[:low], skip_special_tokens=False)) > offset:
|
||||
return max(0, low - 1)
|
||||
return low
|
||||
|
||||
|
||||
def _skip_reasoning(text: str, start: int) -> int:
|
||||
depth = 0
|
||||
for match in _THINK.finditer(text, start):
|
||||
depth += -1 if match.group().startswith("</") else 1
|
||||
if depth == 0:
|
||||
return match.end()
|
||||
return len(text)
|
||||
|
||||
|
||||
def _read_block(text: str, start: int) -> tuple[int, str, Any, ToolCallParseStatus]:
|
||||
body = start + len(_OPEN)
|
||||
while body < len(text) and text[body].isspace():
|
||||
body += 1
|
||||
try:
|
||||
payload, json_end = _JSON.raw_decode(text, body)
|
||||
except ValueError:
|
||||
close = text.find(_CLOSE, body)
|
||||
if close < 0:
|
||||
return len(text), text[body:].strip(), None, ToolCallParseStatus.UNCLOSED_BLOCK
|
||||
return close + len(_CLOSE), text[body:close].strip(), None, ToolCallParseStatus.INVALID_JSON
|
||||
close = json_end
|
||||
while close < len(text) and text[close].isspace():
|
||||
close += 1
|
||||
if not text.startswith(_CLOSE, close):
|
||||
closing = text.find(_CLOSE, close)
|
||||
if closing < 0:
|
||||
return len(text), text[body:].strip(), None, ToolCallParseStatus.UNCLOSED_BLOCK
|
||||
return closing + len(_CLOSE), text[body:closing].strip(), None, ToolCallParseStatus.MALFORMED_STRUCTURE
|
||||
status = ToolCallParseStatus.OK
|
||||
if (
|
||||
not isinstance(payload, dict)
|
||||
or not isinstance(payload.get("name"), str)
|
||||
or not payload["name"].strip()
|
||||
or not isinstance(payload.get("arguments"), dict)
|
||||
):
|
||||
status = ToolCallParseStatus.MALFORMED_STRUCTURE
|
||||
return close + len(_CLOSE), text[body:json_end], payload, status
|
||||
|
||||
|
||||
class HermesToolParser:
|
||||
"""Parse native Hermes envelopes without promoting quoted examples into actions."""
|
||||
|
||||
def __init__(self, tokenizer):
|
||||
self._tokenizer = tokenizer
|
||||
self._starts_in_reasoning = False
|
||||
|
||||
def configure_prefill(self, template_kwargs: dict[str, Any]) -> None:
|
||||
"""Honor templates that put the opening reasoning tag in the prompt."""
|
||||
if not hasattr(self._tokenizer, "apply_chat_template"):
|
||||
return
|
||||
kwargs = {**template_kwargs, "add_generation_prompt": True, "tokenize": False, "return_dict": False}
|
||||
prompt = self._tokenizer.apply_chat_template([{"role": "user", "content": "Hello"}], **kwargs)
|
||||
self._starts_in_reasoning = bool(re.search(r"<think>\s*$", prompt, re.IGNORECASE))
|
||||
|
||||
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
|
||||
text = self._tokenizer.decode(ids, skip_special_tokens=False)
|
||||
if _OPEN not in text:
|
||||
return ids, []
|
||||
# Some chat templates prefill <think>; the generated tokens then start
|
||||
# inside reasoning and contain only its closing delimiter.
|
||||
first_think = _THINK.search(text)
|
||||
if self._starts_in_reasoning and first_think is None:
|
||||
return ids, []
|
||||
cursor = first_think.end() if first_think and first_think.group().startswith("</") else 0
|
||||
kept, calls = [], []
|
||||
previous = 0
|
||||
while cursor < len(text):
|
||||
if text[cursor : cursor + 7].lower() == "<think>":
|
||||
cursor = _skip_reasoning(text, cursor)
|
||||
continue
|
||||
if text[cursor] == "`" or text.startswith("~~~", cursor):
|
||||
end = cursor + 1
|
||||
while end < len(text) and text[end] == text[cursor]:
|
||||
end += 1
|
||||
marker = text[cursor:end]
|
||||
close = text.find(marker, end)
|
||||
cursor = len(text) if close < 0 else close + len(marker)
|
||||
continue
|
||||
if not text.startswith(_OPEN, cursor):
|
||||
cursor += 1
|
||||
continue
|
||||
end, raw, payload, status = _read_block(text, cursor)
|
||||
span = (
|
||||
_token_boundary(self._tokenizer, ids, cursor, end=False),
|
||||
_token_boundary(self._tokenizer, ids, end, end=True),
|
||||
)
|
||||
calls.append(
|
||||
ParsedToolCall(
|
||||
raw=raw,
|
||||
token_span=span,
|
||||
status=status,
|
||||
name=payload["name"] if status == ToolCallParseStatus.OK else None,
|
||||
arguments=payload["arguments"] if status == ToolCallParseStatus.OK else None,
|
||||
)
|
||||
)
|
||||
kept.append(text[previous:cursor])
|
||||
previous = cursor = end
|
||||
if not calls:
|
||||
return ids, []
|
||||
kept.append(text[previous:])
|
||||
# Re-encode retained text so BPE tokens crossing envelope boundaries do
|
||||
# not swallow adjacent text. Spans above always refer to the original ids.
|
||||
content_ids = self._tokenizer.encode("".join(kept), add_special_tokens=False)
|
||||
return content_ids, calls
|
||||
@@ -0,0 +1,706 @@
|
||||
"""Hy3 renderer — hard-coded Python mirroring the Tencent Hunyuan Hy3 Jinja
|
||||
chat template (``tencent/Hy3`` / ``Hy3-FP8``; ``Hy3-preview`` uses an older,
|
||||
incompatible template and is not supported).
|
||||
|
||||
Shape of the Hy3 template, distinct from the GLM / Qwen families:
|
||||
|
||||
- No per-message ``<|system|>`` marker: every system message's content is
|
||||
concatenated into a single blob emitted right after ``<|hy_begin_of_sentence|>``.
|
||||
- Reasoning is gated by ``reasoning_effort`` (``no_think`` / ``low`` / ``high``),
|
||||
not a boolean. Without tools a ``<|reasoning_mode|>reasoning_effort:{effort}``
|
||||
marker is appended to the system blob; with tools it rides at the end of the
|
||||
tool-instruction block instead.
|
||||
- The generation prompt prefills ``<think></think>`` in ``no_think`` mode (the
|
||||
model answers directly) and only ``<think>`` in ``low`` / ``high`` mode (the
|
||||
model streams reasoning up to a ``</think>`` it emits itself).
|
||||
- Each assistant turn closes with an explicit ``<|hy_eos|>`` — the sole stop
|
||||
token — unlike GLM where the next role marker doubles as the close.
|
||||
- Tool calls: ``<tool_calls>`` wraps one or more ``<tool_call>name<tool_sep>``
|
||||
blocks, each carrying ``<arg_key>``/``<arg_value>`` pairs (single special
|
||||
tokens, as in GLM), and the block closes ``</tool_calls><|hy_eos|>``.
|
||||
- Tool responses: ``<tool_responses>`` wraps one or more
|
||||
``<tool_response>…</tool_response>`` blocks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from renderers.base import (
|
||||
Message,
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
)
|
||||
from renderers.configs import Hy3RendererConfig, ResolvedThinkingRetention
|
||||
from renderers.parsing import parse_hy3
|
||||
|
||||
# Special-token strings, constructed exactly as the Jinja template does
|
||||
# (``'<|hy_eos{}|>'.format(':opensource')`` etc.) so ``convert_tokens_to_ids``
|
||||
# resolves each to its single vocabulary id.
|
||||
_HYTK = ":opensource"
|
||||
_BOS = f"<|hy_begin_of_sentence{_HYTK}|>"
|
||||
_EOS = f"<|hy_eos{_HYTK}|>"
|
||||
_USER = f"<|hy_User{_HYTK}|>"
|
||||
_ASSISTANT = f"<|hy_Assistant{_HYTK}|>"
|
||||
_REASONING_MODE = f"<|reasoning_mode{_HYTK}|>"
|
||||
_THINK = f"<think{_HYTK}>"
|
||||
_THINK_END = f"</think{_HYTK}>"
|
||||
_TOOL_CALLS = f"<tool_calls{_HYTK}>"
|
||||
_TOOL_CALLS_END = f"</tool_calls{_HYTK}>"
|
||||
_TOOL_CALL = f"<tool_call{_HYTK}>"
|
||||
_TOOL_CALL_END = f"</tool_call{_HYTK}>"
|
||||
_TOOL_SEP = f"<tool_sep{_HYTK}>"
|
||||
_ARG_KEY = f"<arg_key{_HYTK}>"
|
||||
_ARG_KEY_END = f"</arg_key{_HYTK}>"
|
||||
_ARG_VALUE = f"<arg_value{_HYTK}>"
|
||||
_ARG_VALUE_END = f"</arg_value{_HYTK}>"
|
||||
_TOOL_RESPONSES = f"<tool_responses{_HYTK}>"
|
||||
_TOOL_RESPONSES_END = f"</tool_responses{_HYTK}>"
|
||||
_TOOL_RESPONSE = f"<tool_response{_HYTK}>"
|
||||
_TOOL_RESPONSE_END = f"</tool_response{_HYTK}>"
|
||||
|
||||
|
||||
class Hy3Renderer:
|
||||
"""Deterministic message → token renderer for Tencent Hy3 models."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Hy3RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or Hy3RendererConfig()
|
||||
self._is_training = self.config.is_training
|
||||
self._raw_last_assistant = self.config.raw_last_assistant
|
||||
# ``fallback_strategy="reasoning_toolcall_retry"`` forces high effort and
|
||||
# suppresses the generation prompt (template lines 50-53), resolved here
|
||||
# so the reasoning-mode marker and gen-prompt polarity see the override.
|
||||
self._force_no_gen_prompt = (
|
||||
self.config.fallback_strategy == "reasoning_toolcall_retry"
|
||||
)
|
||||
self._reasoning_effort = (
|
||||
"high" if self._force_no_gen_prompt else self.config.reasoning_effort
|
||||
)
|
||||
# ``<think>`` (and, in no_think mode, the matching ``</think>``) are
|
||||
# prefilled by the generation prompt, so the model never samples them.
|
||||
# Only in low/high mode does the model itself emit the ``</think>``
|
||||
# that closes its reasoning.
|
||||
self._think_is_sampled = self._reasoning_effort in ("low", "high")
|
||||
# Derived bridge policy: when the template keeps reasoning on every
|
||||
# historical turn it is safe to extend across a user query ("all");
|
||||
# otherwise past-cycle reasoning is stripped once a new user query
|
||||
# arrives, so the faithful policy declines there ("tool_cycle").
|
||||
# ``preserved_thinking=None`` follows the template's tools-dependent
|
||||
# default, so the bridge resolves the policy per call; this attribute
|
||||
# holds the no-tools resolution.
|
||||
self.effective_thinking_retention = self._thinking_retention_for(None)
|
||||
|
||||
self._bos = self._token_id(_BOS)
|
||||
self._eos = self._token_id(_EOS)
|
||||
self._user = self._token_id(_USER)
|
||||
self._assistant = self._token_id(_ASSISTANT)
|
||||
self._reasoning_mode = self._token_id(_REASONING_MODE)
|
||||
self._think = self._token_id(_THINK)
|
||||
self._think_end = self._token_id(_THINK_END)
|
||||
self._tool_calls = self._token_id(_TOOL_CALLS)
|
||||
self._tool_calls_end = self._token_id(_TOOL_CALLS_END)
|
||||
self._tool_call = self._token_id(_TOOL_CALL)
|
||||
self._tool_call_end = self._token_id(_TOOL_CALL_END)
|
||||
self._tool_sep = self._token_id(_TOOL_SEP)
|
||||
self._arg_key = self._token_id(_ARG_KEY)
|
||||
self._arg_key_end = self._token_id(_ARG_KEY_END)
|
||||
self._arg_value = self._token_id(_ARG_VALUE)
|
||||
self._arg_value_end = self._token_id(_ARG_VALUE_END)
|
||||
self._tool_responses = self._token_id(_TOOL_RESPONSES)
|
||||
self._tool_responses_end = self._token_id(_TOOL_RESPONSES_END)
|
||||
self._tool_response = self._token_id(_TOOL_RESPONSE)
|
||||
self._tool_response_end = self._token_id(_TOOL_RESPONSE_END)
|
||||
|
||||
# ── helpers ──────────────────────────────────────────────────────
|
||||
|
||||
def _preserved_thinking_for(self, tools: list[ToolSpec] | None) -> bool:
|
||||
"""Mirror the template's ``preserved_thinking`` default: the kwarg
|
||||
when set, else True iff tools are present."""
|
||||
if self.config.preserved_thinking is None:
|
||||
return bool(tools)
|
||||
return self.config.preserved_thinking
|
||||
|
||||
def _thinking_retention_for(
|
||||
self, tools: list[ToolSpec] | None
|
||||
) -> ResolvedThinkingRetention:
|
||||
implied = "all" if self._preserved_thinking_for(tools) else "tool_cycle"
|
||||
return resolve_thinking_retention(self.config, implied)
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
tid = self._tokenizer.convert_tokens_to_ids(token)
|
||||
assert isinstance(tid, int) and tid != self._tokenizer.unk_token_id, (
|
||||
f"Special token {token!r} not found in tokenizer vocabulary"
|
||||
)
|
||||
return tid
|
||||
|
||||
def _encode(self, text: str) -> list[int]:
|
||||
if not text:
|
||||
return []
|
||||
return self._tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
@staticmethod
|
||||
def _visible_text(content: Any) -> str:
|
||||
"""Mirror the template's ``visible_text`` macro: string verbatim, list
|
||||
of text parts concatenated, ``None`` → empty string."""
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
parts.append(item)
|
||||
elif isinstance(item, dict) and item.get("type") == "text":
|
||||
parts.append(item.get("text", ""))
|
||||
return "".join(parts)
|
||||
return str(content)
|
||||
|
||||
@staticmethod
|
||||
def _last_user_index(messages: list[Message]) -> int:
|
||||
for i in range(len(messages) - 1, -1, -1):
|
||||
if messages[i].get("role") == "user":
|
||||
return i
|
||||
return -1
|
||||
|
||||
def _reasoning_content(self, msg: Message) -> str | None:
|
||||
rc = msg.get("reasoning_content")
|
||||
if isinstance(rc, str):
|
||||
return rc
|
||||
rc = msg.get("reasoning")
|
||||
if isinstance(rc, str):
|
||||
return rc
|
||||
return None
|
||||
|
||||
def _tools_instruction_block(self, tools: list[ToolSpec], has_system: bool) -> str:
|
||||
"""Build the ``# Tools`` instruction blob (all scaffold).
|
||||
|
||||
Embedded special-token strings (``<tool_calls>`` etc.) tokenize to
|
||||
their single ids just as ``apply_chat_template`` produces them.
|
||||
"""
|
||||
intro = (
|
||||
"# Tools\n\nYou may call one or more functions to assist with the "
|
||||
"user query."
|
||||
)
|
||||
s = ("\n\n" + intro) if has_system else intro
|
||||
s += (
|
||||
"\n\nYou are provided with function signatures within "
|
||||
"<tools></tools> XML tags:\n<tools>\n"
|
||||
)
|
||||
for idx, tool in enumerate(tools):
|
||||
if idx > 0:
|
||||
s += "\n"
|
||||
s += json.dumps(tool, ensure_ascii=False)
|
||||
s += "\n</tools>\n\n"
|
||||
s += "For function call returns, you should first print " + _TOOL_CALLS + "\n"
|
||||
s += "For each function call, you should return object like:\n"
|
||||
s += _TOOL_CALL + "{function-name}" + _TOOL_SEP + "\n"
|
||||
s += _ARG_KEY + "{arg-key-1}" + _ARG_KEY_END + "\n"
|
||||
s += _ARG_VALUE + "{arg-value-1}" + _ARG_VALUE_END + "\n"
|
||||
s += _ARG_KEY + "{arg-key-2}" + _ARG_KEY_END + "\n"
|
||||
s += _ARG_VALUE + "{arg-value-2}" + _ARG_VALUE_END + "\n"
|
||||
s += "...\n"
|
||||
s += _TOOL_CALL_END + "\n"
|
||||
# ``reasoning_effort`` is always a non-empty string in our config, so
|
||||
# the marker is always appended (matching the template's truthy path).
|
||||
s += (
|
||||
"At the end of function call returns, you should print "
|
||||
+ _TOOL_CALLS_END
|
||||
+ _REASONING_MODE
|
||||
+ "reasoning_effort:"
|
||||
+ self._reasoning_effort
|
||||
)
|
||||
return s
|
||||
|
||||
def _attribute_segments(
|
||||
self, segments: list[tuple[str, bool, int]]
|
||||
) -> list[tuple[int, bool, int]]:
|
||||
"""Tokenize concatenated ``(text, is_content, msg_idx)`` segments as one
|
||||
BPE pass, attributing each token to its source segment via offset
|
||||
mapping. Generalises :func:`attribute_text_segments` with a message
|
||||
index — needed where a system blob abuts the tools block with no
|
||||
special-token boundary between them.
|
||||
"""
|
||||
segments = [s for s in segments if s[0]]
|
||||
if not segments:
|
||||
return []
|
||||
full_text = "".join(text for text, _, _ in segments)
|
||||
encoding = self._tokenizer(
|
||||
full_text,
|
||||
add_special_tokens=False,
|
||||
return_offsets_mapping=True,
|
||||
)
|
||||
token_ids = list(encoding["input_ids"])
|
||||
offsets = list(encoding["offset_mapping"])
|
||||
|
||||
spans: list[tuple[int, int, bool, int]] = []
|
||||
pos = 0
|
||||
for text, is_content, msg_idx in segments:
|
||||
spans.append((pos, pos + len(text), is_content, msg_idx))
|
||||
pos += len(text)
|
||||
total_len = pos
|
||||
|
||||
out: list[tuple[int, bool, int]] = []
|
||||
last = (spans[-1][2], spans[-1][3])
|
||||
for tok_id, (start, _end) in zip(token_ids, offsets):
|
||||
attr = last
|
||||
if start < total_len:
|
||||
for seg_start, seg_end, seg_is_content, seg_idx in spans:
|
||||
if seg_start <= start < seg_end:
|
||||
attr = (seg_is_content, seg_idx)
|
||||
break
|
||||
out.append((tok_id, attr[0], attr[1]))
|
||||
return out
|
||||
|
||||
# ── render ───────────────────────────────────────────────────────
|
||||
|
||||
def render(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> RenderedTokens:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
# fallback_strategy="reasoning_toolcall_retry" suppresses the gen prompt.
|
||||
if self._force_no_gen_prompt:
|
||||
add_generation_prompt = False
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_attributed(segments: list[tuple[str, bool, int]]) -> None:
|
||||
for tok_id, is_content, msg_idx in self._attribute_segments(segments):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(False)
|
||||
content_mask.append(is_content)
|
||||
|
||||
preserved = self._preserved_thinking_for(tools)
|
||||
|
||||
# ── Header: bos + aggregated system + reasoning marker / tools ──
|
||||
emit_special(self._bos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
system_segments = [
|
||||
(self._visible_text(m.get("content")), True, i)
|
||||
for i, m in enumerate(messages)
|
||||
if m.get("role") == "system"
|
||||
]
|
||||
has_system = any(text for text, _, _ in system_segments)
|
||||
|
||||
if tools:
|
||||
tools_text = self._tools_instruction_block(tools, has_system)
|
||||
emit_attributed(system_segments + [(tools_text, False, -1)])
|
||||
else:
|
||||
emit_attributed(system_segments)
|
||||
emit_special(self._reasoning_mode, -1, is_sampled=False, is_content=False)
|
||||
emit_text(
|
||||
"reasoning_effort:" + self._reasoning_effort,
|
||||
-1,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
|
||||
last_ui = self._last_user_index(messages)
|
||||
n = len(messages)
|
||||
prev_is_tool = False
|
||||
is_tool_first = True
|
||||
|
||||
# ── Message loop (system handled in the header) ─────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
role = msg.get("role")
|
||||
if role == "system":
|
||||
continue
|
||||
|
||||
if role == "user":
|
||||
if prev_is_tool:
|
||||
emit_special(
|
||||
self._tool_responses_end, i, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_special(self._user, i, is_sampled=False, is_content=False)
|
||||
emit_text(
|
||||
self._visible_text(msg.get("content")),
|
||||
i,
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
prev_is_tool = False
|
||||
|
||||
elif role == "assistant":
|
||||
if prev_is_tool:
|
||||
emit_special(
|
||||
self._tool_responses_end, i, is_sampled=False, is_content=False
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
is_last=(i == n - 1),
|
||||
retain_thinking=self._is_training or preserved or i > last_ui,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
prev_is_tool = False
|
||||
# The template re-opens a <tool_responses> group only after an
|
||||
# assistant that made tool calls; a plain assistant leaves the
|
||||
# flag as it was.
|
||||
if msg.get("tool_calls"):
|
||||
is_tool_first = True
|
||||
|
||||
elif role == "tool":
|
||||
if is_tool_first:
|
||||
emit_special(
|
||||
self._tool_responses, i, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
is_tool_first = False
|
||||
emit_special(self._tool_response, i, is_sampled=False, is_content=False)
|
||||
emit_text_segments(
|
||||
[
|
||||
("\n", False),
|
||||
(self._visible_text(msg.get("content")), True),
|
||||
("\n", False),
|
||||
],
|
||||
i,
|
||||
is_sampled=False,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_response_end, i, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
prev_is_tool = True
|
||||
|
||||
if prev_is_tool:
|
||||
emit_special(
|
||||
self._tool_responses_end, -1, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
# ── Generation prompt ───────────────────────────────────────────
|
||||
last_is_assistant = messages[-1].get("role") == "assistant"
|
||||
if add_generation_prompt and not last_is_assistant:
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
if self._reasoning_effort == "no_think":
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
msg: Message,
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_last: bool,
|
||||
retain_thinking: bool,
|
||||
emit_special,
|
||||
emit_text,
|
||||
) -> None:
|
||||
# Invariant on assistant tokens: ``is_content == sampled_mask``.
|
||||
# The ``<|hy_Assistant|>`` opener and the ``<think>`` opener are both
|
||||
# generation-prompt scaffold (never sampled). ``</think>`` and any
|
||||
# reasoning body are sampled only in low/high mode; content, tool
|
||||
# calls and the closing ``<|hy_eos|>`` are always sampled.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
visible = self._visible_text(msg.get("content"))
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
|
||||
# Raw passthrough for a trailing non-tool assistant (prefill /
|
||||
# continuation): no ``<think>`` wrap, no ``<|hy_eos|>`` — just the
|
||||
# bare visible content (template lines 186-187).
|
||||
if self._raw_last_assistant and is_last and not tool_calls:
|
||||
emit_text(visible, msg_idx, is_sampled=True, is_content=True)
|
||||
return
|
||||
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
rc = self._reasoning_content(msg)
|
||||
if retain_thinking and rc is not None:
|
||||
emit_text(
|
||||
rc,
|
||||
msg_idx,
|
||||
is_sampled=self._think_is_sampled,
|
||||
is_content=self._think_is_sampled,
|
||||
)
|
||||
emit_special(
|
||||
self._think_end,
|
||||
msg_idx,
|
||||
is_sampled=self._think_is_sampled,
|
||||
is_content=self._think_is_sampled,
|
||||
)
|
||||
|
||||
if tool_calls:
|
||||
emit_text(visible, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_calls, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
for tc in tool_calls:
|
||||
self._emit_tool_call(tc, msg_idx, emit_special, emit_text)
|
||||
emit_special(
|
||||
self._tool_calls_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(self._eos, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_text(visible, msg_idx, is_sampled=True, is_content=True)
|
||||
# Final assistant keeps its close only under is_training; otherwise
|
||||
# a terminal assistant is left open (template lines 188-192).
|
||||
if not is_last or self._is_training:
|
||||
emit_special(self._eos, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
def _emit_tool_call(self, tc: Any, msg_idx: int, emit_special, emit_text) -> None:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(name, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_sep, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# OpenAI canonical form serialises ``arguments`` as a JSON string;
|
||||
# parse it so per-argument rendering still fires.
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
if isinstance(arguments, dict):
|
||||
for key, value in arguments.items():
|
||||
emit_special(self._arg_key, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(key, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._arg_key_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._arg_value, msg_idx, is_sampled=True, is_content=True)
|
||||
if isinstance(value, str):
|
||||
emit_text(value, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_text(
|
||||
json.dumps(value, ensure_ascii=False),
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._arg_value_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> list[int]:
|
||||
return self.render(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
# ── parse ────────────────────────────────────────────────────────
|
||||
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_hy3(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
stop_ids={self._eos},
|
||||
assistant_id=self._assistant,
|
||||
think_id=self._think,
|
||||
think_end_id=self._think_end,
|
||||
tool_calls_id=self._tool_calls,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tool_sep_id=self._tool_sep,
|
||||
arg_key_id=self._arg_key,
|
||||
arg_key_end_id=self._arg_key_end,
|
||||
arg_value_id=self._arg_value,
|
||||
arg_value_end_id=self._arg_value_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
return [self._eos]
|
||||
|
||||
# ── bridge ───────────────────────────────────────────────────────
|
||||
|
||||
def bridge_to_next_turn(
|
||||
self,
|
||||
previous_prompt_ids: list[int],
|
||||
previous_completion_ids: list[int],
|
||||
new_messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> RenderedTokens | None:
|
||||
if (
|
||||
not previous_prompt_ids
|
||||
or not new_messages
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self._thinking_retention_for(tools),
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# A bridge extends a *sampled* assistant turn; with no completion there
|
||||
# is no turn to extend (and no way to tell a pending assistant turn from
|
||||
# a closed tool section), so decline and let the caller re-render.
|
||||
if not previous_completion_ids:
|
||||
return None
|
||||
|
||||
# Anchor on the canonical turn close (``<|hy_eos|>``). The model only
|
||||
# ever ends a turn on eos, so a completion that stops elsewhere was
|
||||
# truncated mid-turn — synthesise the close as non-loss prompt context.
|
||||
# Never synthesise after a boundary that is already a valid
|
||||
# continuation point: eos (turn closed) or ``</tool_responses>`` (tool
|
||||
# section closed, reachable when the prior prompt suppressed the
|
||||
# generation prompt) — an unconditional eos there would wedge a
|
||||
# spurious stop token before the extension.
|
||||
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
|
||||
if previous_ids[-1] not in (self._eos, self._tool_responses_end):
|
||||
previous_ids.append(self._eos)
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int = -1) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_content.append(False)
|
||||
|
||||
def emit_text(
|
||||
text: str, msg_idx: int = -1, *, is_content: bool = False
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(segments: list[tuple[str, bool]], msg_idx: int) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_content.append(is_content)
|
||||
|
||||
# The stream above ends on eos or </tool_responses> — never inside an
|
||||
# open tool group. ``is_tool_first`` mirrors the template's state
|
||||
# machine: it resets only on an assistant turn that made tool calls,
|
||||
# and a tool extension always follows exactly such a turn (that is
|
||||
# what produced the tool results), so it enters the extension True and
|
||||
# is never reset again — assistants are rejected above. The first tool
|
||||
# group opens <tool_responses>; a later group (after a user turn) does
|
||||
# not, matching a full render byte-for-byte.
|
||||
prev_is_tool = False
|
||||
is_tool_first = True
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
if role == "user":
|
||||
if prev_is_tool:
|
||||
emit_special(self._tool_responses_end, i)
|
||||
emit_special(self._user, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
prev_is_tool = False
|
||||
elif role == "system":
|
||||
# Hy3 folds system content into the header, which the bridge
|
||||
# cannot rewrite without re-rendering the prior turn.
|
||||
return None
|
||||
elif role == "tool":
|
||||
if is_tool_first:
|
||||
emit_special(self._tool_responses, i)
|
||||
emit_text("\n", i)
|
||||
is_tool_first = False
|
||||
emit_special(self._tool_response, i)
|
||||
emit_text_segments([("\n", False), (content, True), ("\n", False)], i)
|
||||
emit_special(self._tool_response_end, i)
|
||||
emit_text("\n", i)
|
||||
prev_is_tool = True
|
||||
else:
|
||||
return None
|
||||
|
||||
if prev_is_tool:
|
||||
emit_special(self._tool_responses_end, -1)
|
||||
|
||||
# Generation prompt — suppressed under the fallback retry strategy, so
|
||||
# the extension matches a full render (which forces it off too).
|
||||
if not self._force_no_gen_prompt:
|
||||
emit_special(self._assistant, -1)
|
||||
emit_special(self._think, -1)
|
||||
if self._reasoning_effort == "no_think":
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
+14
-3
@@ -25,6 +25,8 @@ from renderers.base import (
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import KimiK2RendererConfig
|
||||
@@ -38,9 +40,9 @@ class KimiK2Renderer:
|
||||
|
||||
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.
|
||||
``enable_thinking`` / ``thinking_retention`` fields on the config are
|
||||
stored for protocol uniformity with the rest of the renderer family
|
||||
but have no effect on the byte-level output.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -50,6 +52,10 @@ class KimiK2Renderer:
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or KimiK2RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
|
||||
self._im_user = self._token_id("<|im_user|>")
|
||||
self._im_assistant = self._token_id("<|im_assistant|>")
|
||||
@@ -356,6 +362,11 @@ class KimiK2Renderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
|
||||
+18
-13
@@ -38,7 +38,8 @@ from renderers.base import (
|
||||
ToolSpec,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import KimiK25RendererConfig
|
||||
@@ -599,6 +600,10 @@ class KimiK25Renderer:
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
self.config = config or KimiK25RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"tool_cycle" if self.config.thinking else "all",
|
||||
)
|
||||
|
||||
# Core structural tokens — all must be single special tokens in the vocab
|
||||
self._im_user = self._token_id("<|im_user|>")
|
||||
@@ -885,17 +890,10 @@ class KimiK25Renderer:
|
||||
# Body
|
||||
if role == "assistant":
|
||||
is_suffix = i > last_non_tc_assistant
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
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,
|
||||
i,
|
||||
is_suffix=is_suffix,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
@@ -1036,6 +1034,12 @@ class KimiK25Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
close_ids: set[int] = {self._im_end}
|
||||
if self._endoftext is not None:
|
||||
close_ids.add(self._endoftext)
|
||||
@@ -1179,18 +1183,20 @@ class KimiK25Renderer:
|
||||
emit_text("<think></think>", -1)
|
||||
|
||||
# Merge prev mm_data (earlier-turn images) with the new turn's items.
|
||||
# Copy the per-modality lists (not just the outer dict) so appending
|
||||
# below never mutates the caller's previous_multi_modal_data.
|
||||
merged_hashes: dict[str, list[str]] = (
|
||||
dict(previous_multi_modal_data.mm_hashes)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_placeholders: dict[str, list[PlaceholderRange]] = (
|
||||
dict(previous_multi_modal_data.mm_placeholders)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_items: dict[str, list[dict[str, Any]]] = (
|
||||
dict(previous_multi_modal_data.mm_items)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
@@ -1311,7 +1317,6 @@ class KimiK25Renderer:
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_suffix: bool,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
) -> None:
|
||||
@@ -1366,7 +1371,7 @@ class KimiK25Renderer:
|
||||
# ``render`` (also is_sampled=True; it's the model's stop
|
||||
# signal). On assistant tokens ``is_content == sampled_mask`` by
|
||||
# construction.
|
||||
if is_suffix or (preserve_thinking and reasoning_content):
|
||||
if is_suffix:
|
||||
emit_text(
|
||||
f"<think>{reasoning_content}</think>",
|
||||
msg_idx,
|
||||
|
||||
+411
-22
@@ -1,4 +1,4 @@
|
||||
"""Laguna-XS.2 Renderer.
|
||||
"""Laguna-XS.2 / XS-2.1 Renderer.
|
||||
|
||||
Main properties:
|
||||
- Prefix is the single token ``〈|EOS|〉`` (also the EOS / stop token).
|
||||
@@ -12,15 +12,30 @@ Main properties:
|
||||
- Tool calls: ``<tool_call>`` / ``</tool_call>`` ARE single tokens, but the
|
||||
inner ``<arg_key>`` / ``</arg_key>`` / ``<arg_value>`` / ``</arg_value>``
|
||||
markers are plain text — parsed via regex on the decoded inner block.
|
||||
- The template bakes in a default system prompt when ``messages[0]`` is not
|
||||
a system message. The system block also contains the tools section (under
|
||||
a ``### Tools`` header with an ``<available_tools>`` listing and prose
|
||||
format instructions that vary on ``enable_thinking``).
|
||||
- Both templates bake in the same default Poolside system prompt when
|
||||
``messages[0]`` is not a system message; a caller-supplied system
|
||||
message overrides it, and an *empty* one opts out of the ``<system>``
|
||||
block entirely (absent tools). The system block also contains the
|
||||
tools section (under a ``### Tools`` header with an
|
||||
``<available_tools>`` listing).
|
||||
- Reasoning is rendered for every assistant message — no last-user-index
|
||||
gating. ``preserve_all_thinking`` and
|
||||
``preserve_thinking_between_tool_calls`` are accepted for protocol
|
||||
uniformity but are effectively no-ops since past reasoning is preserved
|
||||
by default.
|
||||
gating. ``thinking_retention`` is accepted for protocol uniformity but
|
||||
is effectively a no-op since past reasoning is preserved by default.
|
||||
|
||||
XS-2.1's template (upstream rev ``575f0f28``) is served by the
|
||||
:class:`LagunaXS21Renderer` subclass below:
|
||||
|
||||
- Role tags hug their content: ``<user>{content}</user>``, no inner
|
||||
newlines.
|
||||
- Assistant reasoning is gated on ``enable_thinking``: on, the turn
|
||||
opens ``<think>{reasoning}</think>`` verbatim (empty reasoning
|
||||
included); off, it opens with a bare ``</think>`` and message
|
||||
reasoning is not rendered. Content and tool-call args render verbatim.
|
||||
- Tool-call args pack tightly
|
||||
(``<arg_key>k</arg_key><arg_value>v</arg_value>``) and the tools
|
||||
section ends at ``</available_tools>``.
|
||||
- The ``<system>`` block is emitted whenever there is system content,
|
||||
tools, or ``enable_thinking`` — even if that leaves it empty.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,8 +53,10 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
)
|
||||
from renderers.configs import LagunaXS2RendererConfig
|
||||
from renderers.configs import LagunaXS2RendererConfig, LagunaXS21RendererConfig
|
||||
from renderers.parsing import parse_laguna_xs2
|
||||
|
||||
_DEFAULT_SYSTEM_MESSAGE = (
|
||||
@@ -76,15 +93,32 @@ _TOOLS_FOOTER_NO_THINKING = (
|
||||
"</tool_call>"
|
||||
)
|
||||
|
||||
# XS-2.1 tools section: this header, one tojson line per tool, then a
|
||||
# bare "</available_tools>" close.
|
||||
_TOOLS_HEADER_XS21 = (
|
||||
"### Tools\n\n"
|
||||
"You may call functions to assist with the user query.\n"
|
||||
"All available function signatures are listed below:\n"
|
||||
"<available_tools>\n"
|
||||
)
|
||||
|
||||
|
||||
class LagunaXS2Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: LagunaXS2RendererConfig | None = None,
|
||||
config: LagunaXS2RendererConfig | LagunaXS21RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or LagunaXS2RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
# Both templates bake in the same default Poolside system prompt;
|
||||
# an empty caller-supplied system message opts out of the
|
||||
# <system> block (each variant's render mirrors its own gate).
|
||||
self._default_system_message = _DEFAULT_SYSTEM_MESSAGE
|
||||
|
||||
self._eos = self._token_id("〈|EOS|〉")
|
||||
self._think = self._token_id("<think>")
|
||||
@@ -180,7 +214,7 @@ class LagunaXS2Renderer:
|
||||
emit_special(self._eos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── System header (absorbs messages[0] if it's a system message) ──
|
||||
system_content = _DEFAULT_SYSTEM_MESSAGE
|
||||
system_content = self._default_system_message
|
||||
system_msg_idx = -1
|
||||
caller_has_system = bool(messages and messages[0].get("role") == "system")
|
||||
if caller_has_system:
|
||||
@@ -192,16 +226,12 @@ class LagunaXS2Renderer:
|
||||
# gate: when the caller passes an empty system message and no tools,
|
||||
# the whole ``<system>...</system>`` block is omitted.
|
||||
if has_sys_content or tools:
|
||||
# The template emits ``<system>\n`` then conditionally a second
|
||||
# ``\n``. Bundle those into one emit so BPE merges ``\n\n`` into
|
||||
# its single-token form (rather than two ``\n`` atoms).
|
||||
emit_text(
|
||||
"<system>\n\n" if has_sys_content else "<system>\n",
|
||||
-1,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
if has_sys_content:
|
||||
# The template emits ``<system>\n`` then a second ``\n``
|
||||
# before the system body. Bundle those into one emit so BPE
|
||||
# merges ``\n\n`` into its single-token form (rather than
|
||||
# two ``\n`` atoms).
|
||||
emit_text("<system>\n\n", -1, is_sampled=False, is_content=False)
|
||||
# If the caller provided system content, it's body bytes;
|
||||
# otherwise this is the default system prompt (scaffold).
|
||||
sys_is_content = caller_has_system
|
||||
@@ -220,6 +250,11 @@ class LagunaXS2Renderer:
|
||||
if self.config.enable_thinking
|
||||
else _TOOLS_FOOTER_NO_THINKING
|
||||
)
|
||||
if not has_sys_content:
|
||||
# No system body: ``<system>\n`` runs straight into the
|
||||
# tools header's ``\n\n`` — encode them together so BPE
|
||||
# merges the ``\n\n\n`` seam as the template does.
|
||||
tool_text = "<system>\n" + tool_text
|
||||
emit_text(tool_text, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n</system>\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
@@ -326,6 +361,11 @@ class LagunaXS2Renderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# The canonical assistant-turn close is ``</assistant>``. ``〈|EOS|〉``
|
||||
# also stops generation; either being the final token means the turn
|
||||
@@ -441,7 +481,12 @@ class LagunaXS2Renderer:
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
if self.config.render_assistant_messages_raw:
|
||||
# Raw passthrough is an XS.2-only template gate; the XS-2.1
|
||||
# config doesn't define it.
|
||||
if (
|
||||
isinstance(self.config, LagunaXS2RendererConfig)
|
||||
and self.config.render_assistant_messages_raw
|
||||
):
|
||||
self._render_assistant_raw(
|
||||
msg_idx,
|
||||
content,
|
||||
@@ -573,3 +618,347 @@ class LagunaXS2Renderer:
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
|
||||
class LagunaXS21Renderer(LagunaXS2Renderer):
|
||||
"""Laguna-XS-2.1 — mirrors the ``poolside/Laguna-XS-2.1`` chat
|
||||
template (upstream rev ``575f0f28``); see the module docstring for
|
||||
its format.
|
||||
|
||||
Token wiring, stop tokens, and the parsing skeleton are shared with
|
||||
:class:`LagunaXS2Renderer`; ``render``, ``bridge_to_next_turn``, and
|
||||
the assistant emit implement this template's format.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: LagunaXS21RendererConfig | None = None,
|
||||
):
|
||||
super().__init__(tokenizer, config or LagunaXS21RendererConfig())
|
||||
|
||||
def render(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> RenderedTokens:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
# Role tags hug the body with no whitespace, so a BPE merge
|
||||
# can pull wrap bytes and body bytes into one token —
|
||||
# overlap attribution keeps every body byte in the content
|
||||
# run.
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments, overlap_is_content=True
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
emit_special(self._eos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── System header (absorbs messages[0] if it's a system message) ──
|
||||
system_content = self._default_system_message
|
||||
caller_has_system = bool(messages and messages[0].get("role") == "system")
|
||||
if caller_has_system:
|
||||
system_content = self._visible_text(messages[0].get("content"))
|
||||
|
||||
has_sys_content = bool(system_content and system_content.strip())
|
||||
# The template's gate is ``has_sys or tools or enable_thinking`` —
|
||||
# an empty caller system message opts out of the default, and with
|
||||
# neither tools nor thinking the block vanishes entirely.
|
||||
if has_sys_content or tools or self.config.enable_thinking:
|
||||
# The whole header is one plain-text run — ``<system>`` glues
|
||||
# straight onto the body with no newline — so it must be
|
||||
# tokenized in a single BPE pass. In the header, content bytes
|
||||
# exist exactly when the caller supplied the system message
|
||||
# (the default prompt is scaffold), so the is_content bit also
|
||||
# selects the message index: body → 0, everything else → -1.
|
||||
header_segs: list[tuple[str, bool]] = [("<system>", False)]
|
||||
if has_sys_content:
|
||||
header_segs.append((system_content.rstrip(), caller_has_system))
|
||||
if tools:
|
||||
header_segs.append(("\n\n", False))
|
||||
if tools:
|
||||
tool_text = _TOOLS_HEADER_XS21
|
||||
for tool in tools:
|
||||
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
|
||||
tool_text += "</available_tools>"
|
||||
header_segs.append((tool_text, False))
|
||||
header_segs.append(("</system>\n", False))
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, header_segs, overlap_is_content=True
|
||||
):
|
||||
emit_special(
|
||||
tok_id,
|
||||
0 if is_content else -1,
|
||||
is_sampled=False,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
# ── Per-message loop ──────────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
match msg["role"]:
|
||||
case "system":
|
||||
# The template slices a leading system message off the
|
||||
# loop (it lives in the header); later ones render.
|
||||
if i == 0:
|
||||
continue
|
||||
sys_segs: list[tuple[str, bool]] = [("<system>", False)]
|
||||
if content:
|
||||
sys_segs.append((content, True))
|
||||
sys_segs.append(("</system>\n", False))
|
||||
emit_text_segments(sys_segs, i, is_sampled=False)
|
||||
case "user":
|
||||
user_segs: list[tuple[str, bool]] = [("<user>", False)]
|
||||
if content:
|
||||
user_segs.append((content, True))
|
||||
user_segs.append(("</user>\n", False))
|
||||
emit_text_segments(user_segs, i, is_sampled=False)
|
||||
case "assistant":
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
case "tool":
|
||||
tool_segs: list[tuple[str, bool]] = [("<tool_response>", False)]
|
||||
if content:
|
||||
tool_segs.append((content, True))
|
||||
tool_segs.append(("</tool_response>\n", False))
|
||||
emit_text_segments(tool_segs, i, is_sampled=False)
|
||||
|
||||
# ── Generation prompt (no newline after <assistant>) ──────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
# The XS-2.1 template renders reasoning and content verbatim (no
|
||||
# newline wrapping), so the parse is verbatim too.
|
||||
return parse_laguna_xs2(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
stop_ids={self._assistant_end, self._eos},
|
||||
think_id=self._think,
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tools=tools,
|
||||
strip_newlines=False,
|
||||
)
|
||||
|
||||
def bridge_to_next_turn(
|
||||
self,
|
||||
previous_prompt_ids: list[int],
|
||||
previous_completion_ids: list[int],
|
||||
new_messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> RenderedTokens | None:
|
||||
if (
|
||||
not previous_prompt_ids
|
||||
or not new_messages
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
# ``</assistant>`` is the canonical turn close; ``〈|EOS|〉`` also
|
||||
# stops generation. Truncation (no stop token at the tail)
|
||||
# synthesises the close. The inter-turn ``\n`` the template puts
|
||||
# after ``</assistant>`` is prepended to the first extension
|
||||
# message below so the seam encodes with the tag run.
|
||||
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
|
||||
stop_ids = {self._assistant_end, self._eos}
|
||||
if (
|
||||
not previous_ids[len(previous_prompt_ids) :]
|
||||
or previous_ids[-1] not in stop_ids
|
||||
):
|
||||
previous_ids.append(self._assistant_end)
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments, overlap_is_content=True
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
_OPEN = {"user": "<user>", "system": "<system>", "tool": "<tool_response>"}
|
||||
_CLOSE = {
|
||||
"user": "</user>\n",
|
||||
"system": "</system>\n",
|
||||
"tool": "</tool_response>\n",
|
||||
}
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
if role not in _OPEN:
|
||||
return None
|
||||
content = self._visible_text(msg.get("content"))
|
||||
lead = "\n" if i == 0 else ""
|
||||
segs: list[tuple[str, bool]] = [(lead + _OPEN[role], False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
segs.append((_CLOSE[role], False))
|
||||
emit_text_segments(segs, i)
|
||||
|
||||
emit_special(self._assistant, -1)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
else:
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
msg: Message,
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
reasoning_content = msg["reasoning_content"]
|
||||
else:
|
||||
part_thinking = self._thinking_text(msg.get("content"))
|
||||
if part_thinking:
|
||||
reasoning_content = part_thinking
|
||||
|
||||
# ``<assistant>`` plus the think tag that follows are exactly the
|
||||
# generation prompt for the active mode — template-injected
|
||||
# scaffolding the model never samples.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if self.config.enable_thinking:
|
||||
# ``<think>{reasoning}</think>`` renders verbatim, even when
|
||||
# the reasoning is empty; the opener is the gen-prompt
|
||||
# prefill, the rest the model sampled.
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
if reasoning_content:
|
||||
emit_text(reasoning_content, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
# Thinking off: any reasoning on the message is dropped and
|
||||
# the turn opens with the prefilled ``</think>``.
|
||||
emit_special(self._think_end, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if content:
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
inner = name
|
||||
if isinstance(arguments, dict):
|
||||
for k, v in arguments.items():
|
||||
inner += "<arg_key>" + k + "</arg_key>"
|
||||
if isinstance(v, str):
|
||||
val_text = v
|
||||
else:
|
||||
val_text = json.dumps(v, ensure_ascii=False)
|
||||
inner += "<arg_value>" + val_text + "</arg_value>"
|
||||
emit_text(inner, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+15
-4
@@ -9,7 +9,7 @@ verified.
|
||||
Notable differences from the Qwen / GLM family renderers:
|
||||
|
||||
* No ``<think>`` / reasoning channel — Llama-3 doesn't ship a
|
||||
reasoning-content concept, so ``preserve_*_thinking`` flags don't
|
||||
reasoning-content concept, so the ``thinking_retention`` flag doesn't
|
||||
apply.
|
||||
* ``<|begin_of_text|>`` (BOS) is emitted at the very start of every
|
||||
render. The chat template never omits it.
|
||||
@@ -51,6 +51,8 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Llama3RendererConfig
|
||||
@@ -94,14 +96,18 @@ class Llama3Renderer:
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Llama3RendererConfig | None = None,
|
||||
):
|
||||
# ``preserve_*_thinking`` are accepted but no-ops: Llama-3 ships no
|
||||
# ``thinking_retention`` is accepted but a no-op: Llama-3 ships no
|
||||
# reasoning_content channel, so there's never any past-assistant
|
||||
# thinking to retain or drop. The flags are stored on ``self.config``
|
||||
# for cross-renderer uniformity but never change the token stream —
|
||||
# thinking to retain or drop. The level is stored on ``self.config``
|
||||
# for cross-renderer uniformity but never changes the token stream —
|
||||
# the same contract as Kimi-K2 / Qwen3-VL (see the never-preserves
|
||||
# renderers in tests/test_preserve_thinking.py).
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or Llama3RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
|
||||
self._bos = self._token_id("<|begin_of_text|>")
|
||||
self._start_header = self._token_id("<|start_header_id|>")
|
||||
@@ -434,6 +440,11 @@ class Llama3Renderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
|
||||
+13
-12
@@ -24,7 +24,8 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import MiniMaxM2RendererConfig
|
||||
@@ -61,6 +62,10 @@ class MiniMaxM2Renderer:
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or MiniMaxM2RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"tool_cycle",
|
||||
)
|
||||
|
||||
self._bos = self._token_id("]~!b[")
|
||||
self._role = self._token_id("]~b]")
|
||||
@@ -237,18 +242,11 @@ class MiniMaxM2Renderer:
|
||||
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.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
orig_idx,
|
||||
ci,
|
||||
last_ui,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
@@ -330,6 +328,12 @@ class MiniMaxM2Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
@@ -471,7 +475,6 @@ class MiniMaxM2Renderer:
|
||||
conv_idx,
|
||||
last_user_index,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
@@ -502,9 +505,7 @@ class MiniMaxM2Renderer:
|
||||
# ``is_content == sampled_mask`` holds — every sampled token is
|
||||
# body, every scaffold token isn't.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
emit_thinking = reasoning_content and (
|
||||
conv_idx > last_user_index or preserve_thinking
|
||||
)
|
||||
emit_thinking = reasoning_content and conv_idx > last_user_index
|
||||
|
||||
if emit_thinking:
|
||||
# The thinking branch has the ``<think>`` special token
|
||||
|
||||
+215
-203
@@ -27,10 +27,11 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Nemotron3RendererConfig
|
||||
from renderers.configs import Nemotron3RendererConfig, Nemotron3UltraRendererConfig
|
||||
from renderers.parsing import parse_qwen35
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -75,52 +76,74 @@ def _render_extra_keys(obj: dict[str, Any], handled_keys: set[str]) -> list[str]
|
||||
return lines
|
||||
|
||||
|
||||
# Per-model ``ultra`` default, applied when the renderer config leaves it
|
||||
# ``None``. The Nemotron-3 family ships two chat-template variants: Nano /
|
||||
# Super share one; Ultra differs in the reasoning-block glue (no ``\n`` around
|
||||
# ``</think>``) and the thinking-truncation boundary (drop thinking on every
|
||||
# assistant turn before the last user message). BF16 and FP8 share the same
|
||||
# tokenizer and template. Hard-coded keyed by
|
||||
# ``tokenizer.name_or_path`` rather than probed from the live template — the
|
||||
# same convention as Qwen3.5's ``_ENABLE_THINKING_DEFAULTS`` (avoids pulling
|
||||
# ``apply_chat_template`` onto the construction hot path and keeps
|
||||
# bring-your-own-tokenizer use working).
|
||||
_ULTRA_DEFAULTS: dict[str, bool] = {
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": False,
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": False,
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16": True,
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8": True,
|
||||
}
|
||||
# The Nemotron-3 family ships two chat-template variants. Nano / Super share
|
||||
# one (renderer ``Nemotron3Renderer`` / config ``name="nemotron-3"``); Ultra
|
||||
# differs in the reasoning-block glue — no ``\n`` around ``</think>`` — and is
|
||||
# the ``Nemotron3UltraRenderer`` subclass (``name="nemotron-3-ultra"``). Which
|
||||
# variant a checkpoint uses is carried by ``MODEL_RENDERER_MAP``, so the right
|
||||
# renderer class is constructed and the variant is encoded by the class itself.
|
||||
|
||||
|
||||
def _default_ultra(tokenizer) -> bool:
|
||||
"""Hard-coded ``ultra`` default for ``tokenizer``'s model.
|
||||
def _is_super(tokenizer) -> bool:
|
||||
"""Does this checkpoint use the **Super** flavour of the shared Nano/Super
|
||||
template — i.e. the one whose Jinja defines the ``low_effort`` kwarg?
|
||||
|
||||
Falls back to ``False`` (the Nano / Super template, and the majority of
|
||||
the family) for unknown / fine-tuned checkpoints whose ``name_or_path``
|
||||
isn't in ``_ULTRA_DEFAULTS`` — pass an explicit ``ultra=True`` for an
|
||||
Ultra fine-tune or a locally-pathed Ultra checkpoint.
|
||||
Nano and Super share one config (``nemotron-3``), so the model name is the
|
||||
only signal that separates them. Detected by substring; unknown / fine-tuned
|
||||
checkpoints default to ``False`` so ``low_effort`` is a no-op there —
|
||||
matching how the Nano template silently ignores it.
|
||||
"""
|
||||
return _ULTRA_DEFAULTS.get(getattr(tokenizer, "name_or_path", ""), False)
|
||||
return "super" in (getattr(tokenizer, "name_or_path", "") or "").lower()
|
||||
|
||||
|
||||
class Nemotron3Renderer:
|
||||
"""Deterministic message → token renderer for Nemotron 3 models."""
|
||||
"""Deterministic message → token renderer for Nemotron-3 Nano / Super.
|
||||
|
||||
The Ultra variant (distinct ``</think>`` glue) is the
|
||||
:class:`Nemotron3UltraRenderer` subclass below; both are registered under
|
||||
their own discriminator and differ only by the class-level hooks here.
|
||||
"""
|
||||
|
||||
# Variant hooks (overridden by ``Nemotron3UltraRenderer``): the default
|
||||
# config to build when none is passed, and whether to use Ultra's
|
||||
# reasoning-block glue.
|
||||
_config_cls: type = Nemotron3RendererConfig
|
||||
_ultra: bool = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Nemotron3RendererConfig | None = None,
|
||||
config: Nemotron3RendererConfig | Nemotron3UltraRendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
cfg = config or Nemotron3RendererConfig()
|
||||
# ``ultra=None`` defers to the model's known default (see
|
||||
# ``_ULTRA_DEFAULTS``). Materialise here so downstream reads see a
|
||||
# concrete bool; rebind the frozen config with the resolved value so
|
||||
# introspection sees the same.
|
||||
if cfg.ultra is None:
|
||||
cfg = cfg.model_copy(update={"ultra": _default_ultra(tokenizer)})
|
||||
cfg = config or type(self)._config_cls()
|
||||
self.config = cfg
|
||||
if not cfg.truncate_history_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
elif not cfg.enable_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
else:
|
||||
implied_thinking_retention = "tool_cycle"
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
cfg,
|
||||
implied_thinking_retention,
|
||||
)
|
||||
|
||||
# Resolve the per-variant reasoning-effort hint appended to the last
|
||||
# user message. Ultra honours ``medium_effort``; Super honours
|
||||
# ``low_effort``; Nano honours neither. The non-matching kwarg is
|
||||
# silently ignored (empty hint), exactly as ``apply_chat_template``
|
||||
# ignores a template variable the variant's Jinja never defines.
|
||||
if self._ultra:
|
||||
self._effort_hint = (
|
||||
"\n\n{reasoning effort: efficient}"
|
||||
if getattr(cfg, "medium_effort", False)
|
||||
else ""
|
||||
)
|
||||
elif getattr(cfg, "low_effort", False) and _is_super(tokenizer):
|
||||
self._effort_hint = "\n\n{reasoning effort: low}"
|
||||
else:
|
||||
self._effort_hint = ""
|
||||
|
||||
# Look up special token IDs from the tokenizer (not hardcoded).
|
||||
# <|endoftext|> is optional: Nemotron-3 Nano / Super tokenizers ship
|
||||
@@ -321,9 +344,12 @@ class Nemotron3Renderer:
|
||||
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build system content: user's system text first, then tools
|
||||
# Build system content: user's system text first, then tools.
|
||||
# The template emits ``system_message`` verbatim (no trim) and
|
||||
# gates the ``\n\n`` separator on its raw length, so keep the
|
||||
# caller's content unstripped.
|
||||
if first_is_system:
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
sys_content = self._render_content(messages[0].get("content"))
|
||||
else:
|
||||
sys_content = ""
|
||||
|
||||
@@ -351,7 +377,7 @@ class Nemotron3Renderer:
|
||||
|
||||
elif first_is_system:
|
||||
sys_idx = orig_idx(0)
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
sys_content = self._render_content(messages[0].get("content"))
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
sys_segments2: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
@@ -360,22 +386,13 @@ class Nemotron3Renderer:
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Track the most-recent plain (non-tool-call) assistant so we can
|
||||
# preserve its reasoning while stripping reasoning from earlier
|
||||
# assistants — the Nemotron-3 template matches this pattern.
|
||||
last_plain_assistant_idx = -1
|
||||
for j in range(len(messages) - 1, -1, -1):
|
||||
if messages[j].get("role") == "assistant" and not messages[j].get(
|
||||
"tool_calls"
|
||||
):
|
||||
last_plain_assistant_idx = j
|
||||
break
|
||||
|
||||
# Ultra truncates thinking on every assistant turn *before the last
|
||||
# user message* (template rule ``loop.index0 < last_user_idx``),
|
||||
# whereas Nano/Super preserve only the last plain assistant. Compute
|
||||
# the last-user index over the normalized ``messages`` list (a leading
|
||||
# system never holds a user, so the relative comparison is unaffected).
|
||||
# All Nemotron-3 variants (Nano / Super / Ultra) truncate historical
|
||||
# thinking on every assistant turn *before the last user message* —
|
||||
# the template rule ``truncate_history_thinking and loop.index0 <
|
||||
# last_user_idx`` is byte-identical across the three chat templates.
|
||||
# Compute the last-user index over the normalized ``messages`` list (a
|
||||
# leading system never holds a user, so the relative comparison is
|
||||
# unaffected).
|
||||
last_user_idx_norm = -1
|
||||
for j in range(len(messages) - 1, -1, -1):
|
||||
if messages[j].get("role") == "user":
|
||||
@@ -385,7 +402,10 @@ class Nemotron3Renderer:
|
||||
# ── 2. Iterate messages ─────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
role = msg["role"]
|
||||
content = self._render_content(msg.get("content")).strip()
|
||||
# Keep content unstripped: the template emits user / system / tool
|
||||
# content verbatim, and assistant trimming happens inside
|
||||
# ``_assistant_body`` exactly where the template applies it.
|
||||
content = self._render_content(msg.get("content"))
|
||||
msg_orig_idx = orig_idx(i)
|
||||
|
||||
if role == "system":
|
||||
@@ -400,6 +420,12 @@ class Nemotron3Renderer:
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
# Reasoning-effort hint rides on the LAST user message only,
|
||||
# glued to the content so BPE sees them as one chunk (matching
|
||||
# the template's ``content + '\n\n{reasoning effort: …}'``). It
|
||||
# is template scaffold, not caller content → is_content=False.
|
||||
if self._effort_hint and i == last_user_idx_norm:
|
||||
user_segments.append((self._effort_hint, False))
|
||||
emit_text_segments(user_segments, msg_orig_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._im_end, msg_orig_idx, is_sampled=False, is_content=False
|
||||
@@ -407,26 +433,18 @@ class Nemotron3Renderer:
|
||||
emit_text("\n", msg_orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
if self.config.ultra:
|
||||
is_last_turn = i >= last_user_idx_norm
|
||||
else:
|
||||
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.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
# Template: ``include_content = not (truncate_history_thinking
|
||||
# and loop.index0 < last_user_idx)``.
|
||||
include_content = (
|
||||
not self.config.truncate_history_thinking or i >= last_user_idx_norm
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
msg_orig_idx,
|
||||
content,
|
||||
is_last_turn=is_last_turn,
|
||||
preserve_thinking=preserve_thinking,
|
||||
include_content=include_content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_ids=emit_ids,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
@@ -516,6 +534,17 @@ class Nemotron3Renderer:
|
||||
not previous_prompt_ids
|
||||
or not new_messages
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
# An active effort hint rides on the *last* user message. Appending
|
||||
# a new turn can move which user is last, which would strand the
|
||||
# hint on the frozen previous prompt — the append-only bridge can't
|
||||
# rewrite it. Bail so the caller does a full, correct re-render.
|
||||
or self._effort_hint
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
@@ -585,7 +614,9 @@ class Nemotron3Renderer:
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._render_content(msg.get("content")).strip()
|
||||
# Unstripped — the template emits user / system / tool content
|
||||
# verbatim (see :meth:`render`).
|
||||
content = self._render_content(msg.get("content"))
|
||||
if role == "user":
|
||||
emit_special(self._im_start, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
@@ -646,29 +677,10 @@ class Nemotron3Renderer:
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
is_last_turn: bool,
|
||||
preserve_thinking: bool = False,
|
||||
include_content: bool,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_ids,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Extract reasoning_content
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
reasoning_content = msg["reasoning_content"]
|
||||
elif "</think>" in content:
|
||||
before_think_end, after_think_end = content.split("</think>", 1)
|
||||
if "<think>" in before_think_end:
|
||||
reasoning_content = before_think_end.split("<think>")[-1].lstrip("\n")
|
||||
else:
|
||||
reasoning_content = before_think_end.lstrip("\n")
|
||||
reasoning_content = reasoning_content.rstrip("\n")
|
||||
content = after_think_end.lstrip("\n")
|
||||
|
||||
reasoning_content = reasoning_content.strip()
|
||||
ultra = self.config.ultra
|
||||
|
||||
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
|
||||
# at inference the chat template emits these as the generation
|
||||
# prompt and the model never samples them. Marking the role tag
|
||||
@@ -678,124 +690,110 @@ class Nemotron3Renderer:
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Nemotron 3 keeps reasoning on the most-recent plain assistant but
|
||||
# strips it from historical turns, which collapse to an empty
|
||||
# <think></think> block. Empty <think></think> is also emitted when
|
||||
# the turn has no reasoning at all. The trailing ``\n`` (when
|
||||
# tool_calls follow) is glued to ``content`` in a single emit_text
|
||||
# so BPE sees ``content\n`` as one chunk, matching how
|
||||
# apply_chat_template tokenises the concatenated template string.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
# A \n is always required between the text/think block and the first
|
||||
# <tool_call>, whether the content is empty or not.
|
||||
content_suffix = "\n" if tool_calls else ""
|
||||
|
||||
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)
|
||||
# Ultra: <think>\n{reasoning}</think>{content} (no \n around </think>).
|
||||
# Nano/Super: <think>\n{reasoning}\n</think>\n{content}.
|
||||
emit_text(
|
||||
("\n" + reasoning_content)
|
||||
if ultra
|
||||
else ("\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); Ultra glues directly.
|
||||
emit_text(
|
||||
(content + content_suffix)
|
||||
if ultra
|
||||
else ("\n" + content + content_suffix),
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
elif reasoning_content:
|
||||
# Historical assistant whose reasoning got stripped. Nano/Super keep
|
||||
# a single \n between the collapsed <think></think> and the content
|
||||
# as a marker that reasoning existed; Ultra glues content directly.
|
||||
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)
|
||||
if ultra
|
||||
else ("\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, 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
|
||||
# separator to the next block).
|
||||
if tool_calls:
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\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
|
||||
# per-argument rendering below still works.
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
if isinstance(arguments, dict):
|
||||
for arg_name, arg_value in arguments.items():
|
||||
if isinstance(arg_value, (dict, list)):
|
||||
value_str = json.dumps(arg_value, ensure_ascii=False)
|
||||
else:
|
||||
value_str = str(arg_value)
|
||||
emit_text(
|
||||
"<parameter="
|
||||
+ arg_name
|
||||
+ ">\n"
|
||||
+ value_str
|
||||
+ "\n</parameter>\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=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, 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.
|
||||
# Build the body (everything between ``assistant\n`` and ``<|im_end|>``)
|
||||
# as a single string mirroring the chat template's own string algebra,
|
||||
# then tokenise it in one pass. The ``<think>`` / ``</think>`` /
|
||||
# ``<tool_call>`` / ``</tool_call>`` markers are added tokens, so the
|
||||
# tokenizer isolates them — encoding the assembled body yields the same
|
||||
# ids as ``apply_chat_template`` (which likewise encodes a rendered
|
||||
# string). The whole body is sampled content; ``<|im_end|>`` is the
|
||||
# model's stop signal (sampled), and the inter-turn ``\n`` is not.
|
||||
body = self._assistant_body(msg, content, include_content=include_content)
|
||||
if body:
|
||||
emit_text(body, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
def _assistant_body(
|
||||
self, msg: Message, raw_content: str, *, include_content: bool
|
||||
) -> str:
|
||||
"""Assemble the assistant body string exactly as the chat template.
|
||||
|
||||
``include_content`` is the template's ``not (truncate_history_thinking
|
||||
and loop.index0 < last_user_idx)`` (already OR-ed with the
|
||||
``thinking_retention`` override by the caller): ``True`` keeps the
|
||||
full think+content block,
|
||||
``False`` collapses historical thinking to an empty ``<think></think>``.
|
||||
"""
|
||||
ultra = self._ultra
|
||||
|
||||
# 1. Assemble ``content`` — wrap a ``reasoning_content`` field in
|
||||
# <think> tags (raw, not stripped: interior whitespace is part of
|
||||
# the reasoning), else prepend an empty <think></think> only when
|
||||
# the content carries no inline think tags of its own (which are
|
||||
# passed through verbatim, like the template).
|
||||
reasoning = msg.get("reasoning_content")
|
||||
if isinstance(reasoning, str) and reasoning.strip():
|
||||
if ultra:
|
||||
content = "<think>\n" + reasoning + "</think>" + raw_content
|
||||
else:
|
||||
content = "<think>\n" + reasoning + "\n</think>\n" + raw_content
|
||||
else:
|
||||
content = raw_content
|
||||
if "<think>" not in content and "</think>" not in content:
|
||||
content = "<think></think>" + content
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
|
||||
if tool_calls:
|
||||
parts: list[str] = []
|
||||
if content.strip():
|
||||
if include_content:
|
||||
parts.append(content.strip() + "\n")
|
||||
else:
|
||||
# Drop historical thinking: keep only what follows the last
|
||||
# </think> (or precedes a dangling <think>), then re-stamp
|
||||
# an empty block. Nano/Super trim the remainder; Ultra glues
|
||||
# it raw (its template omits the trailing ``| trim``).
|
||||
c = content
|
||||
if "</think>" in c:
|
||||
c = c.split("</think>")[-1]
|
||||
elif "<think>" in c:
|
||||
c = c.split("<think>")[0]
|
||||
c = "<think></think>" + (c if ultra else c.strip())
|
||||
if c:
|
||||
parts.append(c + "\n")
|
||||
else:
|
||||
# Non-string / empty content: bare collapsed think block, no \n.
|
||||
parts.append("<think></think>")
|
||||
for tc in tool_calls:
|
||||
parts.append(self._format_tool_call(tc))
|
||||
return "".join(parts)
|
||||
|
||||
# No tool calls.
|
||||
if include_content:
|
||||
return content.strip()
|
||||
c = content
|
||||
if "<think>" in c and "</think>" in c:
|
||||
c = "<think></think>" + c.split("</think>")[-1]
|
||||
return c.strip()
|
||||
|
||||
@staticmethod
|
||||
def _format_tool_call(tc: dict[str, Any]) -> str:
|
||||
"""Render one tool call as ``<tool_call>…</tool_call>\\n`` XML."""
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
# per-argument rendering below still works.
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
parts = ["<tool_call>\n<function=" + name + ">\n"]
|
||||
if isinstance(arguments, dict):
|
||||
for arg_name, arg_value in arguments.items():
|
||||
if isinstance(arg_value, (dict, list)):
|
||||
value_str = json.dumps(arg_value, ensure_ascii=False)
|
||||
else:
|
||||
value_str = str(arg_value)
|
||||
parts.append(
|
||||
"<parameter=" + arg_name + ">\n" + value_str + "\n</parameter>\n"
|
||||
)
|
||||
parts.append("</function>\n</tool_call>\n")
|
||||
return "".join(parts)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Tool message rendering
|
||||
# ------------------------------------------------------------------
|
||||
@@ -840,3 +838,17 @@ class Nemotron3Renderer:
|
||||
if not next_is_tool:
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
emit_text("\n", oi, is_sampled=False, is_content=False)
|
||||
|
||||
|
||||
class Nemotron3UltraRenderer(Nemotron3Renderer):
|
||||
"""Renderer for Nemotron-3 **Ultra**.
|
||||
|
||||
Identical to :class:`Nemotron3Renderer` except the reasoning block is glued
|
||||
as ``<think>\\n{reasoning}</think>{content}`` (no ``\\n`` around
|
||||
``</think>``) and truncated historical turns collapse to
|
||||
``<think></think>{content}`` (no ``\\n``) — the difference is carried by the
|
||||
``_ultra`` class hook. Honours the Ultra-only ``medium_effort`` kwarg.
|
||||
"""
|
||||
|
||||
_config_cls = Nemotron3UltraRendererConfig
|
||||
_ultra = True
|
||||
|
||||
@@ -20,6 +20,7 @@ import re
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from renderers.base import ParsedToolCall, ToolCallParseStatus
|
||||
from renderers.hermes import HermesToolParser
|
||||
|
||||
|
||||
# ── Shared helpers ───────────────────────────────────────────────────
|
||||
@@ -458,6 +459,7 @@ class ThinkTextReasoningParser:
|
||||
|
||||
|
||||
TOOL_PARSERS: dict[str, type] = {
|
||||
"hermes": HermesToolParser,
|
||||
"qwen3": Qwen3ToolParser,
|
||||
"qwen3.5": Qwen35ToolParser,
|
||||
"glm": GlmToolParser,
|
||||
|
||||
+226
-16
@@ -556,6 +556,205 @@ def _parse_glm_tool_calls(
|
||||
return tool_calls
|
||||
|
||||
|
||||
# ── Hy3: <think>…</think> content <tool_calls> <tool_call>name<tool_sep> …
|
||||
# <arg_key>k</arg_key> <arg_value>v</arg_value> … </tool_call> </tool_calls>
|
||||
# Same arg_key/arg_value token scheme as GLM, but each call names the function
|
||||
# between <tool_call> and <tool_sep>, and the calls are wrapped in an outer
|
||||
# <tool_calls></tool_calls> pair. All markers are single special tokens.
|
||||
|
||||
|
||||
def parse_hy3(
|
||||
tokenizer,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
stop_ids: set[int],
|
||||
assistant_id: int,
|
||||
think_id: int,
|
||||
think_end_id: int,
|
||||
tool_calls_id: int,
|
||||
tool_call_id: int,
|
||||
tool_call_end_id: int,
|
||||
tool_sep_id: int,
|
||||
arg_key_id: int,
|
||||
arg_key_end_id: int,
|
||||
arg_value_id: int,
|
||||
arg_value_end_id: int,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
"""Parse Hy3 completion tokens.
|
||||
|
||||
Handles both the inference stream (``reasoning</think>content…`` in
|
||||
``low``/``high`` mode, or bare ``content…`` in ``no_think`` mode, since
|
||||
the ``<think>`` opener lives in the generation prompt) and a round-trip
|
||||
slice that still carries a leading ``<|hy_Assistant|>`` opener and a
|
||||
full ``<think>…</think>`` block.
|
||||
"""
|
||||
ids = _strip_stop_tokens(token_ids, stop_ids)
|
||||
|
||||
# ``token_span`` values are reported relative to this stop-stripped stream
|
||||
# (the documented contract), so track every prefix we slice off below.
|
||||
offset = 0
|
||||
|
||||
# A round-trip slice includes the assistant role marker; the live
|
||||
# inference stream does not. Drop a single leading opener so both paths
|
||||
# land on the same downstream logic.
|
||||
if ids and ids[0] == assistant_id:
|
||||
ids = ids[1:]
|
||||
offset += 1
|
||||
|
||||
reasoning = None
|
||||
think_end = _find(ids, think_end_id)
|
||||
if think_end != -1:
|
||||
reasoning_ids = [t for t in ids[:think_end] if t != think_id]
|
||||
reasoning = _decode(tokenizer, reasoning_ids).strip()
|
||||
ids = ids[think_end + 1 :]
|
||||
offset += think_end + 1
|
||||
elif think_id in set(ids):
|
||||
# Reasoning opened but never closed (truncation): everything after
|
||||
# the opener is reasoning; there is no committed content yet.
|
||||
think_start = _find(ids, think_id)
|
||||
reasoning = _decode(tokenizer, ids[think_start + 1 :]).strip()
|
||||
return ParsedResponse(
|
||||
content="", reasoning_content=reasoning or None, tool_calls=[]
|
||||
)
|
||||
|
||||
# Content ends at the first tool marker — the outer <tool_calls> wrapper
|
||||
# or, defensively, a bare <tool_call> the model emitted without it.
|
||||
marker_positions = [
|
||||
p for p in (_find(ids, tool_calls_id), _find(ids, tool_call_id)) if p != -1
|
||||
]
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
if marker_positions:
|
||||
tool_start = min(marker_positions)
|
||||
content_text = _decode(tokenizer, ids[:tool_start]).strip()
|
||||
tool_calls = _parse_hy3_tool_calls(
|
||||
tokenizer,
|
||||
ids[tool_start:],
|
||||
tool_call_id,
|
||||
tool_call_end_id,
|
||||
tool_sep_id,
|
||||
arg_key_id,
|
||||
arg_key_end_id,
|
||||
arg_value_id,
|
||||
arg_value_end_id,
|
||||
section_offset=offset + tool_start,
|
||||
param_index=_build_param_type_index(tools),
|
||||
)
|
||||
else:
|
||||
content_text = _decode(tokenizer, ids).strip()
|
||||
|
||||
return ParsedResponse(
|
||||
content=content_text,
|
||||
reasoning_content=reasoning or None,
|
||||
tool_calls=tool_calls,
|
||||
)
|
||||
|
||||
|
||||
def _parse_hy3_tool_calls(
|
||||
tokenizer,
|
||||
ids,
|
||||
tc_id,
|
||||
tc_end_id,
|
||||
sep_id,
|
||||
ak_id,
|
||||
ake_id,
|
||||
av_id,
|
||||
ave_id,
|
||||
*,
|
||||
section_offset: int,
|
||||
param_index: dict[str, dict[str, dict[str, Any]]],
|
||||
) -> list[ParsedToolCall]:
|
||||
"""Parse Hy3-style tool calls: ``<tool_call>name<tool_sep>`` then
|
||||
arg_key/arg_value pairs, all by token ID. The outer ``<tool_calls>``
|
||||
wrapper and inter-block newlines are skipped by scanning for the
|
||||
per-call ``<tool_call>`` opener. ``section_offset`` shifts recorded
|
||||
``token_span`` values back into the stop-stripped completion stream
|
||||
(``ids`` here is a suffix of it)."""
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
i = 0
|
||||
while i < len(ids):
|
||||
if ids[i] == tc_id:
|
||||
end = _find(ids, tc_end_id, i + 1)
|
||||
if end == -1:
|
||||
raw = _decode(tokenizer, ids[i + 1 :])
|
||||
tool_calls.append(
|
||||
ParsedToolCall(
|
||||
raw=raw,
|
||||
token_span=(section_offset + i, section_offset + len(ids)),
|
||||
status=ToolCallParseStatus.UNCLOSED_BLOCK,
|
||||
)
|
||||
)
|
||||
break
|
||||
block = ids[i + 1 : end]
|
||||
block_text = _decode(tokenizer, block)
|
||||
span = (section_offset + i, section_offset + end + 1)
|
||||
|
||||
# Name sits between <tool_call> and <tool_sep>. Fall back to the
|
||||
# first <arg_key> boundary if the separator is missing.
|
||||
sep = _find(block, sep_id)
|
||||
if sep != -1:
|
||||
name = _decode(tokenizer, block[:sep]).strip()
|
||||
arg_ids = block[sep + 1 :]
|
||||
else:
|
||||
first_ak = _find(block, ak_id)
|
||||
if first_ak == -1:
|
||||
name = _decode(tokenizer, block).strip()
|
||||
arg_ids = []
|
||||
else:
|
||||
name = _decode(tokenizer, block[:first_ak]).strip()
|
||||
arg_ids = block[first_ak:]
|
||||
|
||||
params = param_index.get(name, {})
|
||||
arguments: dict = {}
|
||||
structure_broke = False
|
||||
any_json_fallback = False
|
||||
j = 0
|
||||
while j < len(arg_ids):
|
||||
if arg_ids[j] == ak_id:
|
||||
ake = _find(arg_ids, ake_id, j + 1)
|
||||
if ake == -1:
|
||||
structure_broke = True
|
||||
break
|
||||
key = _decode(tokenizer, arg_ids[j + 1 : ake]).strip()
|
||||
av = _find(arg_ids, av_id, ake + 1)
|
||||
if av == -1:
|
||||
structure_broke = True
|
||||
break
|
||||
ave = _find(arg_ids, ave_id, av + 1)
|
||||
if ave == -1:
|
||||
structure_broke = True
|
||||
break
|
||||
val_text = _decode(tokenizer, arg_ids[av + 1 : ave]).strip()
|
||||
value, used_fallback = _coerce_arg_value(val_text, params.get(key))
|
||||
arguments[key] = value
|
||||
any_json_fallback = any_json_fallback or used_fallback
|
||||
j = ave + 1
|
||||
else:
|
||||
j += 1
|
||||
|
||||
if not name:
|
||||
status = ToolCallParseStatus.MISSING_NAME
|
||||
elif structure_broke:
|
||||
status = ToolCallParseStatus.MALFORMED_STRUCTURE
|
||||
elif any_json_fallback:
|
||||
status = ToolCallParseStatus.INVALID_JSON
|
||||
else:
|
||||
status = ToolCallParseStatus.OK
|
||||
tool_calls.append(
|
||||
ParsedToolCall(
|
||||
raw=block_text,
|
||||
name=name or None,
|
||||
arguments=arguments,
|
||||
token_span=span,
|
||||
status=status,
|
||||
)
|
||||
)
|
||||
i = end + 1
|
||||
else:
|
||||
i += 1
|
||||
return tool_calls
|
||||
|
||||
|
||||
# ── Laguna-XS.2: <tool_call> name\n<arg_key>k</arg_key>\n<arg_value>v</arg_value> </tool_call>
|
||||
# Same outer skeleton as parse_glm, but <arg_key>/<arg_value> are plain text
|
||||
# (multi-token BPE), not single special tokens — so the inner block is decoded
|
||||
@@ -572,32 +771,40 @@ def parse_laguna_xs2(
|
||||
tool_call_id: int,
|
||||
tool_call_end_id: int,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
strip_newlines: bool = True,
|
||||
) -> ParsedResponse:
|
||||
"""Parse Laguna-XS.2 completion tokens.
|
||||
"""Parse Laguna-XS.2 / XS-2.1 completion tokens.
|
||||
|
||||
Thinking uses single-token ``<think>`` / ``</think>`` (ids found by
|
||||
scan). Tool calls are delimited by single-token ``<tool_call>`` /
|
||||
``</tool_call>``, but ``<arg_key>`` / ``<arg_value>`` inside are
|
||||
plain text — regex-extracted from the decoded inner block.
|
||||
|
||||
``strip_newlines`` mirrors the template's whitespace around reasoning
|
||||
and content. XS.2 wraps reasoning with ``\\n`` on both sides
|
||||
(``<think>\\n{r}\\n</think>``) and brackets post-think content with
|
||||
``\\n`` too (``</think>\\n{c}\\n``) — strip exactly those newlines,
|
||||
never a bare ``.strip()``, which would also eat whitespace the model
|
||||
emitted intentionally. XS-2.1 renders both segments verbatim, so it
|
||||
parses with ``strip_newlines=False``.
|
||||
"""
|
||||
ids = _strip_stop_tokens(token_ids, stop_ids)
|
||||
|
||||
# The template wraps reasoning with ``\n`` on both sides
|
||||
# (``<think>\n{r}\n</think>``) and brackets post-think content with ``\n``
|
||||
# too (``</think>\n{c}\n``). Strip exactly those newlines from each
|
||||
# decoded segment — never a bare ``.strip()``, which would also eat
|
||||
# whitespace the model emitted intentionally.
|
||||
def _segment(segment_ids: list[int]) -> str:
|
||||
text = _decode(tokenizer, segment_ids)
|
||||
return text.strip("\n") if strip_newlines else text
|
||||
|
||||
reasoning = None
|
||||
parse_offset = 0
|
||||
think_end = _find(ids, think_end_id)
|
||||
if think_end != -1:
|
||||
reasoning_ids = ids[:think_end]
|
||||
reasoning_ids = [t for t in reasoning_ids if t != think_id]
|
||||
reasoning = _decode(tokenizer, reasoning_ids).strip("\n")
|
||||
reasoning = _segment(reasoning_ids)
|
||||
ids = ids[think_end + 1 :]
|
||||
parse_offset = think_end + 1
|
||||
elif (think_start := _find(ids, think_id)) != -1:
|
||||
reasoning = _decode(tokenizer, ids[think_start + 1 :]).strip("\n")
|
||||
reasoning = _segment(ids[think_start + 1 :])
|
||||
return ParsedResponse(
|
||||
content="", reasoning_content=reasoning or None, tool_calls=[]
|
||||
)
|
||||
@@ -605,7 +812,7 @@ def parse_laguna_xs2(
|
||||
tc_start = _find(ids, tool_call_id)
|
||||
tool_calls: list[ParsedToolCall] = []
|
||||
if tc_start != -1:
|
||||
content_text = _decode(tokenizer, ids[:tc_start]).strip("\n")
|
||||
content_text = _segment(ids[:tc_start])
|
||||
tool_calls = _parse_laguna_xs2_tool_calls(
|
||||
tokenizer,
|
||||
ids[tc_start:],
|
||||
@@ -615,7 +822,7 @@ def parse_laguna_xs2(
|
||||
param_index=_build_param_type_index(tools),
|
||||
)
|
||||
else:
|
||||
content_text = _decode(tokenizer, ids).strip("\n")
|
||||
content_text = _segment(ids)
|
||||
|
||||
return ParsedResponse(
|
||||
content=content_text,
|
||||
@@ -633,17 +840,20 @@ def _parse_laguna_xs2_tool_calls(
|
||||
section_offset: int,
|
||||
param_index: dict[str, dict[str, dict[str, Any]]],
|
||||
) -> list[ParsedToolCall]:
|
||||
"""Parse Laguna-XS.2 tool calls.
|
||||
"""Parse Laguna-XS.2 / XS-2.1 tool calls.
|
||||
|
||||
Inside each ``<tool_call>...</tool_call>`` block, the format is::
|
||||
|
||||
{name}\\n
|
||||
<arg_key>{k1}</arg_key>\\n<arg_value>{v1}</arg_value>\\n
|
||||
{name}
|
||||
<arg_key>{k1}</arg_key><arg_value>{v1}</arg_value>
|
||||
...
|
||||
<arg_key>{kn}</arg_key>\\n<arg_value>{vn}</arg_value>\\n
|
||||
<arg_key>{kn}</arg_key><arg_value>{vn}</arg_value>
|
||||
|
||||
The function name is everything before the first ``<arg_key>`` literal
|
||||
in the decoded block.
|
||||
XS.2 puts a ``\\n`` after the name and between the tag pairs; XS-2.1
|
||||
packs everything tightly. The function name is everything before the
|
||||
first ``<arg_key>`` literal in the decoded block (stripped), and the
|
||||
key/value regex allows optional whitespace between the tags, so both
|
||||
layouts parse identically.
|
||||
"""
|
||||
import re
|
||||
|
||||
|
||||
@@ -0,0 +1,694 @@
|
||||
"""PrimeIntellect Qwen3 renderer with exact chat-template tokenization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from renderers.base import (
|
||||
Message,
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import PrimeQwen3RendererConfig
|
||||
from renderers.parsing import parse_qwen35
|
||||
|
||||
_DEFAULT_TOOL_SYSTEM = "You are Qwen, a helpful AI assistant that can interact with a computer to solve tasks."
|
||||
_TOOLS_HEADER = "\n\n# Tools\n\nYou have access to the following functions:\n\n<tools>"
|
||||
_TOOLS_FOOTER = (
|
||||
"\n</tools>\n\n"
|
||||
"If you choose to call a function ONLY reply in the following format with NO suffix:"
|
||||
"\n\n<tool_call>\n<function=example_function_name>"
|
||||
"\n<parameter=example_parameter_1>\nvalue_1\n</parameter>"
|
||||
"\n<parameter=example_parameter_2>"
|
||||
"\nThis is the value for the second parameter"
|
||||
"\nthat can span\nmultiple lines\n</parameter>"
|
||||
"\n</function>\n</tool_call>"
|
||||
"\n\n<IMPORTANT>\nReminder:"
|
||||
"\n- Function calls MUST follow the specified format: an inner "
|
||||
"<function=...></function> block must be nested within "
|
||||
"<tool_call></tool_call> XML tags"
|
||||
"\n- Required parameters MUST be specified"
|
||||
"\n- You may provide optional reasoning for your function call in natural "
|
||||
"language BEFORE the function call, but NOT after"
|
||||
"\n- If there is no function call available, answer the question like normal "
|
||||
"with your current knowledge and do not tell the user about function calls"
|
||||
"\n</IMPORTANT>"
|
||||
)
|
||||
|
||||
|
||||
def _render_extra_keys(
|
||||
value: Any,
|
||||
handled_keys: frozenset[str],
|
||||
) -> str:
|
||||
if not isinstance(value, Mapping):
|
||||
return ""
|
||||
|
||||
rendered: list[str] = []
|
||||
for key, item in value.items():
|
||||
if key in handled_keys:
|
||||
continue
|
||||
item_text = (
|
||||
json.dumps(item, ensure_ascii=False)
|
||||
if isinstance(item, Mapping)
|
||||
or (
|
||||
isinstance(item, Sequence)
|
||||
and not isinstance(item, (str, bytes, bytearray))
|
||||
)
|
||||
else str(item)
|
||||
)
|
||||
rendered.append(f"\n<{key}>{item_text}</{key}>")
|
||||
return "".join(rendered)
|
||||
|
||||
|
||||
def _tool_definition(tool: ToolSpec) -> str:
|
||||
raw_tool: Any = tool
|
||||
if isinstance(raw_tool, Mapping) and isinstance(raw_tool.get("function"), Mapping):
|
||||
raw_tool = raw_tool["function"]
|
||||
if not isinstance(raw_tool, Mapping):
|
||||
raise TypeError("Tool definitions must be mappings.")
|
||||
|
||||
rendered = "\n<function>\n<name>" + str(raw_tool.get("name", "")) + "</name>"
|
||||
if "description" in raw_tool:
|
||||
rendered += (
|
||||
"\n<description>" + str(raw_tool["description"]).strip() + "</description>"
|
||||
)
|
||||
rendered += "\n<parameters>"
|
||||
|
||||
parameters = raw_tool.get("parameters")
|
||||
if isinstance(parameters, Mapping):
|
||||
properties = parameters.get("properties")
|
||||
if isinstance(properties, Mapping):
|
||||
for param_name, param_fields in properties.items():
|
||||
rendered += "\n<parameter>\n<name>" + str(param_name) + "</name>"
|
||||
if isinstance(param_fields, Mapping):
|
||||
if "type" in param_fields:
|
||||
rendered += "\n<type>" + str(param_fields["type"]) + "</type>"
|
||||
if "description" in param_fields:
|
||||
rendered += (
|
||||
"\n<description>"
|
||||
+ str(param_fields["description"]).strip()
|
||||
+ "</description>"
|
||||
)
|
||||
rendered += _render_extra_keys(
|
||||
param_fields,
|
||||
frozenset({"name", "type", "description"}),
|
||||
)
|
||||
rendered += "\n</parameter>"
|
||||
rendered += _render_extra_keys(
|
||||
parameters,
|
||||
frozenset({"type", "properties"}),
|
||||
)
|
||||
|
||||
rendered += "\n</parameters>"
|
||||
rendered += _render_extra_keys(
|
||||
raw_tool,
|
||||
frozenset({"type", "name", "description", "parameters"}),
|
||||
)
|
||||
rendered += "\n</function>"
|
||||
return rendered
|
||||
|
||||
|
||||
class _TokenBuilder:
|
||||
def __init__(self, tokenizer: PreTrainedTokenizer):
|
||||
self.tokenizer = tokenizer
|
||||
self.token_ids: list[int] = []
|
||||
self.message_indices: list[int] = []
|
||||
self.sampled_mask: list[bool] = []
|
||||
self.is_content: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
self,
|
||||
token_id: int,
|
||||
message_index: int,
|
||||
*,
|
||||
sampled: bool,
|
||||
content: bool,
|
||||
) -> None:
|
||||
self.token_ids.append(token_id)
|
||||
self.message_indices.append(message_index)
|
||||
self.sampled_mask.append(sampled)
|
||||
self.is_content.append(content)
|
||||
|
||||
def emit_text(
|
||||
self,
|
||||
text: str,
|
||||
message_index: int,
|
||||
*,
|
||||
sampled: bool,
|
||||
content: bool,
|
||||
) -> None:
|
||||
if not text:
|
||||
return
|
||||
token_ids = self.tokenizer.encode(text, add_special_tokens=False)
|
||||
self.token_ids.extend(token_ids)
|
||||
self.message_indices.extend([message_index] * len(token_ids))
|
||||
self.sampled_mask.extend([sampled] * len(token_ids))
|
||||
self.is_content.extend([content] * len(token_ids))
|
||||
|
||||
def emit_segments(
|
||||
self,
|
||||
segments: list[tuple[str, bool]],
|
||||
message_index: int,
|
||||
*,
|
||||
sampled: bool,
|
||||
) -> None:
|
||||
for token_id, content in attribute_text_segments(self.tokenizer, segments):
|
||||
self.token_ids.append(token_id)
|
||||
self.message_indices.append(message_index)
|
||||
self.sampled_mask.append(sampled)
|
||||
self.is_content.append(content)
|
||||
|
||||
def emit_assistant_segments(
|
||||
self,
|
||||
segments: list[tuple[str, bool]],
|
||||
message_index: int,
|
||||
) -> None:
|
||||
for token_id, content in attribute_text_segments(self.tokenizer, segments):
|
||||
self.token_ids.append(token_id)
|
||||
self.message_indices.append(message_index)
|
||||
self.sampled_mask.append(content)
|
||||
self.is_content.append(content)
|
||||
|
||||
def prepend_prior(self, token_ids: list[int]) -> None:
|
||||
self.token_ids.extend(token_ids)
|
||||
self.message_indices.extend([-1] * len(token_ids))
|
||||
self.sampled_mask.extend([False] * len(token_ids))
|
||||
self.is_content.extend([False] * len(token_ids))
|
||||
|
||||
|
||||
class PrimeQwen3Renderer:
|
||||
"""Renderer for PrimeIntellect/Qwen3-0.6B and Qwen3-1.7B."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: PrimeQwen3RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or PrimeQwen3RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
self._im_end = self._token_id("<|im_end|>")
|
||||
self._endoftext = self._token_id("<|endoftext|>")
|
||||
self._think = self._token_id("<think>")
|
||||
self._think_end = self._token_id("</think>")
|
||||
self._tool_call = self._token_id("<tool_call>")
|
||||
self._tool_call_end = self._token_id("</tool_call>")
|
||||
self._tool_response = self._token_id("<tool_response>")
|
||||
self._tool_response_end = self._token_id("</tool_response>")
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
token_id = self._tokenizer.convert_tokens_to_ids(token)
|
||||
assert isinstance(token_id, int) and token_id != self._tokenizer.unk_token_id, (
|
||||
f"Token {token!r} not found in tokenizer vocabulary"
|
||||
)
|
||||
return token_id
|
||||
|
||||
@staticmethod
|
||||
def _content(message: Message) -> str:
|
||||
content = message.get("content")
|
||||
if content is None:
|
||||
return ""
|
||||
if not isinstance(content, str):
|
||||
raise TypeError("PrimeQwen3Renderer only supports string message content.")
|
||||
return content
|
||||
|
||||
def render(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> RenderedTokens:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
builder = _TokenBuilder(self._tokenizer)
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
loop_start = 1 if first_is_system else 0
|
||||
|
||||
if first_is_system or tools:
|
||||
system_index = 0 if first_is_system else -1
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
system_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
system_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if first_is_system:
|
||||
system_segments.append((self._content(messages[0]), True))
|
||||
else:
|
||||
system_segments.append((_DEFAULT_TOOL_SYSTEM, False))
|
||||
|
||||
if tools:
|
||||
tools_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tools_text += _tool_definition(tool)
|
||||
tools_text += _TOOLS_FOOTER
|
||||
system_segments.append((tools_text, False))
|
||||
|
||||
builder.emit_segments(system_segments, system_index, sampled=False)
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
system_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
system_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
loop_messages = messages[loop_start:]
|
||||
for loop_index, message in enumerate(loop_messages):
|
||||
message_index = loop_start + loop_index
|
||||
role = message.get("role", "")
|
||||
if role == "assistant":
|
||||
tool_calls = message.get("tool_calls")
|
||||
if tool_calls:
|
||||
self._render_assistant_tool_calls(
|
||||
message,
|
||||
message_index,
|
||||
builder,
|
||||
)
|
||||
else:
|
||||
self._render_assistant(message, message_index, builder)
|
||||
elif role == "tool":
|
||||
opens_group = (
|
||||
loop_index > 0
|
||||
and loop_messages[loop_index - 1].get("role") != "tool"
|
||||
)
|
||||
closes_group = (
|
||||
loop_index == len(loop_messages) - 1
|
||||
or loop_messages[loop_index + 1].get("role") != "tool"
|
||||
)
|
||||
self._render_tool(
|
||||
message,
|
||||
message_index,
|
||||
builder,
|
||||
opens_group=opens_group,
|
||||
closes_group=closes_group,
|
||||
)
|
||||
else:
|
||||
self._render_history_message(message, message_index, builder)
|
||||
|
||||
if add_generation_prompt:
|
||||
self._render_generation_prompt(builder)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=builder.token_ids,
|
||||
message_indices=builder.message_indices,
|
||||
sampled_mask=builder.sampled_mask,
|
||||
is_content=builder.is_content,
|
||||
message_roles=[message.get("role") or "" for message in messages],
|
||||
message_tool_names=extract_message_tool_names(messages),
|
||||
)
|
||||
|
||||
def _render_history_message(
|
||||
self,
|
||||
message: Message,
|
||||
message_index: int,
|
||||
builder: _TokenBuilder,
|
||||
) -> None:
|
||||
role = message.get("role", "")
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_segments(
|
||||
[(role + "\n", False), (self._content(message), True)],
|
||||
message_index,
|
||||
sampled=False,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
message: Message,
|
||||
message_index: int,
|
||||
builder: _TokenBuilder,
|
||||
) -> None:
|
||||
content = self._content(message)
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
if "reasoning_content" in message:
|
||||
builder.emit_text(
|
||||
"assistant\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._think,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
reasoning = message.get("reasoning_content")
|
||||
if reasoning:
|
||||
builder.emit_text(
|
||||
str(reasoning).strip(),
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._think_end,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
if content.strip():
|
||||
builder.emit_text(
|
||||
"\n" + content.strip(),
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
else:
|
||||
builder.emit_assistant_segments(
|
||||
[("assistant\n", False), (content, True)],
|
||||
message_index,
|
||||
)
|
||||
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def _render_assistant_tool_calls(
|
||||
self,
|
||||
message: Message,
|
||||
message_index: int,
|
||||
builder: _TokenBuilder,
|
||||
) -> None:
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
content = message.get("content")
|
||||
trimmed_content = content.strip() if isinstance(content, str) else ""
|
||||
opener_segments = [("assistant\n", False)]
|
||||
if trimmed_content:
|
||||
opener_segments.append((trimmed_content + "\n\n", True))
|
||||
builder.emit_assistant_segments(opener_segments, message_index)
|
||||
|
||||
tool_calls = message.get("tool_calls") or []
|
||||
for tool_call_index, tool_call in enumerate(tool_calls):
|
||||
raw_call: Any = tool_call
|
||||
if isinstance(raw_call, Mapping) and isinstance(
|
||||
raw_call.get("function"), Mapping
|
||||
):
|
||||
raw_call = raw_call["function"]
|
||||
if not isinstance(raw_call, Mapping):
|
||||
raise TypeError("Tool calls must be mappings.")
|
||||
|
||||
builder.emit_special(
|
||||
self._tool_call,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
call_text = "\n<function=" + str(raw_call.get("name", "")) + ">\n"
|
||||
if "arguments" in raw_call:
|
||||
arguments = raw_call["arguments"]
|
||||
# OpenAI canonical form serializes arguments as a JSON string;
|
||||
# degrade malformed payloads to no parameters like Qwen3.5.
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
if not isinstance(arguments, Mapping):
|
||||
arguments = {}
|
||||
for argument_name, argument_value in arguments.items():
|
||||
value_text = (
|
||||
json.dumps(argument_value, ensure_ascii=False)
|
||||
if isinstance(argument_value, Mapping)
|
||||
or (
|
||||
isinstance(argument_value, Sequence)
|
||||
and not isinstance(argument_value, (str, bytes, bytearray))
|
||||
)
|
||||
else str(argument_value)
|
||||
)
|
||||
call_text += (
|
||||
"<parameter="
|
||||
+ str(argument_name)
|
||||
+ ">\n"
|
||||
+ value_text
|
||||
+ "\n</parameter>\n"
|
||||
)
|
||||
call_text += "</function>\n"
|
||||
builder.emit_text(
|
||||
call_text,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._tool_call_end,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
if tool_call_index < len(tool_calls) - 1:
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
message_index,
|
||||
sampled=True,
|
||||
content=True,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
message: Message,
|
||||
message_index: int,
|
||||
builder: _TokenBuilder,
|
||||
*,
|
||||
opens_group: bool,
|
||||
closes_group: bool,
|
||||
) -> None:
|
||||
if opens_group:
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"user\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
builder.emit_special(
|
||||
self._tool_response,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_segments(
|
||||
[("\n", False), (self._content(message), True), ("\n", False)],
|
||||
message_index,
|
||||
sampled=False,
|
||||
)
|
||||
builder.emit_special(
|
||||
self._tool_response_end,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
if closes_group:
|
||||
builder.emit_special(
|
||||
self._im_end,
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"\n",
|
||||
message_index,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def _render_generation_prompt(self, builder: _TokenBuilder) -> None:
|
||||
builder.emit_special(
|
||||
self._im_start,
|
||||
-1,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
builder.emit_text(
|
||||
"assistant\n",
|
||||
-1,
|
||||
sampled=False,
|
||||
content=False,
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> list[int]:
|
||||
return self.render(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_qwen35(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
stop_ids={self._im_end, self._endoftext},
|
||||
think_id=self._think,
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
return [self._im_end, self._endoftext]
|
||||
|
||||
def bridge_to_next_turn(
|
||||
self,
|
||||
previous_prompt_ids: list[int],
|
||||
previous_completion_ids: list[int],
|
||||
new_messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002
|
||||
) -> RenderedTokens | None:
|
||||
if (
|
||||
not previous_prompt_ids
|
||||
or not new_messages
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
{self._im_end, self._endoftext},
|
||||
synthesize_close=self._im_end,
|
||||
)
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
builder = _TokenBuilder(self._tokenizer)
|
||||
builder.prepend_prior(previous_ids)
|
||||
builder.emit_text("\n", -1, sampled=False, content=False)
|
||||
|
||||
for message_index, message in enumerate(new_messages):
|
||||
role = message.get("role", "")
|
||||
if role == "tool":
|
||||
opens_group = (
|
||||
message_index == 0
|
||||
or new_messages[message_index - 1].get("role") != "tool"
|
||||
)
|
||||
closes_group = (
|
||||
message_index == len(new_messages) - 1
|
||||
or new_messages[message_index + 1].get("role") != "tool"
|
||||
)
|
||||
self._render_tool(
|
||||
message,
|
||||
message_index,
|
||||
builder,
|
||||
opens_group=opens_group,
|
||||
closes_group=closes_group,
|
||||
)
|
||||
else:
|
||||
self._render_history_message(message, message_index, builder)
|
||||
|
||||
self._render_generation_prompt(builder)
|
||||
return RenderedTokens(
|
||||
token_ids=builder.token_ids,
|
||||
message_indices=builder.message_indices,
|
||||
sampled_mask=builder.sampled_mask,
|
||||
is_content=builder.is_content,
|
||||
message_roles=[message.get("role") or "" for message in new_messages],
|
||||
message_tool_names=extract_message_tool_names(new_messages),
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["PrimeQwen3Renderer"]
|
||||
+39
-21
@@ -21,7 +21,8 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen3RendererConfig
|
||||
@@ -54,6 +55,10 @@ class Qwen3Renderer:
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or Qwen3RendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all" if not self.config.enable_thinking else "tool_cycle",
|
||||
)
|
||||
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
self._im_end = self._token_id("<|im_end|>")
|
||||
@@ -76,19 +81,34 @@ class Qwen3Renderer:
|
||||
return []
|
||||
return self._tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
@staticmethod
|
||||
def _query_boundary_text(content) -> str:
|
||||
if isinstance(content, str):
|
||||
return content.strip()
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
parts.append(item)
|
||||
elif isinstance(item, dict) and isinstance(item.get("text"), str):
|
||||
parts.append(item["text"])
|
||||
return "".join(parts).strip()
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _is_user_query_message(msg: Message) -> bool:
|
||||
if msg.get("role") != "user":
|
||||
return False
|
||||
content = Qwen3Renderer._query_boundary_text(msg.get("content"))
|
||||
return not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _last_query_index(messages: list[Message]) -> int:
|
||||
for i in range(len(messages) - 1, -1, -1):
|
||||
msg = messages[i]
|
||||
if msg.get("role") != "user":
|
||||
continue
|
||||
content = msg.get("content")
|
||||
if not isinstance(content, str):
|
||||
continue
|
||||
if not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
):
|
||||
if Qwen3Renderer._is_user_query_message(messages[i]):
|
||||
return i
|
||||
return len(messages) - 1
|
||||
|
||||
@@ -206,19 +226,12 @@ class Qwen3Renderer:
|
||||
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.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
last_qi,
|
||||
i == num_messages - 1,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
@@ -298,6 +311,13 @@ class Qwen3Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
is_user_query=self._is_user_query_message,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
@@ -418,7 +438,6 @@ class Qwen3Renderer:
|
||||
last_query_index,
|
||||
is_last,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
@@ -458,8 +477,7 @@ class Qwen3Renderer:
|
||||
emit_in_template_window = msg_idx > last_query_index and (
|
||||
is_last or reasoning_content
|
||||
)
|
||||
emit_via_override = preserve_thinking and bool(reasoning_content)
|
||||
if emit_in_template_window or emit_via_override:
|
||||
if emit_in_template_window:
|
||||
body = (
|
||||
"<think>\n"
|
||||
+ reasoning_content.strip("\n")
|
||||
|
||||
+38
-23
@@ -29,7 +29,8 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
@@ -131,6 +132,16 @@ class Qwen35Renderer:
|
||||
update={"enable_thinking": _default_enable_thinking(tokenizer)}
|
||||
)
|
||||
self.config = cfg
|
||||
if getattr(cfg, "preserve_thinking", False):
|
||||
implied_thinking_retention = "all"
|
||||
elif not cfg.enable_thinking:
|
||||
implied_thinking_retention = "all"
|
||||
else:
|
||||
implied_thinking_retention = "tool_cycle"
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
cfg,
|
||||
implied_thinking_retention,
|
||||
)
|
||||
|
||||
# Look up special token IDs from the tokenizer (not hardcoded)
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
@@ -260,6 +271,16 @@ class Qwen35Renderer:
|
||||
# last_query_index computation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _is_user_query_message(msg: Message) -> bool:
|
||||
if msg.get("role") != "user":
|
||||
return False
|
||||
content = Qwen35Renderer._render_content(msg.get("content")).strip()
|
||||
return not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _last_query_index(messages: list[Message]) -> int:
|
||||
"""Find the index of the last 'real' user query (not a tool_response wrapper).
|
||||
@@ -272,14 +293,7 @@ class Qwen35Renderer:
|
||||
assistant-only inputs (e.g. the bridge's dummy-assistant render).
|
||||
"""
|
||||
for i in range(len(messages) - 1, -1, -1):
|
||||
msg = messages[i]
|
||||
if msg.get("role") != "user":
|
||||
continue
|
||||
content = Qwen35Renderer._render_content(msg.get("content")).strip()
|
||||
if not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
):
|
||||
if Qwen35Renderer._is_user_query_message(messages[i]):
|
||||
return i
|
||||
return len(messages)
|
||||
|
||||
@@ -508,18 +522,11 @@ class Qwen35Renderer:
|
||||
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.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
last_qi,
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_ids=emit_ids,
|
||||
@@ -619,6 +626,13 @@ class Qwen35Renderer:
|
||||
):
|
||||
return None
|
||||
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
is_user_query=self._is_user_query_message,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
previous_completion_ids,
|
||||
@@ -820,18 +834,20 @@ class Qwen35Renderer:
|
||||
emit_text("\n\n", -1)
|
||||
|
||||
# Merge prev mm_data (images from earlier turns) with the new turn's.
|
||||
# Copy the per-modality lists (not just the outer dict) so appending
|
||||
# below never mutates the caller's previous_multi_modal_data.
|
||||
merged_hashes: dict[str, list[str]] = (
|
||||
dict(previous_multi_modal_data.mm_hashes)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_placeholders: dict[str, list[PlaceholderRange]] = (
|
||||
dict(previous_multi_modal_data.mm_placeholders)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_items: dict[str, list[dict[str, Any]]] = (
|
||||
dict(previous_multi_modal_data.mm_items)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
@@ -903,7 +919,6 @@ class Qwen35Renderer:
|
||||
content: str,
|
||||
last_query_index: int,
|
||||
*,
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_ids,
|
||||
@@ -944,9 +959,9 @@ class Qwen35Renderer:
|
||||
# call tags (``<function=...>``, ``<parameter=...>``, etc.) are
|
||||
# part of the model's emitted output too — keep them
|
||||
# ``is_content=True`` per the assistant rule.
|
||||
emit_thinking = self._should_render_thinking(msg_idx, last_query_index) or (
|
||||
preserve_thinking and bool(reasoning_content)
|
||||
)
|
||||
emit_thinking = self._should_render_thinking(
|
||||
msg_idx, last_query_index
|
||||
) or getattr(self.config, "preserve_thinking", False)
|
||||
if emit_thinking:
|
||||
# Include thinking block
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
+3
-6
@@ -7,12 +7,9 @@ Delta vs Qwen3.5 (template line 122):
|
||||
``None`` as ``null`` (not ``None``), fixing the single-turn extension-break
|
||||
mode where a boolean parameter's case drifted across a re-render.
|
||||
|
||||
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`.
|
||||
Historical-thinking retention follows Qwen3.5's default unless
|
||||
``Qwen36RendererConfig.preserve_thinking`` is set, matching the upstream
|
||||
Qwen3.6 Jinja toggle.
|
||||
|
||||
Everything else — tool system prompt, tool-call XML structure, thinking
|
||||
markers, bridge logic, parser — is identical to Qwen3.5.
|
||||
|
||||
+31
-7
@@ -45,6 +45,8 @@ from renderers.base import (
|
||||
attribute_text_segments,
|
||||
extract_message_tool_names,
|
||||
reject_assistant_in_extension,
|
||||
resolve_thinking_retention,
|
||||
should_rerender_for_thinking_retention,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen3VLRendererConfig
|
||||
@@ -302,9 +304,9 @@ class Qwen3VLRenderer:
|
||||
keyed off ``tokenizer.name_or_path`` the first time a
|
||||
multimodal part is seen.
|
||||
|
||||
``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.
|
||||
Qwen3-VL has no historical reasoning channel in this renderer. The
|
||||
default bridge policy therefore resolves to ``"all"``; explicit
|
||||
``thinking_retention`` still controls whether the bridge is attempted.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -317,6 +319,10 @@ class Qwen3VLRenderer:
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
self.config = config or Qwen3VLRendererConfig()
|
||||
self.effective_thinking_retention = resolve_thinking_retention(
|
||||
self.config,
|
||||
"all",
|
||||
)
|
||||
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
self._im_end = self._token_id("<|im_end|>")
|
||||
@@ -410,6 +416,16 @@ class Qwen3VLRenderer:
|
||||
return "".join(parts)
|
||||
raise TypeError(f"Unexpected content type: {type(content)}")
|
||||
|
||||
@staticmethod
|
||||
def _is_user_query_message(msg: Message) -> bool:
|
||||
if msg.get("role") != "user":
|
||||
return False
|
||||
content = Qwen3VLRenderer._render_text_content(msg.get("content")).strip()
|
||||
return not (
|
||||
content.startswith("<tool_response>")
|
||||
and content.endswith("</tool_response>")
|
||||
)
|
||||
|
||||
def _process_image(self, part: dict[str, Any]):
|
||||
"""Resolve, process, and characterize a single image part.
|
||||
|
||||
@@ -665,6 +681,12 @@ class Qwen3VLRenderer:
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
if should_rerender_for_thinking_retention(
|
||||
self.effective_thinking_retention,
|
||||
new_messages,
|
||||
is_user_query=self._is_user_query_message,
|
||||
):
|
||||
return None
|
||||
|
||||
previous_ids = trim_to_turn_close(
|
||||
previous_prompt_ids,
|
||||
@@ -806,19 +828,21 @@ class Qwen3VLRenderer:
|
||||
em.text("assistant\n", is_sampled=False, is_content=False)
|
||||
em.finalize()
|
||||
|
||||
# Merge prev mm_data with the new turn's items.
|
||||
# Merge prev mm_data with the new turn's items. Copy the per-modality
|
||||
# lists (not just the outer dict) so appending below never mutates the
|
||||
# caller's previous_multi_modal_data.
|
||||
merged_hashes = (
|
||||
dict(previous_multi_modal_data.mm_hashes)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_hashes.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_placeholders = (
|
||||
dict(previous_multi_modal_data.mm_placeholders)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_placeholders.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
merged_items = (
|
||||
dict(previous_multi_modal_data.mm_items)
|
||||
{k: list(v) for k, v in previous_multi_modal_data.mm_items.items()}
|
||||
if previous_multi_modal_data
|
||||
else {}
|
||||
)
|
||||
|
||||
+12
-8
@@ -7,7 +7,6 @@ The same barrage of tests runs against every pair.
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import config_from_name
|
||||
@@ -20,6 +19,7 @@ from renderers.configs import config_from_name
|
||||
# own parametrization in the test file.
|
||||
RENDERER_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"),
|
||||
("PrimeIntellect/Qwen3-0.6B", "auto"),
|
||||
("Qwen/Qwen3.5-9B", "auto"),
|
||||
("Qwen/Qwen3.6-35B-A3B", "auto"),
|
||||
("Qwen/Qwen3-VL-4B-Instruct", "auto"),
|
||||
@@ -33,9 +33,13 @@ RENDERER_MODELS = [
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
|
||||
# Ultra resolves the Ultra template variant via name (auto → ultra=True).
|
||||
# Ultra resolves to the `nemotron-3-ultra` config variant via the model
|
||||
# name (auto → MODEL_RENDERER_MAP → nemotron-3-ultra).
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
# XS-2.1 resolves to `LagunaXS21Renderer` via the model name — its
|
||||
# chat template differs from XS.2's (see renderers/laguna_xs2.py).
|
||||
("poolside/Laguna-XS-2.1", "auto"),
|
||||
# DeepSeek-V3/R1 are intentionally NOT in this shared barrage: their
|
||||
# chat templates can't render the barrage's tool-call fixtures (the
|
||||
# templates require ``tool['type']`` and a string-serialized
|
||||
@@ -46,12 +50,12 @@ RENDERER_MODELS = [
|
||||
# there's just no byte-output to parity-check against. Split-specific
|
||||
# parity (V3 bare prompt vs R1 <think>+history-strip) is covered in
|
||||
# tests/test_deepseek_r1.py.
|
||||
# Llama-3 loads via the unrestricted unsloth mirror (byte-identical
|
||||
# chat template) so CI needs no Meta-gated HF token. Pinned to the
|
||||
# explicit "llama-3" config because the mirror name isn't in
|
||||
# MODEL_RENDERER_MAP (so "auto" would fall back to DefaultRenderer).
|
||||
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
|
||||
# Llama-3 uses the canonical Meta ID for renderer auto-resolution, while
|
||||
# load_tokenizer fetches the tokenizer/chat_template from the unrestricted
|
||||
# unsloth mirror so CI needs no Meta-gated HF token.
|
||||
("meta-llama/Llama-3.2-1B-Instruct", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
("tencent/Hy3", "auto"),
|
||||
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
|
||||
]
|
||||
|
||||
@@ -138,7 +142,7 @@ _LLAMA_HF_PARITY_TEST_FILES = {
|
||||
def _skip_llama_for_hf_parity_tests(request):
|
||||
callspec = getattr(request.node, "callspec", None)
|
||||
model_name = callspec.params.get("model_name") if callspec else None
|
||||
if model_name != "unsloth/Llama-3.2-1B-Instruct":
|
||||
if model_name != "meta-llama/Llama-3.2-1B-Instruct":
|
||||
return
|
||||
test_file = os.path.basename(str(request.node.fspath))
|
||||
if test_file in _LLAMA_HF_PARITY_TEST_FILES:
|
||||
|
||||
+167
-13
@@ -20,10 +20,10 @@ from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# (HF model name, renderer name) — one representative per renderer class.
|
||||
_BRIDGE_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"),
|
||||
("PrimeIntellect/Qwen3-0.6B", "auto"),
|
||||
("Qwen/Qwen3.5-9B", "auto"),
|
||||
("Qwen/Qwen3.6-35B-A3B", "auto"),
|
||||
("zai-org/GLM-5", "auto"),
|
||||
@@ -33,6 +33,7 @@ _BRIDGE_MODELS = [
|
||||
("moonshotai/Kimi-K2-Instruct", "auto"),
|
||||
("moonshotai/Kimi-K2.5", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("tencent/Hy3", "auto"),
|
||||
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
]
|
||||
@@ -67,7 +68,25 @@ def br_renderer(br_model, br_renderer_name):
|
||||
return _load(br_model, br_renderer_name)[1]
|
||||
|
||||
|
||||
def _simulate_prior_turn(renderer):
|
||||
@pytest.fixture
|
||||
def br_renderer_all(br_model, br_renderer_name):
|
||||
"""Renderer forced to ``thinking_retention="all"``.
|
||||
|
||||
The verbatim-extension mechanic tests below cross a user-query
|
||||
boundary. For thinking models the template drops a past block's
|
||||
thinking there, so the faithful bridge declines (covered by
|
||||
``test_bridge_declines_across_user_query_when_template_drops_thinking``).
|
||||
``"all"`` keeps thinking on every path, isolating the pure extension
|
||||
mechanic from the retention policy across all renderers.
|
||||
"""
|
||||
from renderers import create_renderer
|
||||
|
||||
tok, base = _load(br_model, br_renderer_name)
|
||||
cfg = base.config.model_copy(update={"thinking_retention": "all"})
|
||||
return create_renderer(tok, cfg)
|
||||
|
||||
|
||||
def _simulate_prior_turn(renderer, assistant=None):
|
||||
"""Build a (prev_prompt, prev_completion) pair that a real rollout
|
||||
would produce for a one-turn prior with a clean stop.
|
||||
|
||||
@@ -76,13 +95,15 @@ def _simulate_prior_turn(renderer):
|
||||
gen_prompt, and take the diff as prev_completion. We then trim
|
||||
prev_completion to the last close token so it matches what vLLM
|
||||
actually hands back (vLLM stops at the close token and excludes the
|
||||
trailing template scaffolding).
|
||||
trailing template scaffolding). Pass ``assistant`` to override the
|
||||
default no-thinking turn (e.g. one carrying ``reasoning_content``).
|
||||
"""
|
||||
prior = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi."},
|
||||
]
|
||||
assistant = [{"role": "assistant", "content": "Hello!"}]
|
||||
if assistant is None:
|
||||
assistant = [{"role": "assistant", "content": "Hello!"}]
|
||||
|
||||
prev_prompt = renderer.render_ids(prior, add_generation_prompt=True)
|
||||
full_with_assistant = renderer.render_ids(
|
||||
@@ -105,11 +126,11 @@ def _simulate_prior_turn(renderer):
|
||||
return prev_prompt, prev_completion
|
||||
|
||||
|
||||
def test_bridge_extends_prev_verbatim_on_clean_stop(br_renderer, br_model):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
|
||||
def test_bridge_extends_prev_verbatim_on_clean_stop(br_renderer_all, br_model):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer_all)
|
||||
new_messages = [{"role": "user", "content": "What's 2+2?"}]
|
||||
|
||||
bridged = br_renderer.bridge_to_next_turn(
|
||||
bridged = br_renderer_all.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, new_messages
|
||||
)
|
||||
assert bridged is not None, f"{br_model}: bridge returned None on clean stop"
|
||||
@@ -148,8 +169,8 @@ def test_bridge_rejects_empty_prev_or_new(br_renderer):
|
||||
assert br_renderer.bridge_to_next_turn(prev_prompt, prev_completion, []) is None
|
||||
|
||||
|
||||
def test_bridge_synthesises_close_on_truncation(br_renderer, br_model):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
|
||||
def test_bridge_synthesises_close_on_truncation(br_renderer_all, br_model):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer_all)
|
||||
# Drop the final close token to simulate a max_tokens truncation.
|
||||
prev_completion_trunc = prev_completion[:-1] if prev_completion else prev_completion
|
||||
if len(prev_completion_trunc) == 0:
|
||||
@@ -157,7 +178,7 @@ def test_bridge_synthesises_close_on_truncation(br_renderer, br_model):
|
||||
f"{br_model}: simulated prior had no completion tokens — can't truncate"
|
||||
)
|
||||
|
||||
bridged = br_renderer.bridge_to_next_turn(
|
||||
bridged = br_renderer_all.bridge_to_next_turn(
|
||||
prev_prompt,
|
||||
prev_completion_trunc,
|
||||
[{"role": "user", "content": "What's 2+2?"}],
|
||||
@@ -176,12 +197,12 @@ def test_bridge_synthesises_close_on_truncation(br_renderer, br_model):
|
||||
|
||||
|
||||
def test_bridge_extension_includes_new_message_text(
|
||||
br_renderer, br_tokenizer, br_model
|
||||
br_renderer_all, br_tokenizer, br_model
|
||||
):
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer_all)
|
||||
new_messages = [{"role": "user", "content": "HELLO_SENTINEL_XYZ"}]
|
||||
|
||||
bridged = br_renderer.bridge_to_next_turn(
|
||||
bridged = br_renderer_all.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, new_messages
|
||||
)
|
||||
assert bridged is not None
|
||||
@@ -190,3 +211,136 @@ def test_bridge_extension_includes_new_message_text(
|
||||
assert "HELLO_SENTINEL_XYZ" in decoded, (
|
||||
f"{br_model}: new-message content missing from extension; got {decoded!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_bridge_declines_across_user_query_when_template_drops_thinking():
|
||||
"""Qwen3's template drops a past block's thinking once a new user turn
|
||||
arrives. The resolved ``tool_cycle`` bridge policy therefore treats a
|
||||
new user query as a hard re-render boundary, independent of whether the
|
||||
prior token stream happens to contain sampled thinking:
|
||||
|
||||
- new user query + retention="tool_cycle" -> decline,
|
||||
and the fallback re-render equals ``apply_chat_template``.
|
||||
- thinking_retention="all" keeps thinking on every path -> extend.
|
||||
- a tool response (in-flight cycle, no new query) keeps thinking in
|
||||
the template too -> extend.
|
||||
- no prior thinking + new user query -> decline; no marker lookback.
|
||||
"""
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import Qwen3RendererConfig
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen3-8B")
|
||||
im_end = tok.convert_tokens_to_ids("<|im_end|>")
|
||||
|
||||
u1 = {"role": "user", "content": "What is 2+2?"}
|
||||
u2 = {"role": "user", "content": "Multiply that by 3."}
|
||||
tool = {"role": "tool", "content": "ok"}
|
||||
think = "<think>\n2 plus 2 is 4.\n</think>\n\n4"
|
||||
|
||||
def prior(r, asst_text):
|
||||
p = r.render_ids([u1], add_generation_prompt=True)
|
||||
completion = tok.encode(asst_text, add_special_tokens=False) + [im_end]
|
||||
return p, completion
|
||||
|
||||
# new user query + prior thinking + default retention -> decline
|
||||
r = create_renderer(tok, Qwen3RendererConfig())
|
||||
p, comp = prior(r, think)
|
||||
assert r.bridge_to_next_turn(p, comp, [u2]) is None
|
||||
# ...and the caller's faithful re-render matches the chat template
|
||||
hist = [u1, {"role": "assistant", "content": think}, u2]
|
||||
rendered = tok.decode(r.render_ids(hist, add_generation_prompt=True))
|
||||
assert rendered == tok.apply_chat_template(
|
||||
hist, tokenize=False, add_generation_prompt=True
|
||||
)
|
||||
|
||||
# thinking_retention="all" keeps thinking everywhere -> extend
|
||||
r_all = create_renderer(tok, Qwen3RendererConfig(thinking_retention="all"))
|
||||
p, comp = prior(r_all, think)
|
||||
assert r_all.bridge_to_next_turn(p, comp, [u2]) is not None
|
||||
|
||||
# tool response continues the in-flight cycle (no new query) -> extend
|
||||
p, comp = prior(r, think)
|
||||
assert r.bridge_to_next_turn(p, comp, [tool]) is not None
|
||||
|
||||
# tool_cycle is a user-query-boundary policy; it does not scan prior tokens.
|
||||
p, comp = prior(r, "4")
|
||||
assert r.bridge_to_next_turn(p, comp, [u2]) is None
|
||||
|
||||
|
||||
# Renderers whose default/effective bridge policy declines at a new user-query
|
||||
# boundary. The exact query-boundary predicate can still be renderer-specific
|
||||
# (for example Qwen's folded ``<tool_response>`` user messages).
|
||||
# Non-thinking models (llama, deepseek-v3) are out of scope for this check.
|
||||
_GUARDED_THINKING_MODELS = {
|
||||
"Qwen/Qwen3-8B",
|
||||
"Qwen/Qwen3.5-9B",
|
||||
"Qwen/Qwen3.6-35B-A3B",
|
||||
"zai-org/GLM-5",
|
||||
"zai-org/GLM-5.1",
|
||||
"THUDM/GLM-4.5-Air",
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
|
||||
"MiniMaxAI/MiniMax-M2.5",
|
||||
"moonshotai/Kimi-K2.5",
|
||||
"openai/gpt-oss-20b",
|
||||
"tencent/Hy3",
|
||||
}
|
||||
|
||||
|
||||
def test_bridge_declines_across_user_turn_when_thinking_present(br_renderer, br_model):
|
||||
"""Across every guarded thinking renderer: a prior turn carrying
|
||||
``reasoning_content`` makes the bridge decline a new *user* query (the
|
||||
template would strip that thinking) but still extend a *tool* response
|
||||
(in-flight cycle keeps it). Non-guarded models are skipped."""
|
||||
if br_model not in _GUARDED_THINKING_MODELS:
|
||||
pytest.skip(f"{br_model}: no bridge thinking-guard")
|
||||
|
||||
asst = [
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Let me think.",
|
||||
"content": "",
|
||||
"tool_calls": [{"function": {"name": "lookup", "arguments": {"q": "x"}}}],
|
||||
}
|
||||
]
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer, asst)
|
||||
|
||||
declined = br_renderer.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, [{"role": "user", "content": "next"}]
|
||||
)
|
||||
assert declined is None, f"{br_model}: expected faithful decline across a user turn"
|
||||
|
||||
extended = br_renderer.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, [{"role": "tool", "content": "result"}]
|
||||
)
|
||||
assert extended is not None, f"{br_model}: should still bridge within a tool cycle"
|
||||
|
||||
|
||||
def test_bridge_keeps_thinking_when_history_kwarg_disables_truncation():
|
||||
"""GLM ``clear_thinking=False`` / Nemotron ``truncate_history_thinking=
|
||||
False`` keep all past thinking (the template doesn't strip it), so the
|
||||
bridge must NOT decline across a user turn — declining would re-render and
|
||||
re-tokenize model-sampled thinking bytes."""
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import GLM5RendererConfig, Nemotron3RendererConfig
|
||||
|
||||
asst = [
|
||||
{"role": "assistant", "reasoning_content": "Let me think.", "content": "Hi"}
|
||||
]
|
||||
cases = [
|
||||
("zai-org/GLM-5", GLM5RendererConfig(clear_thinking=False)),
|
||||
(
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
|
||||
Nemotron3RendererConfig(truncate_history_thinking=False),
|
||||
),
|
||||
]
|
||||
for model, cfg in cases:
|
||||
r = create_renderer(load_tokenizer(model), cfg)
|
||||
prev_prompt, prev_completion = _simulate_prior_turn(r, asst)
|
||||
bridged = r.bridge_to_next_turn(
|
||||
prev_prompt, prev_completion, [{"role": "user", "content": "next"}]
|
||||
)
|
||||
assert bridged is not None, (
|
||||
f"{model}: bridge must keep verbatim when the template keeps all thinking"
|
||||
)
|
||||
|
||||
@@ -4,6 +4,17 @@ Runs against every (model, renderer) pair.
|
||||
"""
|
||||
|
||||
from renderers import build_training_sample, build_trajectory_step
|
||||
from renderers.base import PlaceholderRange, _build_mm_token_type_ids
|
||||
|
||||
|
||||
def test_build_mm_token_type_ids_marks_ranges():
|
||||
"""Image runs → 1, video runs → 2, everything else → 0; clips at length."""
|
||||
placeholders = {
|
||||
"image": [PlaceholderRange(offset=2, length=3)], # tokens 2,3,4
|
||||
"video": [PlaceholderRange(offset=7, length=2)], # tokens 7,8
|
||||
}
|
||||
ids = _build_mm_token_type_ids(placeholders, length=10)
|
||||
assert ids == [0, 0, 1, 1, 1, 0, 0, 2, 2, 0]
|
||||
|
||||
|
||||
def _expected(tokenizer, messages, **kwargs):
|
||||
@@ -29,10 +40,14 @@ def test_build_training_sample_ids_match(model_name, tokenizer, renderer):
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
ids, mask = build_training_sample(
|
||||
sample = build_training_sample(
|
||||
renderer, msgs, role_to_mask=lambda m: m["role"] == "assistant"
|
||||
)
|
||||
ids = sample.token_ids
|
||||
assert ids == _expected(tokenizer, msgs)
|
||||
# text-only sample carries no multimodal payload
|
||||
assert sample.multi_modal_data is None
|
||||
assert sample.mm_token_type_ids is None
|
||||
|
||||
|
||||
def test_build_training_sample_has_trainable_tokens(model_name, tokenizer, renderer):
|
||||
@@ -41,13 +56,42 @@ def test_build_training_sample_has_trainable_tokens(model_name, tokenizer, rende
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
ids, mask = build_training_sample(
|
||||
sample = build_training_sample(
|
||||
renderer, msgs, role_to_mask=lambda m: m["role"] == "assistant"
|
||||
)
|
||||
ids, mask = sample.token_ids, sample.loss_mask
|
||||
assert sum(mask) > 0
|
||||
assert len(mask) == len(ids)
|
||||
|
||||
|
||||
def test_build_training_sample_ensures_final_stop(model_name, tokenizer, renderer):
|
||||
"""The final assistant turn ends at a trainable renderer stop token.
|
||||
|
||||
Templates whose assistant close is part of the message (ChatML, Llama)
|
||||
already satisfy this, so the sample stays byte-identical; templates
|
||||
that terminate turns with the next message's role marker (GLM) get the
|
||||
canonical stop appended as the training target.
|
||||
"""
|
||||
if not renderer.render([{"role": "user", "content": "x"}]).sampled_mask:
|
||||
return # DefaultRenderer: no sampled_mask, role-only masking
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
sample = build_training_sample(renderer, msgs, ensure_final_stop=True)
|
||||
stop_ids = set(renderer.get_stop_token_ids())
|
||||
last_trainable = max(k for k, m in enumerate(sample.loss_mask) if m)
|
||||
assert sample.token_ids[last_trainable] in stop_ids
|
||||
|
||||
baseline = build_training_sample(renderer, msgs)
|
||||
if (
|
||||
baseline.token_ids[max(k for k, m in enumerate(baseline.loss_mask) if m)]
|
||||
in stop_ids
|
||||
):
|
||||
# In-message close: ensure_final_stop must not change the bytes.
|
||||
assert sample.token_ids == baseline.token_ids
|
||||
|
||||
|
||||
def test_build_trajectory_step_reconstructs_full(model_name, tokenizer, renderer):
|
||||
"""prompt_ids + completion_ids must equal the full rendered sequence."""
|
||||
prompt = [
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Hermes regressions on Trinity's real multi-token tool delimiters."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from renderers.base import ToolCallParseStatus
|
||||
from renderers.configs import DefaultRendererConfig
|
||||
from renderers.default import DefaultRenderer
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def trinity_tokenizer():
|
||||
return AutoTokenizer.from_pretrained(
|
||||
"arcee-ai/Trinity-Mini",
|
||||
revision="cdb81e8130815fec299cccc8f8700004b8366e1e",
|
||||
trust_remote_code=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hermes_renderer(trinity_tokenizer):
|
||||
return DefaultRenderer(
|
||||
trinity_tokenizer,
|
||||
DefaultRendererConfig(tool_parser="hermes", reasoning_parser="think"),
|
||||
)
|
||||
|
||||
|
||||
CALL = '<tool_call>{"name":"book_flight","arguments":{"dest":"Paris"}}</tool_call>'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
f"<think>Consider {CALL}, but do not book.</think>No.",
|
||||
f"Consider {CALL}, but do not book.</think>No.",
|
||||
f"<think>Unclosed reasoning containing {CALL}",
|
||||
f"Unclosed prefilled reasoning containing {CALL}",
|
||||
f"Finished reasoning.</think>```json\n{CALL}\n```",
|
||||
f"Finished reasoning.</think>~~~json\n{CALL}\n~~~",
|
||||
f"Finished reasoning.</think>Example: `{CALL}`.",
|
||||
'Finished reasoning.</think>```json\n{"name":"book_flight","arguments":{"dest":"Paris"}}\n```',
|
||||
'Finished reasoning.</think>{"name":"book_flight","arguments":{"dest":"Paris"}}',
|
||||
],
|
||||
)
|
||||
def test_examples_are_not_actions(trinity_tokenizer, hermes_renderer, text):
|
||||
ids = trinity_tokenizer.encode(text, add_special_tokens=False)
|
||||
remaining, calls = hermes_renderer._tool_parser.extract(ids)
|
||||
assert remaining == ids
|
||||
assert calls == []
|
||||
assert hermes_renderer.parse_response(ids).tool_calls == []
|
||||
|
||||
|
||||
def test_native_calls_preserve_reasoning_content_and_original_spans(trinity_tokenizer, hermes_renderer):
|
||||
text = f"Consider the destination.</think>é🙂 before{CALL}between{CALL}after"
|
||||
ids = trinity_tokenizer.encode(text, add_special_tokens=False)
|
||||
parsed = hermes_renderer.parse_response(ids)
|
||||
assert parsed.reasoning_content == "Consider the destination."
|
||||
assert parsed.content == "é🙂 beforebetweenafter"
|
||||
assert len(parsed.tool_calls) == 2
|
||||
for call in parsed.tool_calls:
|
||||
assert call.status == ToolCallParseStatus.OK
|
||||
assert call.name == "book_flight" and call.arguments == {"dest": "Paris"}
|
||||
start, end = call.token_span
|
||||
assert 0 <= start < end <= len(ids)
|
||||
covered = trinity_tokenizer.decode(ids[start:end], skip_special_tokens=False)
|
||||
assert CALL in covered
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body,status",
|
||||
[
|
||||
('{"name":"f","arguments":{}}', ToolCallParseStatus.OK),
|
||||
('{"name":"f","arguments":[]}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":"f","arguments":null}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":"f","arguments":"{}"}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":"f"}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":42,"arguments":{}}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
('{"name":" ","arguments":{}}', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
("[]", ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
("{'name':'f','arguments':{}}", ToolCallParseStatus.INVALID_JSON),
|
||||
('{"name":"f","arguments":{"x":NaN}}', ToolCallParseStatus.INVALID_JSON),
|
||||
('{"name":"f","arguments":{"x":Infinity}}', ToolCallParseStatus.INVALID_JSON),
|
||||
('{"name":"f","name":"g","arguments":{}}', ToolCallParseStatus.INVALID_JSON),
|
||||
('{"name":"f","arguments":{}} trailing', ToolCallParseStatus.MALFORMED_STRUCTURE),
|
||||
],
|
||||
)
|
||||
def test_strict_native_envelopes(trinity_tokenizer, hermes_renderer, body, status):
|
||||
ids = trinity_tokenizer.encode(f"Use the tool.</think><tool_call>{body}</tool_call>", add_special_tokens=False)
|
||||
parsed = hermes_renderer.parse_response(ids)
|
||||
assert len(parsed.tool_calls) == 1
|
||||
assert parsed.tool_calls[0].status == status
|
||||
if status != ToolCallParseStatus.OK:
|
||||
assert parsed.tool_calls[0].name is None
|
||||
|
||||
|
||||
def test_tag_strings_in_arguments_do_not_close_a_call(trinity_tokenizer, hermes_renderer):
|
||||
args = {"text": '</tool_call> <think> ``` <tool_call> " café🙂'}
|
||||
body = json.dumps({"name": "f", "arguments": args}, ensure_ascii=False)
|
||||
ids = trinity_tokenizer.encode(
|
||||
f"Use the tool.</think><tool_call>{body}</tool_call>suffix", add_special_tokens=False
|
||||
)
|
||||
parsed = hermes_renderer.parse_response(ids)
|
||||
assert parsed.content == "suffix"
|
||||
assert parsed.tool_calls[0].arguments == args
|
||||
assert parsed.tool_calls[0].status == ToolCallParseStatus.OK
|
||||
|
||||
|
||||
def test_unclosed_call_remains_a_parse_error(trinity_tokenizer, hermes_renderer):
|
||||
ids = trinity_tokenizer.encode(
|
||||
'Use the tool.</think><tool_call>{"name":"f","arguments":{}}', add_special_tokens=False
|
||||
)
|
||||
parsed = hermes_renderer.parse_response(ids)
|
||||
assert parsed.tool_calls[0].status == ToolCallParseStatus.UNCLOSED_BLOCK
|
||||
assert parsed.tool_calls[0].name is None
|
||||
|
||||
|
||||
def test_real_schema_uses_native_chat_template(trinity_tokenizer, hermes_renderer):
|
||||
tool = {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "book_flight",
|
||||
"description": "Book a flight.",
|
||||
"parameters": {"type": "object", "properties": {"dest": {"type": "string"}}},
|
||||
},
|
||||
}
|
||||
result = hermes_renderer.render(
|
||||
[{"role": "user", "content": "Book a flight to Paris."}],
|
||||
tools=[tool],
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
text = trinity_tokenizer.decode(result.token_ids, skip_special_tokens=False)
|
||||
assert "book_flight" in text and "<tools>" in text and "<tool_call>" in text
|
||||
assert "available_actions" not in text
|
||||
assert "```json" not in text
|
||||
assert text.endswith("<think>\n")
|
||||
@@ -0,0 +1,486 @@
|
||||
"""Hy3-specific coverage beyond the shared barrage.
|
||||
|
||||
The parity / roundtrip / bridge matrices already assert byte-exact
|
||||
``apply_chat_template`` agreement and the emit/parse round trip. This file
|
||||
pins the behaviours unique to Hy3: the ``reasoning_effort`` generation-prompt
|
||||
polarity, parsing of a live inference stream (where the ``<think>`` opener
|
||||
lives in the prompt, not the completion), the reasoning-mode marker
|
||||
placement, and tool-call parse statuses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import Hy3RendererConfig, create_renderer
|
||||
from renderers.base import ToolCallParseStatus, load_tokenizer
|
||||
|
||||
_MODEL = "tencent/Hy3"
|
||||
|
||||
_ASSISTANT = "<|hy_Assistant:opensource|>"
|
||||
_THINK = "<think:opensource>"
|
||||
_THINK_END = "</think:opensource>"
|
||||
_EOS = "<|hy_eos:opensource|>"
|
||||
_REASONING_MODE = "<|reasoning_mode:opensource|>"
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _tok():
|
||||
return load_tokenizer(_MODEL)
|
||||
|
||||
|
||||
def _renderer(**flags):
|
||||
return create_renderer(_tok(), Hy3RendererConfig(**flags))
|
||||
|
||||
|
||||
def _decode(ids):
|
||||
return _tok().decode(ids, skip_special_tokens=False)
|
||||
|
||||
|
||||
# ── generation-prompt polarity ─────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"effort,expected_tail",
|
||||
[
|
||||
("no_think", _ASSISTANT + _THINK + _THINK_END),
|
||||
("low", _ASSISTANT + _THINK),
|
||||
("high", _ASSISTANT + _THINK),
|
||||
],
|
||||
)
|
||||
def test_generation_prompt_polarity(effort, expected_tail):
|
||||
r = _renderer(reasoning_effort=effort)
|
||||
ids = r.render_ids([{"role": "user", "content": "Hi"}], add_generation_prompt=True)
|
||||
assert _decode(ids).endswith(expected_tail), (
|
||||
f"effort={effort}: gen prompt tail was {_decode(ids)[-60:]!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_mode_marker_in_system_without_tools():
|
||||
"""Without tools, ``<|reasoning_mode|>reasoning_effort:{effort}`` is
|
||||
appended to the system blob."""
|
||||
r = _renderer(reasoning_effort="high")
|
||||
text = _decode(r.render_ids([{"role": "user", "content": "Hi"}]))
|
||||
assert _REASONING_MODE + "reasoning_effort:high" in text
|
||||
|
||||
|
||||
def test_reasoning_mode_marker_rides_tools_footer():
|
||||
"""With tools, the reasoning-mode marker moves to the end of the tool
|
||||
instructions (after ``</tool_calls>``), not the system blob."""
|
||||
r = _renderer(reasoning_effort="low")
|
||||
text = _decode(r.render_ids([{"role": "user", "content": "Hi"}], tools=TOOLS))
|
||||
assert "</tool_calls:opensource>" + _REASONING_MODE + "reasoning_effort:low" in text
|
||||
|
||||
|
||||
# ── stop token ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_stop_token_is_eos_only():
|
||||
r = _renderer()
|
||||
eos_id = _tok().convert_tokens_to_ids(_EOS)
|
||||
assert r.get_stop_token_ids() == [eos_id]
|
||||
|
||||
|
||||
# ── parsing a live inference stream ──────────────────────────────────────
|
||||
|
||||
|
||||
def test_parse_low_mode_inference_stream():
|
||||
"""In low/high mode the completion starts with reasoning text and closes
|
||||
it with ``</think>`` the model emits itself (the ``<think>`` opener was in
|
||||
the prompt)."""
|
||||
r = _renderer(reasoning_effort="low")
|
||||
comp = _tok().encode(
|
||||
"Let me work it out." + _THINK_END + "It is 4." + _EOS,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp)
|
||||
assert parsed.reasoning_content == "Let me work it out."
|
||||
assert parsed.content == "It is 4."
|
||||
assert not parsed.tool_calls
|
||||
|
||||
|
||||
def test_parse_no_think_inference_stream():
|
||||
"""In no_think mode the completion is the bare answer (both think tokens
|
||||
were prefilled into the prompt)."""
|
||||
r = _renderer()
|
||||
comp = _tok().encode("It is 4." + _EOS, add_special_tokens=False)
|
||||
parsed = r.parse_response(comp)
|
||||
assert parsed.content == "It is 4."
|
||||
assert parsed.reasoning_content is None
|
||||
|
||||
|
||||
def test_parse_tool_call_stream_with_schema():
|
||||
"""A tool-call completion parses name + typed args; the schema keeps a
|
||||
string arg verbatim (status OK, no JSON fallback)."""
|
||||
r = _renderer()
|
||||
comp = _tok().encode(
|
||||
"<tool_calls:opensource>\n<tool_call:opensource>get_weather<tool_sep:opensource>\n"
|
||||
"<arg_key:opensource>city</arg_key:opensource>\n"
|
||||
"<arg_value:opensource>Paris</arg_value:opensource>\n"
|
||||
"</tool_call:opensource>\n</tool_calls:opensource>" + _EOS,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp, tools=TOOLS)
|
||||
assert len(parsed.tool_calls) == 1
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.name == "get_weather"
|
||||
assert tc.arguments == {"city": "Paris"}
|
||||
assert tc.status is ToolCallParseStatus.OK
|
||||
assert parsed.content == ""
|
||||
|
||||
|
||||
def test_parse_unclosed_tool_call_is_flagged():
|
||||
r = _renderer()
|
||||
comp = _tok().encode(
|
||||
"<tool_calls:opensource>\n<tool_call:opensource>get_weather<tool_sep:opensource>\n"
|
||||
"<arg_key:opensource>city</arg_key:opensource>\n"
|
||||
"<arg_value:opensource>Paris</arg_value:opensource>\n",
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp)
|
||||
assert len(parsed.tool_calls) == 1
|
||||
assert parsed.tool_calls[0].status is ToolCallParseStatus.UNCLOSED_BLOCK
|
||||
|
||||
|
||||
def test_parse_content_before_tool_call_preserved():
|
||||
r = _renderer()
|
||||
comp = _tok().encode(
|
||||
"Let me check."
|
||||
"<tool_calls:opensource>\n<tool_call:opensource>get_weather<tool_sep:opensource>\n"
|
||||
"<arg_key:opensource>city</arg_key:opensource>\n"
|
||||
"<arg_value:opensource>Paris</arg_value:opensource>\n"
|
||||
"</tool_call:opensource>\n</tool_calls:opensource>" + _EOS,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp, tools=TOOLS)
|
||||
assert parsed.content == "Let me check."
|
||||
assert parsed.tool_calls[0].name == "get_weather"
|
||||
|
||||
|
||||
# ── tool-group re-opening (is_tool_first state machine) ─────────────────
|
||||
|
||||
|
||||
def test_tool_group_not_reopened_after_plain_assistant():
|
||||
"""The template resets ``is_tool_first`` only on an assistant that made
|
||||
tool calls; tool results arriving after a plain assistant continue the
|
||||
earlier <tool_responses> group without re-opening it. Byte-parity check
|
||||
on a shape the shared matrices never generate."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Weather?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "sunny"},
|
||||
{"role": "assistant", "content": "Checking again."},
|
||||
{"role": "tool", "content": "rainy"},
|
||||
{"role": "user", "content": "So?"},
|
||||
]
|
||||
ours = _renderer().render_ids(convo, tools=TOOLS, add_generation_prompt=True)
|
||||
theirs = _tok().apply_chat_template(
|
||||
convo,
|
||||
tools=TOOLS,
|
||||
add_generation_prompt=True,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
)
|
||||
assert ours == list(theirs)
|
||||
|
||||
|
||||
# ── preserved_thinking history retention ─────────────────────────────────
|
||||
|
||||
|
||||
def test_preserved_thinking_history_retention():
|
||||
"""A historical assistant (before the last user turn) keeps its reasoning
|
||||
only when ``preserved_thinking`` resolves True."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Q1"},
|
||||
{"role": "assistant", "reasoning_content": "R1", "content": "A1"},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{"role": "assistant", "reasoning_content": "R2", "content": "A2"},
|
||||
]
|
||||
stripped = _decode(_renderer(preserved_thinking=False).render_ids(convo))
|
||||
# Historical reasoning "R1" dropped; in-flight "R2" kept.
|
||||
assert "R1" not in stripped
|
||||
assert "R2" in stripped
|
||||
|
||||
kept = _decode(_renderer(preserved_thinking=True).render_ids(convo))
|
||||
assert "R1" in kept and "R2" in kept
|
||||
|
||||
|
||||
def test_preserved_thinking_defaults_to_tools_presence():
|
||||
"""With the default (None) config, the template keeps historical reasoning
|
||||
iff tools are supplied at render time."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Q1"},
|
||||
{"role": "assistant", "reasoning_content": "R1", "content": "A1"},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{"role": "assistant", "reasoning_content": "R2", "content": "A2"},
|
||||
]
|
||||
r = _renderer()
|
||||
assert "R1" not in _decode(r.render_ids(convo))
|
||||
assert "R1" in _decode(r.render_ids(convo, tools=TOOLS))
|
||||
|
||||
|
||||
# ── bridge policy resolution ─────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_effective_retention_defaults_conservative():
|
||||
assert _renderer().effective_thinking_retention == "tool_cycle"
|
||||
assert _renderer(preserved_thinking=True).effective_thinking_retention == "all"
|
||||
assert _renderer(thinking_retention="all").effective_thinking_retention == "all"
|
||||
|
||||
|
||||
def test_preserved_thinking_conflict_raises():
|
||||
with pytest.raises(ValueError):
|
||||
Hy3RendererConfig(preserved_thinking=True, thinking_retention="tool_cycle")
|
||||
with pytest.raises(ValueError):
|
||||
Hy3RendererConfig(preserved_thinking=False, thinking_retention="all")
|
||||
|
||||
|
||||
_BRIDGE_ASST = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
}
|
||||
_BRIDGE_EXT = [
|
||||
{"role": "tool", "content": "sunny"},
|
||||
{"role": "user", "content": "And tomorrow?"},
|
||||
]
|
||||
|
||||
|
||||
def test_bridge_default_config_with_tools_extends_across_user_turn():
|
||||
"""With the default (None) config the bridge policy mirrors the template's
|
||||
tools-dependent ``preserved_thinking``: a full render with tools keeps
|
||||
historical reasoning across user turns, so declining the bridge there
|
||||
would force a re-render that drops the verbatim sampled tokens for no
|
||||
semantic gain. The bridge must extend, byte-identical to a fresh render."""
|
||||
r = _renderer()
|
||||
prev = [{"role": "user", "content": "Weather?"}]
|
||||
pp = r.render_ids(prev, tools=TOOLS, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, _BRIDGE_ASST], tools=TOOLS)[len(pp) :])
|
||||
|
||||
bridged = r.bridge_to_next_turn(pp, pc, _BRIDGE_EXT, tools=TOOLS)
|
||||
fresh = r.render_ids(
|
||||
[*prev, _BRIDGE_ASST, *_BRIDGE_EXT], tools=TOOLS, add_generation_prompt=True
|
||||
)
|
||||
assert bridged is not None and bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_default_config_without_tools_declines_at_user_turn():
|
||||
"""Without tools the template default drops past-cycle reasoning once a
|
||||
new user query arrives, so the faithful bridge declines there."""
|
||||
r = _renderer()
|
||||
prev = [{"role": "user", "content": "Q1"}]
|
||||
pp = r.render_ids(prev, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, {"role": "assistant", "content": "A1"}])[len(pp) :])
|
||||
assert r.bridge_to_next_turn(pp, pc, [{"role": "user", "content": "Q2"}]) is None
|
||||
|
||||
|
||||
def test_bridge_explicit_tool_cycle_declines_at_user_turn_despite_tools():
|
||||
"""An explicit ``thinking_retention="tool_cycle"`` wins over the
|
||||
tools-dependent template default: the bridge still declines at a new
|
||||
user turn even though tools are present."""
|
||||
r = _renderer(thinking_retention="tool_cycle")
|
||||
prev = [{"role": "user", "content": "Weather?"}]
|
||||
pp = r.render_ids(prev, tools=TOOLS, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, _BRIDGE_ASST], tools=TOOLS)[len(pp) :])
|
||||
assert r.bridge_to_next_turn(pp, pc, _BRIDGE_EXT, tools=TOOLS) is None
|
||||
|
||||
|
||||
# ── is_training / raw_last_assistant / fallback_strategy ─────────────────
|
||||
|
||||
|
||||
def test_is_training_keeps_all_thinking_and_closes_final_assistant():
|
||||
"""``is_training=True`` keeps historical reasoning regardless of position
|
||||
and terminates the final assistant with ``<|hy_eos|>``."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Q1"},
|
||||
{"role": "assistant", "reasoning_content": "R1", "content": "A1"},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{"role": "assistant", "reasoning_content": "R2", "content": "A2"},
|
||||
]
|
||||
default = _decode(_renderer().render_ids(convo))
|
||||
training = _decode(_renderer(is_training=True).render_ids(convo))
|
||||
assert "R1" not in default and not default.endswith(_EOS)
|
||||
assert "R1" in training and "R2" in training and training.endswith(_EOS)
|
||||
|
||||
|
||||
def test_raw_last_assistant_drops_wrap_and_eos():
|
||||
"""A trailing non-tool assistant renders as bare visible content."""
|
||||
convo = [
|
||||
{"role": "user", "content": "Q"},
|
||||
{"role": "assistant", "reasoning_content": "R", "content": "the answer"},
|
||||
]
|
||||
raw = _decode(_renderer(raw_last_assistant=True).render_ids(convo))
|
||||
assert raw.endswith(_ASSISTANT + "the answer") # no think wrap, no eos
|
||||
assert _THINK not in raw.split(_ASSISTANT)[-1]
|
||||
|
||||
|
||||
def test_fallback_strategy_forces_high_and_no_gen_prompt():
|
||||
"""``reasoning_toolcall_retry`` forces high effort and suppresses the gen
|
||||
prompt even when the caller asks for it."""
|
||||
r = _renderer(fallback_strategy="reasoning_toolcall_retry")
|
||||
ids = r.render_ids([{"role": "user", "content": "Hi"}], add_generation_prompt=True)
|
||||
text = _decode(ids)
|
||||
assert _REASONING_MODE + "reasoning_effort:high" in text
|
||||
assert not text.endswith(_ASSISTANT + _THINK) # gen prompt suppressed
|
||||
assert not text.endswith(_ASSISTANT)
|
||||
|
||||
|
||||
def test_fallback_strategy_bridge_matches_full_render():
|
||||
"""The bridge must also suppress the generation prompt under the fallback
|
||||
retry strategy, so it stays consistent with a fresh full render."""
|
||||
r = _renderer(
|
||||
fallback_strategy="reasoning_toolcall_retry", thinking_retention="all"
|
||||
)
|
||||
eos = _tok().convert_tokens_to_ids(_EOS)
|
||||
prior = [{"role": "user", "content": "Hi."}]
|
||||
pp = r.render_ids(prior, add_generation_prompt=True)
|
||||
full = r.render_ids([*prior, {"role": "assistant", "content": "Hello!"}])
|
||||
pc = list(full[len(pp) :])
|
||||
if not pc or pc[-1] != eos:
|
||||
pc = pc + [eos]
|
||||
|
||||
bridged = r.bridge_to_next_turn(pp, pc, [{"role": "tool", "content": "result"}])
|
||||
assert bridged is not None
|
||||
# No generation prompt appended (fallback forces add_generation_prompt=False).
|
||||
assert bridged.token_ids[-1] != _tok().convert_tokens_to_ids(_ASSISTANT)
|
||||
assert _ASSISTANT not in _decode(bridged.token_ids[len(pp) + len(pc) :])
|
||||
|
||||
|
||||
# ── tool-call token_span reporting ───────────────────────────────────────
|
||||
|
||||
|
||||
def test_tool_call_token_span_indexes_stripped_stream():
|
||||
"""``token_span`` must slice the stop-stripped completion back to the
|
||||
<tool_call>…</tool_call> block, accounting for the reasoning + leading
|
||||
content stripped before parsing."""
|
||||
from renderers.parsing import _strip_stop_tokens
|
||||
|
||||
r = _renderer(reasoning_effort="low")
|
||||
tok = _tok()
|
||||
comp = tok.encode(
|
||||
"Let me think." + _THINK_END + "Checking now."
|
||||
"<tool_calls:opensource>\n<tool_call:opensource>get_weather<tool_sep:opensource>\n"
|
||||
"<arg_key:opensource>city</arg_key:opensource>\n"
|
||||
"<arg_value:opensource>Paris</arg_value:opensource>\n"
|
||||
"</tool_call:opensource>\n</tool_calls:opensource>" + _EOS,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
parsed = r.parse_response(comp, tools=TOOLS)
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.status is ToolCallParseStatus.OK
|
||||
stripped = _strip_stop_tokens(comp, {tok.convert_tokens_to_ids(_EOS)})
|
||||
s, e = tc.token_span
|
||||
assert stripped[s] == tok.convert_tokens_to_ids("<tool_call:opensource>")
|
||||
assert stripped[e - 1] == tok.convert_tokens_to_ids("</tool_call:opensource>")
|
||||
# The reported block decodes to exactly this call, no reasoning/content leak.
|
||||
block = tok.decode(stripped[s:e], skip_special_tokens=False)
|
||||
assert block.startswith("<tool_call:opensource>get_weather")
|
||||
assert "Let me think" not in block and "Checking now" not in block
|
||||
|
||||
|
||||
# ── bridge close-token synthesis ─────────────────────────────────────────
|
||||
|
||||
|
||||
def test_bridge_tool_cycle_matches_full_render():
|
||||
"""A bridge over a clean assistant tool-call turn (completion ends in
|
||||
<|hy_eos|>) must be byte-identical to a fresh full render — no spurious
|
||||
close token wedged in."""
|
||||
r = _renderer(thinking_retention="all")
|
||||
eos = _tok().convert_tokens_to_ids(_EOS)
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
}
|
||||
prev = [{"role": "user", "content": "Weather?"}]
|
||||
pp = r.render_ids(prev, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, asst])[len(pp) :])
|
||||
assert pc[-1] == eos # tool-call turn closes with eos
|
||||
|
||||
bridged = r.bridge_to_next_turn(pp, pc, [{"role": "tool", "content": '{"t": 20}'}])
|
||||
fresh = r.render_ids(
|
||||
[*prev, asst, {"role": "tool", "content": '{"t": 20}'}],
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
assert bridged is not None and bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_tool_groups_across_user_turn_match_full_render():
|
||||
"""Within one extension, ``is_tool_first`` is consumed by the first tool
|
||||
group and never resets (no assistant turns are allowed in extensions), so
|
||||
a second group after a user turn must not re-open <tool_responses> —
|
||||
exactly as a fresh full render tokenizes it."""
|
||||
r = _renderer(preserved_thinking=True)
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
}
|
||||
prev = [{"role": "user", "content": "Weather?"}]
|
||||
pp = r.render_ids(prev, tools=TOOLS, add_generation_prompt=True)
|
||||
pc = list(r.render_ids([*prev, asst], tools=TOOLS)[len(pp) :])
|
||||
|
||||
ext = [
|
||||
{"role": "tool", "content": "sunny"},
|
||||
{"role": "user", "content": "And tomorrow?"},
|
||||
{"role": "tool", "content": "rainy"},
|
||||
]
|
||||
bridged = r.bridge_to_next_turn(pp, pc, ext, tools=TOOLS)
|
||||
fresh = r.render_ids([*prev, asst, *ext], tools=TOOLS, add_generation_prompt=True)
|
||||
assert bridged is not None and bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_declines_on_empty_completion():
|
||||
"""With no sampled completion there is no assistant turn to extend — the
|
||||
bridge declines (so a stream ending at a </tool_responses> tool-section
|
||||
boundary never gets a spurious <|hy_eos|> wedged before the extension)."""
|
||||
rf = _renderer(
|
||||
fallback_strategy="reasoning_toolcall_retry", thinking_retention="all"
|
||||
)
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
}
|
||||
base = [
|
||||
{"role": "user", "content": "Weather?"},
|
||||
asst,
|
||||
{"role": "tool", "content": '{"t": 20}'},
|
||||
]
|
||||
prompt = rf.render_ids(base, add_generation_prompt=True) # fallback → no gen prompt
|
||||
assert prompt[-1] == _tok().convert_tokens_to_ids("</tool_responses:opensource>")
|
||||
assert (
|
||||
rf.bridge_to_next_turn(prompt, [], [{"role": "tool", "content": "more"}])
|
||||
is None
|
||||
)
|
||||
@@ -353,12 +353,13 @@ def test_build_training_sample_content_sft_roles_picks_up_tool_body(
|
||||
{"role": "tool", "content": "done", "tool_call_id": "call_z"},
|
||||
{"role": "assistant", "content": "OK."},
|
||||
]
|
||||
ids, mask = build_training_sample(
|
||||
sample = build_training_sample(
|
||||
renderer,
|
||||
msgs,
|
||||
role_to_mask=lambda m: m["role"] == "assistant",
|
||||
content_sft_roles={"tool"},
|
||||
)
|
||||
ids, mask = sample.token_ids, sample.loss_mask
|
||||
assert len(mask) == len(ids)
|
||||
|
||||
# We need at least one trainable tool-body token if the renderer
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
"""Laguna-XS-2.1 focused tests.
|
||||
|
||||
The shared matrices (conftest / config-parity) already assert byte
|
||||
parity on the common shapes; this file pins the behaviours specific to
|
||||
the XS-2.1 template that those matrices don't generate:
|
||||
|
||||
- the empty-system opt-out (and the empty ``<system></system>`` block
|
||||
under ``enable_thinking``),
|
||||
- verbatim content / reasoning (no whitespace normalisation),
|
||||
- reasoning gated on ``enable_thinking`` rather than on the data,
|
||||
- packed tool-call args,
|
||||
- parse round-trips under ``enable_thinking=True`` (the shared roundtrip
|
||||
matrix runs the default config, where the template drops reasoning at
|
||||
render time, so reasoning can't round-trip there by design),
|
||||
- bridge extensions matching a fresh render byte-for-byte.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import LagunaXS21RendererConfig
|
||||
from renderers.laguna_xs2 import LagunaXS21Renderer
|
||||
|
||||
_MODEL = "poolside/Laguna-XS-2.1"
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "The city name"},
|
||||
"days": {"type": "integer", "description": "Forecast days"},
|
||||
},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _tok():
|
||||
return load_tokenizer(_MODEL)
|
||||
|
||||
|
||||
def _renderer(**config_kwargs) -> LagunaXS21Renderer:
|
||||
renderer = create_renderer(_tok(), LagunaXS21RendererConfig(**config_kwargs))
|
||||
assert isinstance(renderer, LagunaXS21Renderer)
|
||||
return renderer
|
||||
|
||||
|
||||
def _expected(msgs, *, tools=None, add_generation_prompt=False, **template_kwargs):
|
||||
return list(
|
||||
_tok().apply_chat_template(
|
||||
msgs,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
**template_kwargs,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ── Variant-specific byte parity ──────────────────────────────────────
|
||||
|
||||
|
||||
def test_empty_system_opts_out_of_system_block():
|
||||
"""An empty caller system message suppresses the default system
|
||||
prompt; with no tools and no thinking there is no <system> block."""
|
||||
msgs = [
|
||||
{"role": "system", "content": ""},
|
||||
{"role": "user", "content": "Hi"},
|
||||
]
|
||||
r = _renderer()
|
||||
assert r.render_ids(msgs, add_generation_prompt=True) == _expected(
|
||||
msgs, add_generation_prompt=True
|
||||
)
|
||||
text = _tok().decode(r.render_ids(msgs, add_generation_prompt=True))
|
||||
assert "<system>" not in text
|
||||
|
||||
|
||||
def test_empty_system_with_thinking_renders_empty_block():
|
||||
"""enable_thinking alone forces the <system> block, even when the
|
||||
empty caller system message removed all of its content."""
|
||||
msgs = [
|
||||
{"role": "system", "content": ""},
|
||||
{"role": "user", "content": "Hi"},
|
||||
]
|
||||
r = _renderer(enable_thinking=True)
|
||||
ours = r.render_ids(msgs, add_generation_prompt=True)
|
||||
assert ours == _expected(msgs, add_generation_prompt=True, enable_thinking=True)
|
||||
assert "<system></system>\n" in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_empty_system_with_tools_glues_tools_header():
|
||||
"""With the system content opted out, the tools section opens the
|
||||
block directly: ``<system>### Tools`` with no separating newlines."""
|
||||
msgs = [
|
||||
{"role": "system", "content": ""},
|
||||
{"role": "user", "content": "Weather?"},
|
||||
]
|
||||
r = _renderer()
|
||||
ours = r.render_ids(msgs, tools=TOOLS, add_generation_prompt=True)
|
||||
assert ours == _expected(msgs, tools=TOOLS, add_generation_prompt=True)
|
||||
assert "<system>### Tools" in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_reasoning_dropped_without_thinking():
|
||||
"""enable_thinking=False renders a bare ``</think>`` and drops the
|
||||
message's reasoning entirely."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{"role": "assistant", "reasoning_content": "Simple arithmetic", "content": "4"},
|
||||
]
|
||||
r = _renderer()
|
||||
ours = r.render_ids(msgs)
|
||||
assert ours == _expected(msgs)
|
||||
assert "Simple arithmetic" not in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_reasoning_rendered_verbatim_with_thinking():
|
||||
"""enable_thinking=True wraps the reasoning verbatim — whitespace
|
||||
included, empty included."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "\n spaced reasoning \n",
|
||||
"content": "4",
|
||||
},
|
||||
]
|
||||
r = _renderer(enable_thinking=True)
|
||||
ours = r.render_ids(msgs)
|
||||
assert ours == _expected(msgs, enable_thinking=True)
|
||||
assert "<think>\n spaced reasoning \n</think>" in _tok().decode(ours)
|
||||
|
||||
no_reasoning = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
ours = r.render_ids(no_reasoning)
|
||||
assert ours == _expected(no_reasoning, enable_thinking=True)
|
||||
assert "<think></think>" in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_content_rendered_verbatim():
|
||||
"""Assistant content is not stripped or newline-normalised."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "\n keep my whitespace \n"},
|
||||
]
|
||||
r = _renderer()
|
||||
assert r.render_ids(msgs) == _expected(msgs)
|
||||
|
||||
|
||||
def test_multiple_tool_calls_packed_args():
|
||||
"""Tool-call args pack tightly with mixed value types (strings
|
||||
verbatim, non-strings via tojson)."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Compare Tokyo and Paris"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "Let me check.",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Tokyo", "days": 3},
|
||||
}
|
||||
},
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "Sunny"},
|
||||
{"role": "tool", "content": "Rainy"},
|
||||
]
|
||||
r = _renderer()
|
||||
ours = r.render_ids(msgs, tools=TOOLS, add_generation_prompt=True)
|
||||
assert ours == _expected(msgs, tools=TOOLS, add_generation_prompt=True)
|
||||
assert (
|
||||
"<tool_call>get_weather<arg_key>city</arg_key><arg_value>Tokyo</arg_value>"
|
||||
"<arg_key>days</arg_key><arg_value>3</arg_value></tool_call>"
|
||||
) in _tok().decode(ours)
|
||||
|
||||
|
||||
def test_later_system_message_renders_in_loop():
|
||||
"""A system message after the first renders inline as
|
||||
``<system>{content}</system>``; only the leading one is absorbed
|
||||
into the header."""
|
||||
msgs = [
|
||||
{"role": "system", "content": "Be helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
{"role": "system", "content": "Now be terse."},
|
||||
{"role": "user", "content": "Why?"},
|
||||
]
|
||||
r = _renderer()
|
||||
assert r.render_ids(msgs, add_generation_prompt=True) == _expected(
|
||||
msgs, add_generation_prompt=True
|
||||
)
|
||||
|
||||
|
||||
# ── Masks ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_assistant_prefill_tokens_unsampled():
|
||||
"""The generation prompt is ``<assistant>`` plus the mode's think
|
||||
tag — in a re-render both are scaffold, everything after (through
|
||||
``</assistant>``) is sampled, and the inter-turn newline is not."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "reasoning_content": "greeting", "content": "Hello!"},
|
||||
]
|
||||
for enable_thinking in (False, True):
|
||||
r = _renderer(enable_thinking=enable_thinking)
|
||||
rendered = r.render(msgs)
|
||||
positions = [k for k, i in enumerate(rendered.message_indices) if i == 1]
|
||||
sampled = [rendered.sampled_mask[k] for k in positions]
|
||||
# <assistant> + (<think> | </think>) prefill.
|
||||
assert sampled[:2] == [False, False]
|
||||
# Everything between the prefill and the inter-turn newline is
|
||||
# the model's emission, ending with the sampled </assistant>.
|
||||
assert all(sampled[2:-1]), sampled
|
||||
assert sampled[-1] is False # trailing "\n"
|
||||
assert [rendered.is_content[k] for k in positions] == sampled
|
||||
|
||||
|
||||
# ── Parse ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _completion_ids(text: str) -> list[int]:
|
||||
return _tok().encode(text, add_special_tokens=False)
|
||||
|
||||
|
||||
def test_parse_no_think_completion():
|
||||
"""Under the no-think gen prompt (``</think>`` prefilled), the
|
||||
completion is pure content up to ``</assistant>``."""
|
||||
parsed = _renderer().parse_response(_completion_ids("Four.</assistant>"))
|
||||
assert parsed.content == "Four."
|
||||
assert parsed.reasoning_content is None
|
||||
assert not parsed.tool_calls
|
||||
|
||||
|
||||
def test_parse_preserves_newlines_verbatim():
|
||||
"""The template renders content verbatim, so the parse must not
|
||||
strip the newlines the model emitted."""
|
||||
parsed = _renderer(enable_thinking=True).parse_response(
|
||||
_completion_ids("Chain of thought</think>\nThe answer.\n</assistant>")
|
||||
)
|
||||
assert parsed.reasoning_content == "Chain of thought"
|
||||
assert parsed.content == "\nThe answer.\n"
|
||||
|
||||
|
||||
def test_parse_tool_call_packed_args():
|
||||
parsed = _renderer().parse_response(
|
||||
_completion_ids(
|
||||
"I will check.<tool_call>get_weather"
|
||||
"<arg_key>city</arg_key><arg_value>Tokyo</arg_value>"
|
||||
"<arg_key>days</arg_key><arg_value>3</arg_value>"
|
||||
"</tool_call></assistant>"
|
||||
),
|
||||
tools=TOOLS,
|
||||
)
|
||||
assert parsed.content == "I will check."
|
||||
assert len(parsed.tool_calls) == 1
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.name == "get_weather"
|
||||
assert tc.arguments == {"city": "Tokyo", "days": 3}
|
||||
|
||||
|
||||
def test_roundtrip_reasoning_with_thinking():
|
||||
"""render → parse recovers reasoning and content under
|
||||
enable_thinking=True (the mode where the template keeps them)."""
|
||||
r = _renderer(enable_thinking=True)
|
||||
prompt = [{"role": "user", "content": "What is 2+2?"}]
|
||||
msg = {
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Two plus two equals four.",
|
||||
"content": "The answer is four.",
|
||||
}
|
||||
pp = r.render_ids(prompt, add_generation_prompt=True)
|
||||
full = r.render_ids([*prompt, msg])
|
||||
completion = full[len(pp) :]
|
||||
parsed = r.parse_response(completion)
|
||||
assert parsed.reasoning_content == "Two plus two equals four."
|
||||
assert parsed.content == "The answer is four."
|
||||
|
||||
|
||||
# ── Bridge ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _bridge_case(r, prev, asst, ext, *, tools=None, **template_kwargs):
|
||||
"""Return (bridged, fresh) token ids for extending prev+asst by ext."""
|
||||
pp = r.render_ids(prev, tools=tools, add_generation_prompt=True)
|
||||
full_turn = r.render_ids([*prev, asst], tools=tools)
|
||||
# The turn ends "</assistant>\n"; the model's completion stops at
|
||||
# </assistant>, so drop the template's inter-turn newline token.
|
||||
completion = full_turn[len(pp) : -1]
|
||||
assert completion[-1] == r._assistant_end
|
||||
bridged = r.bridge_to_next_turn(pp, completion, ext, tools=tools)
|
||||
fresh = r.render_ids([*prev, asst, *ext], tools=tools, add_generation_prompt=True)
|
||||
return bridged, fresh
|
||||
|
||||
|
||||
def test_bridge_user_extension_matches_full_render():
|
||||
prev = [{"role": "user", "content": "Hi"}]
|
||||
asst = {"role": "assistant", "content": "Hello!"}
|
||||
ext = [{"role": "user", "content": "Bye"}]
|
||||
for enable_thinking in (False, True):
|
||||
r = _renderer(enable_thinking=enable_thinking)
|
||||
bridged, fresh = _bridge_case(r, prev, asst, ext)
|
||||
assert bridged is not None
|
||||
assert bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_tool_extension_matches_full_render():
|
||||
prev = [{"role": "user", "content": "Weather in Tokyo, then Paris?"}]
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Tokyo"}}}
|
||||
],
|
||||
}
|
||||
ext = [
|
||||
{"role": "tool", "content": "Sunny"},
|
||||
{"role": "user", "content": "And Paris?"},
|
||||
{"role": "tool", "content": "Rainy"},
|
||||
]
|
||||
r = _renderer()
|
||||
bridged, fresh = _bridge_case(r, prev, asst, ext, tools=TOOLS)
|
||||
assert bridged is not None
|
||||
assert bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_synthesizes_close_on_truncation():
|
||||
prev = [{"role": "user", "content": "Hi"}]
|
||||
asst = {"role": "assistant", "content": "Hello!"}
|
||||
ext = [{"role": "user", "content": "Bye"}]
|
||||
r = _renderer()
|
||||
pp = r.render_ids(prev, add_generation_prompt=True)
|
||||
full_turn = r.render_ids([*prev, asst])
|
||||
# Truncated: no </assistant> in the completion.
|
||||
completion = full_turn[len(pp) : -2]
|
||||
assert r._assistant_end not in completion
|
||||
bridged = r.bridge_to_next_turn(pp, completion, ext)
|
||||
assert bridged is not None
|
||||
# The synthesised close makes the tape identical to the clean-stop
|
||||
# bridge, which matches the fresh render byte-for-byte.
|
||||
fresh = r.render_ids([*prev, asst, *ext], add_generation_prompt=True)
|
||||
assert bridged.token_ids == fresh
|
||||
|
||||
|
||||
def test_bridge_rejects_assistant_extension():
|
||||
r = _renderer()
|
||||
prev = [{"role": "user", "content": "Hi"}]
|
||||
pp = r.render_ids(prev, add_generation_prompt=True)
|
||||
assert (
|
||||
r.bridge_to_next_turn(
|
||||
pp, [r._assistant_end], [{"role": "assistant", "content": "x"}]
|
||||
)
|
||||
is None
|
||||
)
|
||||
+21
-11
@@ -1,10 +1,10 @@
|
||||
"""Llama-3 renderer coverage.
|
||||
|
||||
Covers ``Llama3Renderer`` and the ``meta-llama/Llama-3.2-{1B,3B}-Instruct``
|
||||
entries in ``MODEL_RENDERER_MAP``. Tokenizers are loaded via the
|
||||
unrestricted ``unsloth/Llama-3.2-{1B,3B}-Instruct`` mirrors (verified
|
||||
byte-identical chat templates) so CI doesn't need an HF token with Meta
|
||||
license access.
|
||||
entries in ``MODEL_RENDERER_MAP``. ``load_tokenizer`` uses the
|
||||
unrestricted ``unsloth/Llama-3.2-{1B,3B}-Instruct`` mirrors underneath
|
||||
(verified byte-identical chat templates) so CI doesn't need an HF token
|
||||
with Meta license access.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,7 +34,7 @@ _MODEL_PAIRS = [
|
||||
@pytest.fixture(scope="module", params=_MODEL_PAIRS, ids=[m for m, _ in _MODEL_PAIRS])
|
||||
def llama_pair(request):
|
||||
canonical, mirror = request.param
|
||||
tok = load_tokenizer(mirror)
|
||||
tok = load_tokenizer(canonical)
|
||||
renderer = Llama3Renderer(tok, Llama3RendererConfig(date_string=_PINNED_DATE))
|
||||
return canonical, mirror, tok, renderer
|
||||
|
||||
@@ -58,6 +58,14 @@ def test_create_renderer_via_explicit_config(llama_pair):
|
||||
assert isinstance(r, Llama3Renderer)
|
||||
|
||||
|
||||
def test_create_renderer_auto_resolves_after_mirror_load(llama_pair):
|
||||
"""``load_tokenizer(canonical_meta_id)`` loads from the unrestricted
|
||||
mirror but preserves the canonical name needed for auto-resolution."""
|
||||
canonical, _, tok, _ = llama_pair
|
||||
assert tok.name_or_path == canonical
|
||||
assert isinstance(create_renderer(tok), Llama3Renderer)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constructor contract
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -72,8 +80,8 @@ def test_default_date_matches_chat_template_strftime_fallback(llama_pair):
|
||||
|
||||
|
||||
def test_preserve_thinking_flags_are_noops(llama_pair):
|
||||
"""Llama-3 has no reasoning channel, so the ``preserve_*_thinking``
|
||||
flags are accepted but never change the token stream — the same
|
||||
"""Llama-3 has no reasoning channel, so any ``thinking_retention``
|
||||
level is accepted but never changes the token stream — the same
|
||||
never-preserves contract as Kimi-K2 / Qwen3-VL. (Cross-renderer
|
||||
coverage lives in tests/test_preserve_thinking.py.)"""
|
||||
_, _, tok, _ = llama_pair
|
||||
@@ -86,10 +94,12 @@ def test_preserve_thinking_flags_are_noops(llama_pair):
|
||||
},
|
||||
]
|
||||
base = Llama3Renderer(tok).render_ids(msgs)
|
||||
for flag in ("preserve_all_thinking", "preserve_thinking_between_tool_calls"):
|
||||
r = Llama3Renderer(tok, Llama3RendererConfig(**{flag: True}))
|
||||
assert r.config.__getattribute__(flag) is True
|
||||
assert r.render_ids(msgs) == base, f"{flag} must be a no-op for Llama-3"
|
||||
for level in ("tool_cycle", "all"):
|
||||
r = Llama3Renderer(tok, Llama3RendererConfig(thinking_retention=level))
|
||||
assert r.config.thinking_retention == level
|
||||
assert r.render_ids(msgs) == base, (
|
||||
f"thinking_retention={level!r} must be a no-op for Llama-3"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -9,9 +9,13 @@ repo doesn't auto-propagate.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from renderers.base import TRUSTED_REVISIONS, load_tokenizer
|
||||
import pytest
|
||||
|
||||
from renderers import base
|
||||
from renderers.base import TOKENIZER_SOURCE_OVERRIDES, TRUSTED_REVISIONS, load_tokenizer
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -70,6 +74,23 @@ def test_kimi_loads_with_pinned_revision(mock_from_pretrained):
|
||||
}
|
||||
|
||||
|
||||
@patch("transformers.AutoTokenizer.from_pretrained")
|
||||
def test_meta_llama_loads_tokenizer_from_unsloth_mirror(mock_from_pretrained):
|
||||
"""Canonical Meta Llama repos are gated; load their tokenizer/chat
|
||||
template from the audited unrestricted mirror while preserving the
|
||||
canonical name for renderer auto-resolution."""
|
||||
canonical = "meta-llama/Llama-3.2-1B-Instruct"
|
||||
mirror = "unsloth/Llama-3.2-1B-Instruct"
|
||||
mock_from_pretrained.return_value = SimpleNamespace(name_or_path=mirror)
|
||||
|
||||
tok = load_tokenizer(canonical)
|
||||
|
||||
args, kwargs = mock_from_pretrained.call_args
|
||||
assert args == (mirror,)
|
||||
assert kwargs == {"trust_remote_code": False}
|
||||
assert tok.name_or_path == canonical
|
||||
|
||||
|
||||
@patch("transformers.AutoTokenizer.from_pretrained")
|
||||
def test_unknown_path_falls_through_to_no_remote_code(mock_from_pretrained):
|
||||
"""Unknown / fine-tuned model paths — including ``moonshotai/Kimi-K2*``
|
||||
@@ -92,6 +113,33 @@ def test_unknown_path_falls_through_to_no_remote_code(mock_from_pretrained):
|
||||
)
|
||||
|
||||
|
||||
def test_tokenizer_source_overrides_are_exact_llama_mirrors():
|
||||
"""Mirror overrides are intentionally narrow: only verified
|
||||
byte-identical Llama tokenizer/template mirrors should live here."""
|
||||
assert TOKENIZER_SOURCE_OVERRIDES == {
|
||||
"meta-llama/Llama-3.2-1B-Instruct": "unsloth/Llama-3.2-1B-Instruct",
|
||||
"meta-llama/Llama-3.2-3B-Instruct": "unsloth/Llama-3.2-3B-Instruct",
|
||||
}
|
||||
|
||||
|
||||
def test_get_offset_tokenizer_rejects_offsetless_byo():
|
||||
"""BYO tokenizers without ``return_offsets_mapping`` support raise a
|
||||
clear error. Hand-coded renderers concatenate scaffold + body in one
|
||||
BPE pass and attribute tokens via the fast tokenizer's offset map;
|
||||
no transparent reload-from-name_or_path fallback exists. The
|
||||
contract is: pass a fast tokenizer or get a loud error at construct
|
||||
time, not silent BPE drift at the wrap/body boundary."""
|
||||
|
||||
class _NoOffsets:
|
||||
name_or_path = "anywhere/anything"
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
raise NotImplementedError("BYO tokenizer has no offsets")
|
||||
|
||||
with pytest.raises(RuntimeError, match="fast tokenizer.*offsets"):
|
||||
base._get_offset_tokenizer(_NoOffsets())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Smoke: real tokenizer loads behave as expected
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,213 +0,0 @@
|
||||
"""Coverage for the fastokens fast-path in ``renderers.base.load_tokenizer``.
|
||||
|
||||
``load_tokenizer`` defaults to routing every supported model through
|
||||
``fastokens.patch_transformers()`` for ~10x faster encode. Models in
|
||||
``FASTOKENS_INCOMPATIBLE`` skip the patch (DeepSeek's Metaspace
|
||||
pretokenizer isn't supported). Callers can opt out per-call with
|
||||
``use_fastokens=False``.
|
||||
|
||||
These tests pin the policy:
|
||||
|
||||
1. The denylist contains the empirically-verified incompat models —
|
||||
adding to it should be a deliberate review action.
|
||||
2. With ``use_fastokens=True`` (the default) on a compatible model, the
|
||||
resulting tokenizer's backend is the fastokens shim. Encode output
|
||||
stays byte-identical to vanilla.
|
||||
3. With ``use_fastokens=False``, the resulting tokenizer is vanilla.
|
||||
4. For incompat models, the fast path is silently skipped and the
|
||||
tokenizer still loads + encodes correctly.
|
||||
5. The fastokens patch is removed immediately after the load so it
|
||||
doesn't leak into the caller's process — subsequent
|
||||
``AutoTokenizer.from_pretrained`` calls outside ``load_tokenizer``
|
||||
use vanilla.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from renderers.base import (
|
||||
FASTOKENS_INCOMPATIBLE,
|
||||
load_tokenizer,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Denylist shape
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_fastokens_incompatible_is_explicit_set():
|
||||
"""The denylist is small and audited — pinning the exact contents
|
||||
catches accidental drift. Adding/removing entries should be a
|
||||
deliberate action with a parity probe."""
|
||||
assert FASTOKENS_INCOMPATIBLE == frozenset(
|
||||
{
|
||||
"deepseek-ai/DeepSeek-V3",
|
||||
"deepseek-ai/DeepSeek-V3-Base",
|
||||
"deepseek-ai/DeepSeek-R1",
|
||||
"deepseek-ai/DeepSeek-R1-0528",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fast path (compatible model — Qwen3.5-9B as representative)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
_FAST_MODEL = "Qwen/Qwen3.5-9B"
|
||||
|
||||
|
||||
def _backend_class_name(tok) -> str:
|
||||
"""Return the class name of the underlying backend object so tests
|
||||
can tell vanilla from fastokens-shimmed tokenizers."""
|
||||
backend = getattr(tok, "_tokenizer", None)
|
||||
return type(backend).__name__ if backend is not None else type(tok).__name__
|
||||
|
||||
|
||||
def test_default_uses_fastokens_on_compatible_model():
|
||||
tok = load_tokenizer(_FAST_MODEL)
|
||||
# The shim type is named ``_TokenizerShim`` (see fastokens._compat);
|
||||
# match by name so we don't import private fastokens internals.
|
||||
assert "Shim" in _backend_class_name(tok), (
|
||||
f"Expected fastokens shim backend, got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_explicit_off_returns_vanilla_backend():
|
||||
tok = load_tokenizer(_FAST_MODEL, use_fastokens=False)
|
||||
assert "Shim" not in _backend_class_name(tok), (
|
||||
f"Expected vanilla backend, got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_fast_and_vanilla_encode_identically_on_compatible_model():
|
||||
fast = load_tokenizer(_FAST_MODEL)
|
||||
vanilla = load_tokenizer(_FAST_MODEL, use_fastokens=False)
|
||||
samples = [
|
||||
"Hello, world!",
|
||||
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
|
||||
"🌍 emoji + 中文 + tabs\there",
|
||||
" ".join([f"word_{i}" for i in range(50)]),
|
||||
]
|
||||
for s in samples:
|
||||
assert fast.encode(s, add_special_tokens=False) == vanilla.encode(
|
||||
s, add_special_tokens=False
|
||||
), f"encode diverged on {s!r}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Denylist: incompat models silently skip the patch and still load.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", sorted(FASTOKENS_INCOMPATIBLE))
|
||||
def test_incompat_model_loads_via_vanilla_backend(model):
|
||||
"""For models we know diverge / fail under fastokens, the fast path
|
||||
must be skipped so the load still succeeds with a vanilla backend."""
|
||||
if "DeepSeek" in model:
|
||||
# Skip if upstream gating / size makes the load impractical here.
|
||||
# We only care that the path doesn't try fastokens. Probe the
|
||||
# tokenizer_config to make sure the repo is reachable; if not,
|
||||
# skip rather than fail (CI without HF auth, network issues).
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
try:
|
||||
HfApi().repo_info(model)
|
||||
except Exception as e:
|
||||
pytest.skip(f"{model}: repo unreachable in this env ({e})")
|
||||
tok = load_tokenizer(model)
|
||||
assert "Shim" not in _backend_class_name(tok), (
|
||||
f"{model}: should NOT have been patched; got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
# And it still encodes.
|
||||
ids = tok.encode("hello", add_special_tokens=False)
|
||||
assert len(ids) > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Patch must not leak: AutoTokenizer.from_pretrained calls OUTSIDE
|
||||
# load_tokenizer should still produce a vanilla tokenizer.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_patch_is_unloaded_after_call():
|
||||
"""``load_tokenizer`` brackets the fastokens patch. After it returns
|
||||
a fastokens-shimmed tokenizer, a fresh ``AutoTokenizer.from_pretrained``
|
||||
call must NOT pick up the patch — the user's process stays clean."""
|
||||
fast = load_tokenizer(_FAST_MODEL)
|
||||
assert "Shim" in _backend_class_name(fast), "preconditions: fast path active"
|
||||
|
||||
# Now call AutoTokenizer.from_pretrained directly. It MUST be vanilla.
|
||||
direct = AutoTokenizer.from_pretrained(_FAST_MODEL, trust_remote_code=False)
|
||||
assert "Shim" not in _backend_class_name(direct), (
|
||||
f"fastokens patch leaked into user-side AutoTokenizer call: "
|
||||
f"got {_backend_class_name(direct)!r}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Failure-mode fallback: if fastokens raises during the patched load,
|
||||
# load_tokenizer falls back to vanilla without surfacing the error.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_fallback_on_fastokens_load_error(monkeypatch):
|
||||
"""Simulate fastokens raising during patched load — load_tokenizer
|
||||
should fall back to vanilla and return a working tokenizer."""
|
||||
import renderers.base as rb
|
||||
|
||||
def _boom(*args, **kwargs):
|
||||
raise ValueError("simulated fastokens failure: unsupported pre-tokenizer")
|
||||
|
||||
monkeypatch.setattr(rb, "_patched_load", _boom)
|
||||
|
||||
tok = load_tokenizer(_FAST_MODEL) # default use_fastokens=True
|
||||
# The vanilla fallback ran — backend is not a fastokens shim.
|
||||
assert "Shim" not in _backend_class_name(tok)
|
||||
# Still works.
|
||||
assert len(tok.encode("hi", add_special_tokens=False)) > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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)}"
|
||||
)
|
||||
@@ -37,12 +37,16 @@ from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
|
||||
def _config_for_model(model_name: str, **kwargs):
|
||||
renderer_name = MODEL_RENDERER_MAP[model_name]
|
||||
return _config_class_for(renderer_name)(**kwargs)
|
||||
|
||||
|
||||
def _config_with_add_vision_id(model_name: str, add_vision_id: bool):
|
||||
"""Build the typed config for ``model_name`` (resolved via
|
||||
``MODEL_RENDERER_MAP``) with ``add_vision_id`` set. The qwen_vl
|
||||
family — Qwen3.5 and Qwen3-VL — both expose this field."""
|
||||
renderer_name = MODEL_RENDERER_MAP[model_name]
|
||||
return _config_class_for(renderer_name)(add_vision_id=add_vision_id)
|
||||
return _config_for_model(model_name, add_vision_id=add_vision_id)
|
||||
|
||||
|
||||
pytest.importorskip("PIL", reason="Pillow required for multimodal tests")
|
||||
@@ -529,10 +533,9 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
|
||||
):
|
||||
"""Bridge-to-next-turn invariants for the multimodal case.
|
||||
|
||||
Asserts three properties that should hold for every renderer
|
||||
regardless of thinking-mode quirks (the prior bridge-vs-full
|
||||
invariant was too strong — see commit log for the divergence
|
||||
rationale on thinking renderers):
|
||||
The renderer is forced to ``thinking_retention="all"`` so this test
|
||||
isolates multimodal bridge mechanics from thinking-retention policy.
|
||||
Asserts three properties:
|
||||
|
||||
1. **Verbatim prefix**: ``bridged.token_ids`` begins with
|
||||
``previous_prompt_ids + previous_completion_ids``. Whatever the
|
||||
@@ -552,7 +555,13 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
|
||||
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
|
||||
|
||||
kit = _modality_kit(modality, mm_model_name)
|
||||
tokenizer, _, renderer = _load_processor_and_renderer(mm_model_name)
|
||||
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
_config_for_model(mm_model_name, thinking_retention="all"),
|
||||
)
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
|
||||
initial = [
|
||||
{
|
||||
@@ -574,6 +583,12 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
|
||||
]
|
||||
|
||||
initial_rendered = renderer.render(initial, add_generation_prompt=True)
|
||||
prior_mm = initial_rendered.multi_modal_data
|
||||
prior_counts = (
|
||||
len(prior_mm.mm_placeholders.get(modality, [])),
|
||||
len(prior_mm.mm_items.get(modality, [])),
|
||||
len(prior_mm.mm_hashes.get(modality, [])),
|
||||
)
|
||||
# ``previous_completion_ids`` mirrors what a sampler would emit
|
||||
# starting AFTER the prompt's assistant role opener — i.e. the
|
||||
# response text followed by ``<|im_end|>``.
|
||||
@@ -623,6 +638,19 @@ def test_multimodal_bridge_extends_and_carries_mm_data(
|
||||
hashes = bridged_mm.mm_hashes.get(modality, [])
|
||||
assert len(items) == 2 and len(hashes) == 2
|
||||
|
||||
# (2b) The prior turn's sidecar is unchanged — the bridge copies the
|
||||
# per-modality lists, so the carried-forward item doesn't grow the
|
||||
# caller's previous_multi_modal_data in place.
|
||||
assert (
|
||||
(
|
||||
len(prior_mm.mm_placeholders.get(modality, [])),
|
||||
len(prior_mm.mm_items.get(modality, [])),
|
||||
len(prior_mm.mm_hashes.get(modality, [])),
|
||||
)
|
||||
== prior_counts
|
||||
== (1, 1, 1)
|
||||
), f"{mm_model_name} / {modality}: bridge mutated previous_multi_modal_data"
|
||||
|
||||
# (3) Extension contains the new turn's pad run, and its
|
||||
# placeholder offset lands inside the extension region.
|
||||
pad_id = tokenizer.convert_tokens_to_ids(kit["placeholder_token"])
|
||||
@@ -806,9 +834,15 @@ def test_bridge_refuses_when_add_vision_id_loses_prior_count(
|
||||
|
||||
kit = _modality_kit(modality, mm_model_name)
|
||||
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
|
||||
# Force bridge-allowed retention so this test isolates add_vision_id
|
||||
# counter state from the user-turn retention gate.
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
_config_with_add_vision_id(mm_model_name, True),
|
||||
_config_for_model(
|
||||
mm_model_name,
|
||||
add_vision_id=True,
|
||||
thinking_retention="all",
|
||||
),
|
||||
)
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
|
||||
@@ -0,0 +1,676 @@
|
||||
"""Exhaustive token-for-token parity for the Nemotron-3 renderer.
|
||||
|
||||
The shared barrage in ``test_render_ids.py`` covers the common message
|
||||
shapes against every model. This file pins the Nemotron-3-specific template
|
||||
branches that the shared matrix can't reach — they'd fail on other models or
|
||||
exercise behaviour unique to the Nemotron-3 chat template:
|
||||
|
||||
* reasoning + empty / ``None`` content with and without tool calls (the
|
||||
template trims the assembled ``<think>…</think>{content}`` block and appends
|
||||
exactly one separator — a stray ``\\n`` here is the most common agentic
|
||||
regression);
|
||||
* the historical-thinking truncation boundary, which is ``loop.index0 <
|
||||
last_user_idx`` in **all three** variants (Nano / Super / Ultra) — so an
|
||||
in-flight tool cycle (assistant turns after the last user message) keeps its
|
||||
reasoning by default;
|
||||
* inline ``<think>…</think>`` tags carried in ``content`` rendering verbatim
|
||||
(the template only reformats reasoning supplied via ``reasoning_content``);
|
||||
* verbatim (unstripped) user / system / tool content and ``reasoning_content``;
|
||||
* the ``enable_thinking`` / ``truncate_history_thinking`` template kwargs;
|
||||
* the per-variant reasoning-effort kwargs: ``low_effort`` (Super) and
|
||||
``medium_effort`` (Ultra), each a no-op on the variants that don't define it.
|
||||
|
||||
Every assertion compares ``renderer.render_ids(...)`` to
|
||||
``tokenizer.apply_chat_template(..., tokenize=True)`` — a pass means the
|
||||
renderer is byte-for-byte faithful for that case. Tokenizers are loaded from
|
||||
the local HF cache (offline); no network.
|
||||
|
||||
The variants split across two configs: ``nemotron-3`` (Nano / Super, with
|
||||
``low_effort``) and ``nemotron-3-ultra`` (Ultra, with ``medium_effort``). The
|
||||
helper resolves the right config class per model from ``MODEL_RENDERER_MAP``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
# BF16 / FP8 share a tokenizer; only the BF16 checkpoints are cached for tests.
|
||||
NANO = "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"
|
||||
SUPER = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
|
||||
ULTRA = "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16"
|
||||
MODELS = [NANO, SUPER, ULTRA]
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _tok(model: str):
|
||||
return load_tokenizer(model)
|
||||
|
||||
|
||||
def _config_cls(model: str):
|
||||
"""The typed-config class the model resolves to (``nemotron-3`` for
|
||||
Nano/Super, ``nemotron-3-ultra`` for Ultra)."""
|
||||
return _config_class_for(MODEL_RENDERER_MAP[model])
|
||||
|
||||
|
||||
def _renderer(model: str, **flags):
|
||||
# Build with the model's own variant config so the renderer picks the right
|
||||
# ``</think>`` glue (and only valid kwargs are accepted).
|
||||
return create_renderer(_tok(model), _config_cls(model)(**flags))
|
||||
|
||||
|
||||
def _expected(
|
||||
model: str, messages, *, tools=None, add_generation_prompt=False, **kwargs
|
||||
):
|
||||
out = _tok(model).apply_chat_template(
|
||||
messages,
|
||||
tools=tools,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
**kwargs,
|
||||
)
|
||||
if isinstance(out, str): # some tokenizers return str even with tokenize=True
|
||||
return list(_tok(model).encode(out, add_special_tokens=False))
|
||||
return list(out)
|
||||
|
||||
|
||||
def _assert_parity(
|
||||
model, messages, *, tools=None, add_generation_prompt=False, **template_kwargs
|
||||
):
|
||||
"""Renderer ids == apply_chat_template ids for ``model``.
|
||||
|
||||
``template_kwargs`` (e.g. ``enable_thinking``, ``truncate_history_thinking``)
|
||||
are forwarded to both the renderer config and ``apply_chat_template`` so the
|
||||
two sides stay aligned.
|
||||
"""
|
||||
renderer = _renderer(model, **template_kwargs)
|
||||
got = renderer.render_ids(
|
||||
messages, tools=tools, add_generation_prompt=add_generation_prompt
|
||||
)
|
||||
exp = _expected(
|
||||
model,
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
**template_kwargs,
|
||||
)
|
||||
assert got == exp, (
|
||||
f"{model}: render_ids diverged from apply_chat_template\n"
|
||||
f" exp …{_tok(model).decode(exp[-40:])!r}\n"
|
||||
f" got …{_tok(model).decode(got[-40:])!r}"
|
||||
)
|
||||
|
||||
|
||||
pytestmark = pytest.mark.parametrize("model", MODELS, ids=["nano", "super", "ultra"])
|
||||
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "The city name"}
|
||||
},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
# ── Reasoning + tool calls: the trim / separator boundary ─────────────
|
||||
|
||||
|
||||
def test_reasoning_empty_content_tool_call(model):
|
||||
"""reason → tool call, no prose. Must be ``</think>\\n<tool_call>`` (one
|
||||
newline), not ``</think>\\n\\n<tool_call>``."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "I should call the weather tool.",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_none_content_tool_call(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Call the tool.",
|
||||
"content": None,
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_content_tool_call(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Think first.",
|
||||
"content": "Let me check.",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_empty_content_no_tool_call(model):
|
||||
"""reason → empty answer, no tool call: ``</think>`` glued to ``<|im_end|>``."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{"role": "assistant", "reasoning_content": "thinking", "content": ""},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_multiple_tool_calls_with_reasoning(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris and London?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Two cities — two calls.",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
},
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "London"},
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_tool_call_with_nested_object_args(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "go"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {
|
||||
"city": "Paris",
|
||||
"opts": {"unit": "c", "days": [1, 2]},
|
||||
},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
# ── Historical-thinking truncation boundary (last_user_idx) ───────────
|
||||
|
||||
|
||||
def test_inflight_tool_cycle_keeps_reasoning(model):
|
||||
"""Assistant turns after the last user message (the in-flight tool cycle)
|
||||
keep their reasoning by default — boundary is ``loop.index0 <
|
||||
last_user_idx`` in every variant."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Call the tool first.",
|
||||
"content": "calling",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Now I can answer.",
|
||||
"content": "It is 20 degrees.",
|
||||
},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_history_truncation_drops_older_reasoning(model):
|
||||
"""A reasoning turn before the last user message is collapsed to an empty
|
||||
think block (tool-call branch trims the remainder on Nano/Super)."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Q1"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "reasoning before tool",
|
||||
"content": "calling",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{"role": "assistant", "reasoning_content": "after", "content": "Done."},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{"role": "assistant", "reasoning_content": "final", "content": "A2"},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_two_block_tool_conversation(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "system", "content": "be brief"},
|
||||
{"role": "user", "content": "first"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "R2",
|
||||
"content": "calling.",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "a"}}}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "result-a"},
|
||||
{"role": "assistant", "reasoning_content": "R4", "content": "answer-1"},
|
||||
{"role": "user", "content": "second"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "R6",
|
||||
"content": "calling.",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "b"}}}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "result-b"},
|
||||
{"role": "assistant", "reasoning_content": "R8", "content": "answer-2"},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_plain_multi_turn_reasoning_truncation(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Q1"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "long reasoning one",
|
||||
"content": "A1",
|
||||
},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "long reasoning two",
|
||||
"content": "A2",
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("truncate", [True, False])
|
||||
def test_truncate_history_thinking_kwarg(model, truncate):
|
||||
"""``truncate_history_thinking=False`` keeps reasoning on every past turn."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Q1"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "first reasoning",
|
||||
"content": "A1",
|
||||
},
|
||||
{"role": "user", "content": "Q2"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "second reasoning",
|
||||
"content": "A2",
|
||||
},
|
||||
],
|
||||
truncate_history_thinking=truncate,
|
||||
)
|
||||
|
||||
|
||||
# ── Inline <think> tags carried in content (no reasoning_content field) ─
|
||||
|
||||
|
||||
def test_inline_think_tags_final_turn_verbatim(model):
|
||||
"""Inline ``<think>…</think>`` in the final assistant ``content`` renders
|
||||
verbatim — the renderer must not parse + reformat it."""
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{"role": "assistant", "content": "<think>secret</think>visible"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_inline_think_tags_history_turn(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "<think>secret reasoning</think>visible answer",
|
||||
},
|
||||
{"role": "user", "content": "again"},
|
||||
{"role": "assistant", "content": "second"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
# ── Verbatim (unstripped) content ─────────────────────────────────────
|
||||
|
||||
|
||||
def test_system_content_whitespace_verbatim(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "system", "content": " padded system "},
|
||||
{"role": "user", "content": "hi"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_user_content_whitespace_verbatim(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": " padded user "},
|
||||
{"role": "assistant", "content": "ok"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_assistant_content_whitespace(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{"role": "assistant", "content": " spaced answer "},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_reasoning_content_whitespace_verbatim(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "hi"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": " padded reason ",
|
||||
"content": "answer",
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_tool_content_whitespace_verbatim(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "go"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": " spaced tool result "},
|
||||
{"role": "assistant", "content": "done"},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_system_whitespace_with_tools(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "system", "content": " weather bot "},
|
||||
{"role": "user", "content": "Weather?"},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
# ── Generation prompt / thinking toggle ───────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enable_thinking", [True, False])
|
||||
def test_generation_prompt_thinking_toggle(model, enable_thinking):
|
||||
_assert_parity(
|
||||
model,
|
||||
[{"role": "user", "content": "hi"}],
|
||||
add_generation_prompt=True,
|
||||
enable_thinking=enable_thinking,
|
||||
)
|
||||
|
||||
|
||||
def test_generation_prompt_after_tool_response(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
],
|
||||
tools=TOOLS,
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
|
||||
|
||||
# ── Whole-conversation cycles, no reasoning ───────────────────────────
|
||||
|
||||
|
||||
def test_full_tool_cycle_no_reasoning(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "Let me check.",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20, "condition": "sunny"}'},
|
||||
{"role": "assistant", "content": "It is 20 degrees and sunny."},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_consecutive_tool_responses(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris and London?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
},
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "London"},
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{"role": "tool", "content": '{"temp": 15}'},
|
||||
{"role": "assistant", "content": "Paris: 20, London: 15."},
|
||||
],
|
||||
tools=TOOLS,
|
||||
)
|
||||
|
||||
|
||||
def test_no_system_no_tools_injects_empty_system(model):
|
||||
_assert_parity(
|
||||
model,
|
||||
[
|
||||
{"role": "user", "content": "Hello!"},
|
||||
{"role": "assistant", "content": "Hi there!"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
# ── Reasoning-effort kwargs (variant-specific) ────────────────────────
|
||||
|
||||
_EFFORT_SHAPES = [
|
||||
# gen-prompt shape: hint rides on the (only) user message.
|
||||
([{"role": "user", "content": "solve it"}], {"add_generation_prompt": True}),
|
||||
# multi-turn: hint must land on the LAST user message, not the first.
|
||||
(
|
||||
[
|
||||
{"role": "user", "content": "first"},
|
||||
{"role": "assistant", "content": "ok"},
|
||||
{"role": "user", "content": "second"},
|
||||
],
|
||||
{"add_generation_prompt": True},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
"shape,extra", _EFFORT_SHAPES, ids=["gen_prompt", "multi_turn"]
|
||||
)
|
||||
def test_low_effort_kwarg(model, flag, shape, extra):
|
||||
"""``low_effort`` appends ``\\n\\n{reasoning effort: low}`` to the last user
|
||||
message on **Super**; it's a no-op on **Nano** (its template never defines
|
||||
it). Ultra's config has no such field, so it's skipped."""
|
||||
if model == ULTRA:
|
||||
pytest.skip("low_effort is a nemotron-3 (Nano/Super) kwarg")
|
||||
_assert_parity(model, shape, low_effort=flag, **extra)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
"shape,extra", _EFFORT_SHAPES, ids=["gen_prompt", "multi_turn"]
|
||||
)
|
||||
def test_medium_effort_kwarg(model, flag, shape, extra):
|
||||
"""``medium_effort`` appends ``\\n\\n{reasoning effort: efficient}`` on
|
||||
**Ultra**. Nano/Super configs have no such field, so they're skipped."""
|
||||
if model != ULTRA:
|
||||
pytest.skip("medium_effort is a nemotron-3-ultra kwarg")
|
||||
_assert_parity(model, shape, medium_effort=flag, **extra)
|
||||
|
||||
|
||||
def test_effort_kwarg_lives_on_the_right_variant(model):
|
||||
"""Each effort kwarg is declared only on the variant whose template defines
|
||||
it — the discriminated union rejects the wrong combination at config load."""
|
||||
fields = _config_cls(model).template_field_names()
|
||||
if model == ULTRA:
|
||||
assert "medium_effort" in fields and "low_effort" not in fields
|
||||
else:
|
||||
assert "low_effort" in fields and "medium_effort" not in fields
|
||||
@@ -1,22 +1,37 @@
|
||||
"""Offline wiring tests for the Nemotron-3 Ultra template variant.
|
||||
"""Offline wiring tests for the Nemotron-3 variant split.
|
||||
|
||||
Assert the name-based ``ultra`` auto-selection, the model→renderer mapping,
|
||||
and the typed-config surface WITHOUT loading any tokenizer (no network). This
|
||||
pins the wiring the parity matrix can't reach — in particular the FP8 entry,
|
||||
which no test loads a tokenizer for — so it can't silently rot.
|
||||
Assert the model→renderer mapping, the per-variant typed-config surface, and
|
||||
the name-based ``low_effort`` gating WITHOUT loading any tokenizer (no
|
||||
network). This pins the wiring the parity matrix can't reach — in particular
|
||||
the FP8 Ultra entry, which no test loads a tokenizer for — so it can't
|
||||
silently rot.
|
||||
|
||||
The two variants:
|
||||
|
||||
* ``nemotron-3`` — Nano / Super, shared template. Config exposes ``low_effort``
|
||||
(honoured on Super, a no-op on Nano).
|
||||
* ``nemotron-3-ultra`` — Ultra, distinct ``</think>`` glue. Config exposes
|
||||
``medium_effort``.
|
||||
|
||||
Both route to the one ``Nemotron3Renderer`` class, which selects the variant
|
||||
from ``config.name``.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
from renderers.configs import Nemotron3RendererConfig
|
||||
from renderers.nemotron3 import _ULTRA_DEFAULTS, _default_ultra
|
||||
from renderers.base import MODEL_RENDERER_MAP, RENDERER_REGISTRY, _populate_registry
|
||||
from renderers.configs import (
|
||||
Nemotron3RendererConfig,
|
||||
Nemotron3UltraRendererConfig,
|
||||
_config_class_for,
|
||||
)
|
||||
from renderers.nemotron3 import Nemotron3Renderer, Nemotron3UltraRenderer, _is_super
|
||||
|
||||
_ULTRA_REPOS = [
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
|
||||
"nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-FP8",
|
||||
]
|
||||
_NON_ULTRA_REPOS = [
|
||||
_NANO_SUPER_REPOS = [
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16",
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
|
||||
]
|
||||
@@ -26,34 +41,64 @@ def _fake_tok(name):
|
||||
return SimpleNamespace(name_or_path=name)
|
||||
|
||||
|
||||
def test_ultra_and_non_ultra_models_map_to_nemotron3():
|
||||
for repo in _ULTRA_REPOS + _NON_ULTRA_REPOS:
|
||||
def test_models_map_to_their_variant():
|
||||
for repo in _ULTRA_REPOS:
|
||||
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3-ultra", repo
|
||||
for repo in _NANO_SUPER_REPOS:
|
||||
assert MODEL_RENDERER_MAP.get(repo) == "nemotron-3", repo
|
||||
|
||||
|
||||
def test_default_ultra_resolves_by_name():
|
||||
# Ultra checkpoints (incl. the gated FP8 repo) resolve True.
|
||||
for repo in _ULTRA_REPOS:
|
||||
assert _ULTRA_DEFAULTS[repo] is True
|
||||
assert _default_ultra(_fake_tok(repo)) is True
|
||||
# Nano / Super resolve False (the shared Nano/Super template).
|
||||
for repo in _NON_ULTRA_REPOS:
|
||||
assert _default_ultra(_fake_tok(repo)) is False
|
||||
# Unknown / fine-tuned / local-path checkpoints fall back to False;
|
||||
# those must pass an explicit ultra= if they need the Ultra template.
|
||||
assert _default_ultra(_fake_tok("acme/my-nemotron-ultra-ft")) is False
|
||||
assert _default_ultra(_fake_tok("/home/user/local-ckpt")) is False
|
||||
assert _default_ultra(SimpleNamespace()) is False # no name_or_path attr
|
||||
def test_each_discriminator_maps_to_its_config_and_renderer_class():
|
||||
# Config discriminator → config class.
|
||||
assert _config_class_for("nemotron-3") is Nemotron3RendererConfig
|
||||
assert _config_class_for("nemotron-3-ultra") is Nemotron3UltraRendererConfig
|
||||
# Registry → renderer class (Ultra is a sibling subclass, matching the
|
||||
# GLM-5/5.1 and Qwen3.5/3.6 house style — not one class under two names).
|
||||
_populate_registry()
|
||||
assert RENDERER_REGISTRY["nemotron-3"] is Nemotron3Renderer
|
||||
assert RENDERER_REGISTRY["nemotron-3-ultra"] is Nemotron3UltraRenderer
|
||||
assert issubclass(Nemotron3UltraRenderer, Nemotron3Renderer)
|
||||
|
||||
|
||||
def test_ultra_is_not_a_template_kwarg():
|
||||
fields = Nemotron3RendererConfig.template_field_names()
|
||||
assert "ultra" not in fields
|
||||
assert fields == frozenset({"enable_thinking", "truncate_history_thinking"})
|
||||
assert "ultra" in Nemotron3RendererConfig._internal_fields
|
||||
def test_variant_is_encoded_by_the_class():
|
||||
# The ``</think>`` glue is selected by the class hook, not config.name —
|
||||
# so the right renderer class must be constructed (create_renderer routes
|
||||
# config.name → class). Default config also follows the class.
|
||||
assert Nemotron3Renderer._ultra is False
|
||||
assert Nemotron3UltraRenderer._ultra is True
|
||||
assert Nemotron3Renderer._config_cls is Nemotron3RendererConfig
|
||||
assert Nemotron3UltraRenderer._config_cls is Nemotron3UltraRendererConfig
|
||||
|
||||
|
||||
def test_ultra_config_default_is_none_and_overridable():
|
||||
assert Nemotron3RendererConfig().ultra is None # None => auto-detect by name
|
||||
assert Nemotron3RendererConfig(ultra=True).ultra is True
|
||||
assert Nemotron3RendererConfig(ultra=False).ultra is False
|
||||
def test_template_fields_per_variant():
|
||||
# ``low_effort`` lives only on the Nano/Super config; ``medium_effort``
|
||||
# only on Ultra. Both ARE chat-template kwargs (unlike the removed ``ultra``
|
||||
# selector), so they appear in the template-field surface.
|
||||
assert Nemotron3RendererConfig.template_field_names() == frozenset(
|
||||
{"enable_thinking", "truncate_history_thinking", "low_effort"}
|
||||
)
|
||||
assert Nemotron3UltraRendererConfig.template_field_names() == frozenset(
|
||||
{"enable_thinking", "truncate_history_thinking", "medium_effort"}
|
||||
)
|
||||
|
||||
|
||||
def test_configs_reject_the_other_variants_effort_kwarg():
|
||||
# Discriminated-union honesty: a bad combination fails at config-load.
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
Nemotron3RendererConfig(medium_effort=True) # type: ignore[call-arg]
|
||||
with pytest.raises(ValidationError):
|
||||
Nemotron3UltraRendererConfig(low_effort=True) # type: ignore[call-arg]
|
||||
# And the removed ``ultra`` selector is gone entirely.
|
||||
with pytest.raises(ValidationError):
|
||||
Nemotron3RendererConfig(ultra=True) # type: ignore[call-arg]
|
||||
|
||||
|
||||
def test_is_super_name_detection():
|
||||
assert _is_super(_fake_tok("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"))
|
||||
assert not _is_super(_fake_tok("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"))
|
||||
# Unknown / local-path checkpoints default to False → low_effort no-op.
|
||||
assert not _is_super(_fake_tok("/home/user/local-ckpt"))
|
||||
assert not _is_super(SimpleNamespace()) # no name_or_path attr
|
||||
|
||||
+48
-424
@@ -1,62 +1,20 @@
|
||||
"""Smoke coverage for the ``preserve_*_thinking`` override flags.
|
||||
"""Targeted coverage for the ``thinking_retention`` bridge-policy flag.
|
||||
|
||||
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:
|
||||
|
||||
1. Default render (no flags) is byte-identical to the existing
|
||||
``apply_chat_template`` parity baseline — covered exhaustively elsewhere.
|
||||
2. Setting either flag never *removes* tokens compared to the default and,
|
||||
for renderers whose template would drop past-asst thinking, actually
|
||||
adds tokens for a conversation containing past-asst ``reasoning_content``.
|
||||
|
||||
Renderers whose template either always preserves thinking (DeepSeek-V3) or
|
||||
never references ``reasoning_content`` for past-asst (Kimi-K2, Qwen3-VL)
|
||||
are no-ops by design — they're listed below and the test asserts the
|
||||
default==override equality instead of strict growth.
|
||||
Generic ``thinking_retention`` controls whether a renderer may append via
|
||||
``bridge_to_next_turn`` or should fall back to a full re-render. It is not a
|
||||
chat-template kwarg, so the only full-render contract here is that explicit
|
||||
generic values do not change render output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import MODEL_RENDERER_MAP, should_preserve_past_thinking
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
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."""
|
||||
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
|
||||
# place to re-emit it. For these, override flags MUST be no-ops.
|
||||
NO_OP_MODELS = {
|
||||
"deepseek-ai/DeepSeek-V3",
|
||||
"deepseek-ai/DeepSeek-V3-Base",
|
||||
"moonshotai/Kimi-K2-Instruct",
|
||||
"Qwen/Qwen3-VL-4B-Instruct",
|
||||
"Qwen/Qwen3-VL-8B-Instruct",
|
||||
"Qwen/Qwen3-VL-30B-A3B-Instruct",
|
||||
"poolside/Laguna-XS.2",
|
||||
# Llama-3 has no reasoning channel at all — preserve flags can't add
|
||||
# or drop anything, so they're pure no-ops.
|
||||
"unsloth/Llama-3.2-1B-Instruct",
|
||||
}
|
||||
|
||||
|
||||
CONVERSATION = [
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
@@ -77,397 +35,63 @@ CONVERSATION = [
|
||||
]
|
||||
|
||||
|
||||
def test_should_preserve_past_thinking_classification():
|
||||
# CURRENT-block-only behaviour. between_tool_calls preserves thinking
|
||||
# ONLY for asst messages that sit AFTER the last user turn AND are in
|
||||
# a segment that contains a tool. Anything before the last user turn
|
||||
# falls back to template default (typically dropped).
|
||||
|
||||
# Live tool cycle: U-A_tc-T-A_final, no trailing user. The whole
|
||||
# post-user segment contains a tool, so both A's are preserved.
|
||||
live_cycle = [
|
||||
{"role": "user", "content": "q"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "r1",
|
||||
"tool_calls": [{"function": {"name": "f", "arguments": {}}}],
|
||||
},
|
||||
{"role": "tool", "name": "f", "content": "data"},
|
||||
{"role": "assistant", "reasoning_content": "r2", "content": "answer"},
|
||||
]
|
||||
assert should_preserve_past_thinking(
|
||||
live_cycle,
|
||||
1,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
assert should_preserve_past_thinking(
|
||||
live_cycle,
|
||||
3,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
|
||||
# Same shape with a NEW user appended → now the prior tool block is
|
||||
# "older" and between_tool_calls must drop its thinking (template
|
||||
# default). Only preserve_all_thinking would keep them.
|
||||
closed_cycle = live_cycle + [{"role": "user", "content": "next"}]
|
||||
assert not should_preserve_past_thinking(
|
||||
closed_cycle,
|
||||
1,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
assert not should_preserve_past_thinking(
|
||||
closed_cycle,
|
||||
3,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
# preserve_all_thinking still keeps them.
|
||||
assert should_preserve_past_thinking(
|
||||
closed_cycle,
|
||||
1,
|
||||
preserve_all_thinking=True,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
)
|
||||
assert should_preserve_past_thinking(
|
||||
closed_cycle,
|
||||
3,
|
||||
preserve_all_thinking=True,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
)
|
||||
|
||||
# Current segment without a tool → not a tool cycle → not preserved.
|
||||
no_tool_yet = [
|
||||
{"role": "user", "content": "q"},
|
||||
{"role": "assistant", "reasoning_content": "r", "content": "a"},
|
||||
]
|
||||
assert not should_preserve_past_thinking(
|
||||
no_tool_yet,
|
||||
1,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
)
|
||||
|
||||
# Both flags False → always False.
|
||||
assert not should_preserve_past_thinking(
|
||||
live_cycle,
|
||||
1,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
)
|
||||
def _make(tokenizer, renderer_name, **flags):
|
||||
"""Build a fresh renderer with the given construction-time flags."""
|
||||
if renderer_name == "auto":
|
||||
renderer_name = MODEL_RENDERER_MAP.get(
|
||||
getattr(tokenizer, "name_or_path", ""), "default"
|
||||
)
|
||||
config = _config_class_for(renderer_name)(**flags)
|
||||
return create_renderer(tokenizer, config)
|
||||
|
||||
|
||||
def test_preserve_flags_default_unchanged(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
# A renderer constructed with both flags explicitly ``False`` must
|
||||
# produce byte-identical output to one constructed with the defaults.
|
||||
bare = renderer.render_ids(CONVERSATION)
|
||||
explicit_off = _make(
|
||||
tokenizer,
|
||||
renderer_name,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
).render_ids(CONVERSATION)
|
||||
assert bare == explicit_off, (
|
||||
f"{model_name}: explicit flags=False must equal bare default render"
|
||||
)
|
||||
|
||||
|
||||
def test_preserve_all_thinking_grows_or_no_op(
|
||||
def test_generic_thinking_retention_does_not_change_full_render(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
"""Generic retention is bridge policy only, not a render override."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
pytest.skip("DefaultRenderer raises on explicit retention — covered separately")
|
||||
|
||||
default = renderer.render_ids(CONVERSATION)
|
||||
preserved = _make(tokenizer, renderer_name, preserve_all_thinking=True).render_ids(
|
||||
CONVERSATION
|
||||
)
|
||||
|
||||
if model_name in NO_OP_MODELS:
|
||||
assert preserved == default, (
|
||||
f"{model_name} is a no-op renderer; preserve_all_thinking must "
|
||||
f"not change output (got {len(default)} → {len(preserved)})"
|
||||
)
|
||||
else:
|
||||
assert len(preserved) > len(default), (
|
||||
f"{model_name}: preserve_all_thinking should add tokens for a "
|
||||
f"conversation with past-asst reasoning_content "
|
||||
f"(default={len(default)}, preserved={len(preserved)})"
|
||||
for retention in ("tool_cycle", "all"):
|
||||
explicit = _make(
|
||||
tokenizer,
|
||||
renderer_name,
|
||||
thinking_retention=retention,
|
||||
).render_ids(CONVERSATION)
|
||||
assert explicit == default, (
|
||||
f"{model_name}: thinking_retention={retention!r} changed full render"
|
||||
)
|
||||
|
||||
|
||||
def test_preserve_between_tool_calls_strict_subset(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
def test_no_thinking_knob_implies_all_bridge_policy(
|
||||
model_name, renderer_name, tokenizer
|
||||
):
|
||||
"""``preserve_thinking_between_tool_calls`` is strictly weaker than
|
||||
``preserve_all_thinking``: token count satisfies default <= between <= all."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
default = renderer.render_ids(CONVERSATION)
|
||||
between = _make(
|
||||
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
|
||||
).render_ids(CONVERSATION)
|
||||
all_ = _make(tokenizer, renderer_name, preserve_all_thinking=True).render_ids(
|
||||
CONVERSATION
|
||||
)
|
||||
assert len(default) <= len(between) <= len(all_), (
|
||||
f"{model_name}: expected default <= between <= all, "
|
||||
f"got {len(default)} <= {len(between)} <= {len(all_)}"
|
||||
)
|
||||
|
||||
|
||||
LIVE_TOOL_CYCLE = [
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Let me call the tool.",
|
||||
"content": "Calling.",
|
||||
"tool_calls": [
|
||||
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "name": "get_weather", "content": "Sunny, 22C"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Tool returned weather.",
|
||||
"content": "Sunny.",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_preserve_btc_on_live_cycle_matches_all(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
"""In a live tool cycle (no trailing user), every past-asst sits in
|
||||
the current tool-bearing segment. ``preserve_thinking_between_tool_calls``
|
||||
should preserve all of their thinking — same set of asst messages as
|
||||
``preserve_all_thinking``, so the resulting token sequences must be
|
||||
identical (independent of which template-default condition each
|
||||
renderer uses internally)."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
btc = _make(
|
||||
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
|
||||
).render_ids(LIVE_TOOL_CYCLE)
|
||||
all_ = _make(tokenizer, renderer_name, preserve_all_thinking=True).render_ids(
|
||||
LIVE_TOOL_CYCLE
|
||||
)
|
||||
assert btc == all_, (
|
||||
f"{model_name}: in a live tool cycle btc must match preserve_all "
|
||||
f"(got len(btc)={len(btc)}, len(all)={len(all_)})"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# End-to-end visibility matrix
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Conversation shape: S-U-A-T-A-U-A-T-A. Each assistant carries a unique
|
||||
# sentinel string in ``reasoning_content`` so we can grep the decoded
|
||||
# output to see whose thinking was kept.
|
||||
TWO_BLOCK_TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "lookup",
|
||||
"description": "look up a value",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"key": {"type": "string"}},
|
||||
"required": ["key"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
TWO_BLOCK_CONV = [
|
||||
{"role": "system", "content": "be brief"},
|
||||
{"role": "user", "content": "first"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "REASON-A2",
|
||||
"content": "calling.",
|
||||
"tool_calls": [{"function": {"name": "lookup", "arguments": {"key": "a"}}}],
|
||||
},
|
||||
{"role": "tool", "name": "lookup", "content": "result-a"},
|
||||
{"role": "assistant", "reasoning_content": "REASON-A4", "content": "answer-1"},
|
||||
{"role": "user", "content": "second"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "REASON-A6",
|
||||
"content": "calling.",
|
||||
"tool_calls": [{"function": {"name": "lookup", "arguments": {"key": "b"}}}],
|
||||
},
|
||||
{"role": "tool", "name": "lookup", "content": "result-b"},
|
||||
{"role": "assistant", "reasoning_content": "REASON-A8", "content": "answer-2"},
|
||||
]
|
||||
|
||||
ALL_SENTINELS = ("REASON-A2", "REASON-A4", "REASON-A6", "REASON-A8")
|
||||
CURRENT_BLOCK_SENTINELS = ("REASON-A6", "REASON-A8")
|
||||
OLDER_BLOCK_SENTINELS = ("REASON-A2", "REASON-A4")
|
||||
|
||||
# Renderers whose template renders ``reasoning_content`` for past-asst
|
||||
# under no condition. Flags accepted as no-ops; sentinels never appear.
|
||||
NEVER_PRESERVES_MODELS = {
|
||||
"moonshotai/Kimi-K2-Instruct",
|
||||
"Qwen/Qwen3-VL-4B-Instruct",
|
||||
"Qwen/Qwen3-VL-8B-Instruct",
|
||||
"Qwen/Qwen3-VL-30B-A3B-Instruct",
|
||||
# Llama-3 ships no <think> rendering path, so reasoning_content never
|
||||
# surfaces in the output regardless of the preserve flags.
|
||||
"unsloth/Llama-3.2-1B-Instruct",
|
||||
}
|
||||
|
||||
|
||||
def test_preserve_all_thinking_emits_every_asst_reasoning(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
"""``preserve_all_thinking=True`` must surface every past-asst's
|
||||
``reasoning_content`` in the decoded output — for renderers that
|
||||
have any pathway to render reasoning at all."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
|
||||
ids = _make(tokenizer, renderer_name, preserve_all_thinking=True).render_ids(
|
||||
TWO_BLOCK_CONV, tools=TWO_BLOCK_TOOLS
|
||||
)
|
||||
text = tokenizer.decode(ids)
|
||||
|
||||
if model_name in NEVER_PRESERVES_MODELS:
|
||||
for sentinel in ALL_SENTINELS:
|
||||
assert sentinel not in text, (
|
||||
f"{model_name}: never-preserves renderer leaked {sentinel} "
|
||||
f"under preserve_all_thinking"
|
||||
)
|
||||
else:
|
||||
for sentinel in ALL_SENTINELS:
|
||||
assert sentinel in text, (
|
||||
f"{model_name}: preserve_all_thinking did not emit {sentinel} "
|
||||
f"in decoded output"
|
||||
)
|
||||
|
||||
|
||||
def test_preserve_btc_emits_current_block_reasoning(
|
||||
model_name, tokenizer, renderer_name, renderer
|
||||
):
|
||||
"""``preserve_thinking_between_tool_calls=True`` must surface the
|
||||
current (post-last-user) tool block's reasoning. Older blocks fall
|
||||
back to template default, which varies per renderer — no universal
|
||||
assertion there."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer raises on these flags — covered separately")
|
||||
|
||||
ids = _make(
|
||||
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
|
||||
).render_ids(TWO_BLOCK_CONV, tools=TWO_BLOCK_TOOLS)
|
||||
text = tokenizer.decode(ids)
|
||||
|
||||
if model_name in NEVER_PRESERVES_MODELS:
|
||||
for sentinel in ALL_SENTINELS:
|
||||
assert sentinel not in text, (
|
||||
f"{model_name}: never-preserves renderer leaked {sentinel} "
|
||||
f"under preserve_thinking_between_tool_calls"
|
||||
)
|
||||
else:
|
||||
for sentinel in CURRENT_BLOCK_SENTINELS:
|
||||
assert sentinel in text, (
|
||||
f"{model_name}: btc did not emit current-block {sentinel} "
|
||||
f"in decoded output"
|
||||
)
|
||||
|
||||
|
||||
def test_default_renderer_raises_on_flags():
|
||||
"""``DefaultRenderer`` falls back to apply_chat_template with no
|
||||
selective re-emit pathway, so constructing one with either flag set
|
||||
must raise — fail fast, before any render is attempted."""
|
||||
from renderers import DefaultRendererConfig
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen2.5-0.5B-Instruct")
|
||||
# No flags → constructs cleanly.
|
||||
create_renderer(tok, DefaultRendererConfig())
|
||||
# Either flag set → raises at construction.
|
||||
with pytest.raises(NotImplementedError):
|
||||
create_renderer(tok, DefaultRendererConfig(preserve_all_thinking=True))
|
||||
with pytest.raises(NotImplementedError):
|
||||
create_renderer(
|
||||
tok,
|
||||
DefaultRendererConfig(preserve_thinking_between_tool_calls=True),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Construction-time configuration is discoverable via instance attributes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_create_renderer_records_flag_state(model_name, renderer_name, tokenizer):
|
||||
"""Each renderer exposes the bound flag state via ``self.config`` —
|
||||
useful for downstream code (pool cache keys, logging, test
|
||||
assertions) that needs to confirm what was constructed."""
|
||||
"""No-thinking generation config means there is no thinking to evict."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
bare = _make(tokenizer, renderer_name)
|
||||
assert bare.config.preserve_all_thinking is False
|
||||
assert bare.config.preserve_thinking_between_tool_calls is False
|
||||
if isinstance(bare, DefaultRenderer):
|
||||
pytest.skip("DefaultRenderer has no typed no-thinking bridge policy")
|
||||
|
||||
if not isinstance(bare, DefaultRenderer):
|
||||
# DefaultRenderer raises at construction with either flag set —
|
||||
# covered by ``test_default_renderer_raises_on_flags``.
|
||||
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
|
||||
cfg_cls = _config_class_for(renderer_name)
|
||||
template_fields = cfg_cls.template_field_names()
|
||||
if "enable_thinking" in template_fields:
|
||||
no_thinking = {"enable_thinking": False}
|
||||
elif "thinking" in template_fields:
|
||||
no_thinking = {"thinking": False}
|
||||
else:
|
||||
pytest.skip(f"{model_name}: no no-thinking generation knob")
|
||||
|
||||
btc_on = _make(
|
||||
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
|
||||
)
|
||||
assert btc_on.config.preserve_all_thinking is False
|
||||
assert btc_on.config.preserve_thinking_between_tool_calls is True
|
||||
all_on = _make(tokenizer, renderer_name, **no_thinking)
|
||||
assert all_on.effective_thinking_retention == "all"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Regression: legacy chat-template-kwarg pass-throughs are gone
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
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")
|
||||
# Both values must be accepted without raising.
|
||||
GLM5Renderer(tok, GLM5RendererConfig(clear_thinking=True))
|
||||
GLM5Renderer(tok, GLM5RendererConfig(clear_thinking=False))
|
||||
|
||||
|
||||
def test_qwen36_config_rejects_unknown_field():
|
||||
"""``preserve_thinking`` on Qwen3.6 was a chat-template-kwarg
|
||||
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
|
||||
|
||||
with pytest.raises(ValidationError, match="preserve_thinking"):
|
||||
Qwen36RendererConfig(preserve_thinking=True) # type: ignore[call-arg]
|
||||
conservative = _make(
|
||||
tokenizer,
|
||||
renderer_name,
|
||||
**no_thinking,
|
||||
thinking_retention="tool_cycle",
|
||||
)
|
||||
assert conservative.effective_thinking_retention == "tool_cycle"
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
from functools import lru_cache
|
||||
|
||||
import pytest
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
MODELS = [
|
||||
"PrimeIntellect/Qwen3-0.6B",
|
||||
"PrimeIntellect/Qwen3-1.7B",
|
||||
]
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {
|
||||
"type": "string",
|
||||
"description": "City name",
|
||||
"default": "Paris",
|
||||
"examples": [{"country": "FR", "city": "Paris"}],
|
||||
},
|
||||
"days": {"type": "integer", "minimum": 1},
|
||||
},
|
||||
"required": ["city"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
"strict": True,
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
CASES = [
|
||||
pytest.param(
|
||||
[{"role": "user", "content": "Hello"}],
|
||||
None,
|
||||
True,
|
||||
id="generation-prompt",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "Reverse abc"},
|
||||
{"role": "assistant", "content": "cba"},
|
||||
],
|
||||
None,
|
||||
False,
|
||||
id="plain-assistant",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": " simple arithmetic ",
|
||||
"content": " 4 ",
|
||||
},
|
||||
],
|
||||
None,
|
||||
False,
|
||||
id="reasoning",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{"role": "assistant", "reasoning_content": "", "content": "4"},
|
||||
],
|
||||
None,
|
||||
False,
|
||||
id="empty-reasoning",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "A"},
|
||||
{"role": "assistant", "content": "<think>raw</think>\nB"},
|
||||
{"role": "user", "content": "C"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "kept",
|
||||
"content": "D",
|
||||
},
|
||||
],
|
||||
None,
|
||||
False,
|
||||
id="multi-turn-reasoning",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "system", "content": "Use tools."},
|
||||
{"role": "user", "content": "Weather?"},
|
||||
],
|
||||
TOOLS,
|
||||
True,
|
||||
id="tools-with-system",
|
||||
),
|
||||
pytest.param(
|
||||
[{"role": "user", "content": "Weather?"}],
|
||||
TOOLS,
|
||||
True,
|
||||
id="tools-with-default-system",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "Weather?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "not rendered in the tool-call branch",
|
||||
"content": " Checking. ",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {
|
||||
"city": "Paris",
|
||||
"days": 2,
|
||||
"options": {"units": "metric", "locale": "fr"},
|
||||
},
|
||||
}
|
||||
},
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "London", "days": 3},
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{"role": "tool", "content": '{"temp": 15}'},
|
||||
{"role": "assistant", "content": "Paris is warmer."},
|
||||
],
|
||||
TOOLS,
|
||||
False,
|
||||
id="tool-cycle",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _load(model: str):
|
||||
tokenizer = load_tokenizer(model)
|
||||
return tokenizer, create_renderer(tokenizer)
|
||||
|
||||
|
||||
def _expected(tokenizer, messages, tools, add_generation_prompt):
|
||||
result = tokenizer.apply_chat_template(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
)
|
||||
return list(result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
@pytest.mark.parametrize("messages,tools,add_generation_prompt", CASES)
|
||||
def test_prime_qwen3_matches_hf_template(
|
||||
model,
|
||||
messages,
|
||||
tools,
|
||||
add_generation_prompt,
|
||||
):
|
||||
tokenizer, renderer = _load(model)
|
||||
|
||||
expected = _expected(tokenizer, messages, tools, add_generation_prompt)
|
||||
actual = renderer.render_ids(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
)
|
||||
|
||||
assert actual == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", MODELS)
|
||||
def test_prime_qwen3_populates_assistant_masks(model):
|
||||
_, renderer = _load(model)
|
||||
prompt = [{"role": "user", "content": "Reverse abc"}]
|
||||
messages = [*prompt, {"role": "assistant", "content": "cba"}]
|
||||
|
||||
generation_prompt = renderer.render_ids(prompt, add_generation_prompt=True)
|
||||
rendered = renderer.render(messages)
|
||||
|
||||
assert rendered.token_ids[: len(generation_prompt)] == generation_prompt
|
||||
assert not any(rendered.sampled_mask[: len(generation_prompt)])
|
||||
assert any(rendered.sampled_mask[len(generation_prompt) :])
|
||||
assert rendered.sampled_mask[-1] is False
|
||||
assert (
|
||||
len(rendered.sampled_mask)
|
||||
== len(rendered.is_content)
|
||||
== len(rendered.token_ids)
|
||||
)
|
||||
@@ -11,11 +11,15 @@ from renderers import (
|
||||
AutoRendererConfig,
|
||||
DefaultRendererConfig,
|
||||
GLM5RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
Nemotron3RendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
Qwen36RendererConfig,
|
||||
RendererConfig,
|
||||
base,
|
||||
create_renderer,
|
||||
create_renderer_pool,
|
||||
)
|
||||
|
||||
|
||||
@@ -85,7 +89,7 @@ def test_create_renderer_forwards_typed_config_to_renderer(monkeypatch):
|
||||
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."""
|
||||
carrying the shared ``thinking_retention`` field over from the auto config."""
|
||||
|
||||
class _FakeQwen35:
|
||||
def __init__(self, tokenizer, config):
|
||||
@@ -97,16 +101,109 @@ def test_create_renderer_auto_resolves_via_model_map(monkeypatch):
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/qwen35"),
|
||||
AutoRendererConfig(preserve_all_thinking=True),
|
||||
AutoRendererConfig(thinking_retention="all"),
|
||||
)
|
||||
|
||||
assert isinstance(renderer.config, Qwen35RendererConfig)
|
||||
assert renderer.config.preserve_all_thinking is True
|
||||
assert renderer.config.thinking_retention == "all"
|
||||
# Template-level kwargs stay at their per-renderer defaults — auto
|
||||
# carries only the preserve_* flags.
|
||||
# carries only the thinking_retention flag.
|
||||
assert renderer.config.add_vision_id is False
|
||||
|
||||
|
||||
def test_create_renderer_auto_applies_chat_template_kwargs(monkeypatch):
|
||||
"""Auto resolution happens before chat-template kwargs are validated."""
|
||||
|
||||
class _FakeQwen3:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.tokenizer = tokenizer
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeQwen3)
|
||||
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen3", "qwen3")
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/qwen3"),
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
assert isinstance(renderer.config, Qwen3RendererConfig)
|
||||
assert renderer.config.enable_thinking is False
|
||||
|
||||
|
||||
def test_create_renderer_pool_forwards_chat_template_kwargs(monkeypatch):
|
||||
"""Pool construction uses the same renderer-owned config resolution."""
|
||||
|
||||
class _FakeQwen3:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeQwen3)
|
||||
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen3", "qwen3")
|
||||
monkeypatch.setattr(
|
||||
base,
|
||||
"load_tokenizer",
|
||||
lambda name: SimpleNamespace(name_or_path=name),
|
||||
)
|
||||
|
||||
pool = create_renderer_pool(
|
||||
"fake/qwen3",
|
||||
size=1,
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
assert isinstance(pool._sole.config, Qwen3RendererConfig)
|
||||
assert pool._sole.config.enable_thinking is False
|
||||
|
||||
|
||||
def test_auto_unknown_model_rejects_chat_template_kwargs():
|
||||
tok = SimpleNamespace(name_or_path="unknown/text-model")
|
||||
|
||||
with pytest.raises(ValueError, match="chat_template_kwargs"):
|
||||
create_renderer(tok, chat_template_kwargs={"enable_thinking": False})
|
||||
|
||||
|
||||
def test_chat_template_kwargs_validate_against_resolved_config(monkeypatch):
|
||||
class _FakeQwen3:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeQwen3)
|
||||
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen3", "qwen3")
|
||||
|
||||
with pytest.raises(ValidationError, match="enable_thinkng"):
|
||||
create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/qwen3"),
|
||||
chat_template_kwargs={"enable_thinkng": False},
|
||||
)
|
||||
|
||||
|
||||
def test_chat_template_kwargs_conflict_with_explicit_config():
|
||||
with pytest.raises(ValidationError, match="thinking_retention"):
|
||||
create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/glm"),
|
||||
GLM5RendererConfig(thinking_retention="tool_cycle"),
|
||||
chat_template_kwargs={"clear_thinking": False},
|
||||
)
|
||||
|
||||
|
||||
def test_chat_template_kwargs_preserve_default_field_unset_state(monkeypatch):
|
||||
class _FakeGlm:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "glm-5", _FakeGlm)
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/glm"),
|
||||
GLM5RendererConfig(thinking_retention="all"),
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
assert renderer.config.thinking_retention == "all"
|
||||
assert renderer.config.enable_thinking is False
|
||||
|
||||
|
||||
def test_create_renderer_default_argument_is_auto():
|
||||
"""Passing no config is equivalent to passing ``AutoRendererConfig()``
|
||||
— short form for the common case."""
|
||||
@@ -114,3 +211,114 @@ def test_create_renderer_default_argument_is_auto():
|
||||
renderer = create_renderer(tok)
|
||||
# Falls through to DefaultRenderer when no match and no vision config.
|
||||
assert renderer.__class__.__name__ == "DefaultRenderer"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_cls,kwargs",
|
||||
[
|
||||
(GLM5RendererConfig, {"thinking_retention": "template"}),
|
||||
(
|
||||
GLM5RendererConfig,
|
||||
{"clear_thinking": False, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(GLM5RendererConfig, {"clear_thinking": True, "thinking_retention": "all"}),
|
||||
(
|
||||
Nemotron3RendererConfig,
|
||||
{
|
||||
"truncate_history_thinking": False,
|
||||
"thinking_retention": "tool_cycle",
|
||||
},
|
||||
),
|
||||
(
|
||||
Nemotron3RendererConfig,
|
||||
{"truncate_history_thinking": True, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
Qwen36RendererConfig,
|
||||
{"preserve_thinking": True, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(
|
||||
Qwen36RendererConfig,
|
||||
{"preserve_thinking": False, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
GptOssRendererConfig,
|
||||
{"auto_drop_analysis": False, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(
|
||||
GptOssRendererConfig,
|
||||
{"auto_drop_analysis": True, "thinking_retention": "all"},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_thinking_retention_conflict_raises(config_cls, kwargs):
|
||||
"""Explicit template and generic retention knobs must agree."""
|
||||
with pytest.raises(ValidationError, match="thinking_retention"):
|
||||
config_cls(**kwargs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_cls,kwargs",
|
||||
[
|
||||
(GLM5RendererConfig, {"clear_thinking": False, "thinking_retention": "all"}),
|
||||
(
|
||||
GLM5RendererConfig,
|
||||
{"clear_thinking": True, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(GLM5RendererConfig, {"clear_thinking": False}),
|
||||
(GLM5RendererConfig, {"thinking_retention": "tool_cycle"}),
|
||||
(
|
||||
Nemotron3RendererConfig,
|
||||
{"truncate_history_thinking": False, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
Nemotron3RendererConfig,
|
||||
{
|
||||
"truncate_history_thinking": True,
|
||||
"thinking_retention": "tool_cycle",
|
||||
},
|
||||
),
|
||||
(
|
||||
Qwen36RendererConfig,
|
||||
{"preserve_thinking": True, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
Qwen36RendererConfig,
|
||||
{"preserve_thinking": False, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
(
|
||||
GptOssRendererConfig,
|
||||
{"auto_drop_analysis": False, "thinking_retention": "all"},
|
||||
),
|
||||
(
|
||||
GptOssRendererConfig,
|
||||
{"auto_drop_analysis": True, "thinking_retention": "tool_cycle"},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_thinking_retention_consistent_pairs_are_accepted(config_cls, kwargs):
|
||||
config_cls(**kwargs)
|
||||
|
||||
|
||||
def test_default_renderer_rejects_explicit_retention():
|
||||
"""Opaque apply_chat_template fallback cannot implement bridge policy."""
|
||||
tok = SimpleNamespace(name_or_path="")
|
||||
create_renderer(tok, DefaultRendererConfig())
|
||||
|
||||
for retention in ("tool_cycle", "all"):
|
||||
with pytest.raises(ValueError, match="DefaultRenderer"):
|
||||
create_renderer(tok, DefaultRendererConfig(thinking_retention=retention))
|
||||
|
||||
|
||||
def test_default_renderer_config_rejects_legacy_preserve_flags():
|
||||
"""``DefaultRendererConfig`` is ``extra="allow"``, so the removed
|
||||
``preserve_*`` bools would otherwise slip into ``model_extra`` and be
|
||||
forwarded to ``apply_chat_template`` silently. A validator rejects them
|
||||
with a migration message; genuine Jinja kwargs still pass through."""
|
||||
with pytest.raises(ValidationError, match="thinking_retention"):
|
||||
DefaultRendererConfig(preserve_all_thinking=True)
|
||||
with pytest.raises(ValidationError, match="thinking_retention"):
|
||||
DefaultRendererConfig(preserve_thinking_between_tool_calls=True)
|
||||
|
||||
cfg = DefaultRendererConfig(some_jinja_kwarg=True)
|
||||
assert cfg.model_extra["some_jinja_kwarg"] is True
|
||||
|
||||
@@ -55,11 +55,17 @@ _RENDERER_MODELS = [
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("deepseek-ai/DeepSeek-V3", "auto"),
|
||||
("deepseek-ai/DeepSeek-R1", "auto"),
|
||||
# Nano + Super share the ``nemotron-3`` config (incl. ``low_effort``, which
|
||||
# fires only on Super); both are exercised so the kwarg is checked where it
|
||||
# no-ops (Nano) AND where it appends (Super).
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
# Ultra: auto-resolves to the Ultra template variant (ultra=True) via the
|
||||
# model name; parity asserted against the Ultra apply_chat_template.
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
|
||||
# Ultra: auto-resolves to the ``nemotron-3-ultra`` config via the model
|
||||
# name; parity asserted against the Ultra apply_chat_template (``medium_effort``).
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("poolside/Laguna-XS-2.1", "auto"),
|
||||
("tencent/Hy3", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
]
|
||||
|
||||
@@ -76,7 +82,22 @@ _KWARG_VALUES: dict[str, list[Any]] = {
|
||||
# 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"],
|
||||
# gpt-oss accepts low/medium/high; Hy3 accepts no_think/low/high. The
|
||||
# union is listed here and the matrix builder drops values a given
|
||||
# renderer's typed config rejects (see ``_value_valid_for``).
|
||||
"reasoning_effort": ["no_think", "low", "medium", "high"],
|
||||
# Hy3 — keep <think>{reasoning}</think> on historical assistant turns
|
||||
# (True) vs collapse past-cycle reasoning to <think></think> (False).
|
||||
"preserved_thinking": [True, False],
|
||||
# Hy3 — SFT-target rendering (keep all thinking + close the final
|
||||
# assistant with <|hy_eos|>).
|
||||
"is_training": [True, False],
|
||||
# Hy3 — raw passthrough of a trailing non-tool assistant (no <think>
|
||||
# wrap, no eos) for prefill / continuation.
|
||||
"raw_last_assistant": [True, False],
|
||||
# Hy3 — sole active value forces reasoning_effort="high" +
|
||||
# add_generation_prompt=False.
|
||||
"fallback_strategy": ["reasoning_toolcall_retry"],
|
||||
# GLM-5 / GLM-5.1 — ``clear_thinking=False`` preserves the
|
||||
# ``<think>{reasoning}</think>`` wrap on historical assistants too
|
||||
# (default True collapses past-cycle reasoning to ``</think>``).
|
||||
@@ -85,6 +106,12 @@ _KWARG_VALUES: dict[str, list[Any]] = {
|
||||
# ``truncate_history_thinking=False`` keeps reasoning on historical
|
||||
# assistants instead of collapsing to ``<think></think>``.
|
||||
"truncate_history_thinking": [True, False],
|
||||
# Nemotron-3 reasoning-effort hints appended to the last user message.
|
||||
# ``low_effort`` is a Super (``nemotron-3``) kwarg; ``medium_effort`` an
|
||||
# Ultra (``nemotron-3-ultra``) kwarg. On the variant that doesn't define
|
||||
# the kwarg the template — and the renderer — no-op it.
|
||||
"low_effort": [True, False],
|
||||
"medium_effort": [True, False],
|
||||
# MiniMax-M2 — fallback persona string when no system message is
|
||||
# supplied. Two arbitrary values to verify the renderer threads the
|
||||
# exact bytes through (whitespace included).
|
||||
@@ -99,6 +126,8 @@ _KWARG_VALUES: dict[str, list[Any]] = {
|
||||
# Qwen3.5 / Qwen3.6 / Qwen3-VL — when True, prefix each image /
|
||||
# video placeholder with ``Picture N: `` / ``Video N: ``.
|
||||
"add_vision_id": [True, False],
|
||||
# Qwen3.6 — keep historical think blocks before the last real user query.
|
||||
"preserve_thinking": [True, False],
|
||||
# gpt-oss — pin to a fixed date so the renderer's preamble matches
|
||||
# the harmony oracle built with the same date. The default
|
||||
# ``today's date`` is intentionally avoided here so the assertion
|
||||
@@ -251,6 +280,19 @@ def _template_fields_for(model: str, renderer_name: str) -> frozenset[str]:
|
||||
return _config_class_for(resolved).template_field_names()
|
||||
|
||||
|
||||
def _value_valid_for(model: str, renderer_name: str, kwarg: str, value: Any) -> bool:
|
||||
"""Whether ``value`` is accepted by this renderer's typed config for
|
||||
``kwarg``. Lets renderers share a template-field name with different value
|
||||
domains (e.g. ``reasoning_effort``: gpt-oss ``low/medium/high`` vs Hy3
|
||||
``no_think/low/high``) — the matrix keeps only the cells that construct."""
|
||||
resolved = _resolve_renderer_name(model, renderer_name)
|
||||
try:
|
||||
_config_class_for(resolved)(**{kwarg: value})
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _hf_parity_matrix() -> list[Any]:
|
||||
"""Auto-derived ``(model, renderer_name, kwarg, value)`` matrix for
|
||||
every renderer with template fields, minus gpt-oss (handled
|
||||
@@ -262,6 +304,8 @@ def _hf_parity_matrix() -> list[Any]:
|
||||
continue
|
||||
for kwarg in sorted(_template_fields_for(model, name)):
|
||||
for value in _KWARG_VALUES.get(kwarg, []):
|
||||
if not _value_valid_for(model, name, kwarg, value):
|
||||
continue
|
||||
out.append(
|
||||
pytest.param(
|
||||
model, name, kwarg, value, id=f"{model}-{kwarg}={value}"
|
||||
@@ -280,6 +324,8 @@ def _harmony_parity_matrix() -> list[Any]:
|
||||
continue
|
||||
for kwarg in sorted(_template_fields_for(model, name)):
|
||||
for value in _KWARG_VALUES.get(kwarg, []):
|
||||
if not _value_valid_for(model, name, kwarg, value):
|
||||
continue
|
||||
out.append(
|
||||
pytest.param(
|
||||
model, name, kwarg, value, id=f"{model}-{kwarg}={value}"
|
||||
|
||||
@@ -25,11 +25,11 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# (HuggingFace model name, renderer name or "auto"). These are the
|
||||
# renderers we actively rely on; expand as new ones get hand-coded.
|
||||
_ROUNDTRIP_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"),
|
||||
("PrimeIntellect/Qwen3-0.6B", "auto"),
|
||||
("Qwen/Qwen3.5-9B", "auto"),
|
||||
("Qwen/Qwen3.6-35B-A3B", "auto"),
|
||||
("Qwen/Qwen3-VL-4B-Instruct", "auto"),
|
||||
@@ -47,6 +47,11 @@ _ROUNDTRIP_MODELS = [
|
||||
# (no separating newline) — the Ultra-specific glue stresses the round-trip.
|
||||
("nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
# Laguna-XS-2.1 is deliberately absent: under the default
|
||||
# ``enable_thinking=False`` its template drops assistant reasoning at
|
||||
# render time, so the reasoning round-trip can't hold by design.
|
||||
# test_laguna_xs21.py covers the round-trip under enable_thinking=True.
|
||||
("tencent/Hy3", "auto"),
|
||||
("unsloth/Llama-3.2-1B-Instruct", "llama-3"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
|
||||
|
||||
@@ -32,6 +32,7 @@ _MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"), # hermes JSON — control
|
||||
("moonshotai/Kimi-K2-Instruct", "auto"), # section JSON — control
|
||||
("Qwen/Qwen3.5-9B", "auto"), # XML
|
||||
("PrimeIntellect/Qwen3-0.6B", "auto"), # XML
|
||||
("zai-org/GLM-5", "auto"), # XML
|
||||
("MiniMaxAI/MiniMax-M2.5", "auto"), # XML
|
||||
("poolside/Laguna-XS.2", "auto"), # XML
|
||||
|
||||
@@ -9,12 +9,11 @@ resolution-markers = [
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "2026-05-18T21:42:54.18041997Z"
|
||||
exclude-newer = "2026-06-19T02:36:32.208558271Z"
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
prime-pydantic-config = false
|
||||
fastokens = false
|
||||
|
||||
[[package]]
|
||||
name = "annotated-doc"
|
||||
@@ -268,35 +267,6 @@ 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"
|
||||
@@ -1380,7 +1350,6 @@ 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'" },
|
||||
@@ -1405,11 +1374,10 @@ 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 = "openai-harmony", specifier = ">=0.0.4" },
|
||||
{ name = "prime-pydantic-config", specifier = ">=0.3.0.dev83" },
|
||||
{ name = "tiktoken" },
|
||||
{ name = "transformers", specifier = ">=4.50.0" },
|
||||
|
||||
Reference in New Issue
Block a user