Compare commits

...
Author SHA1 Message Date
halleriteandGitHub 8704f9d502 feat(map): add Qwen3-30B-A3B-{Instruct,Thinking}-2507, GLM-5-FP8 (#50)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-18 19:47:42 +02:00
halleriteandGitHub fdc03f2861 feat(client): pre-flight overflow check with auto-discovery (#48) 2026-05-18 18:33:28 +02:00
eligottsandGitHub d547eef54c fix(client): add Qwen35Renderer to _build_mm_features dispatch (#45) 2026-05-18 12:11:01 +02:00
eligottsandGitHub 25ba413d46 fix(qwen3_vl): require truthy value in untyped image_part fallback (#46) 2026-05-18 12:09:58 +02:00
halleriteandGitHub 17d0584f87 feat(base): per-message / per-role analytics on RenderedTokens (#38)
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
2026-05-16 14:08:10 +02:00
JannikStandGitHub 87084dcb8c Merge pull request #37 from PrimeIntellect-ai/improvement/pypi-trusted-publishing
Publish / build (push) Canceled after 0s
Publish / publish (push) Canceled after 0s
improvement: switch renderers PyPI publish to OIDC trusted publishing
2026-05-15 08:52:16 +02:00
Jannik Straube 2eabcf4274 improvement: switch renderers PyPI publish to OIDC trusted publishing
- Split publish.yml into build (contents: read) and publish (id-token: write, pypi-prod env)
- Replace uv publish --token "$PYPI_RENDERERS_TOKEN" with pypa/gh-action-pypi-publish pinned to SHA (v1.14.0)
- Build runs untrusted code without OIDC so a poisoned build dep cannot mint the publishing token
2026-05-14 22:53:18 -07:00
halleriteandGitHub 973581f5e0 feat: route load_tokenizer through fastokens by default (#10) 2026-05-15 02:45:15 +02:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
e2639e32b8 build(deps): bump urllib3 from 2.6.3 to 2.7.0 (#35)
Bumps [urllib3](https://github.com/urllib3/urllib3) from 2.6.3 to 2.7.0.
- [Release notes](https://github.com/urllib3/urllib3/releases)
- [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst)
- [Commits](https://github.com/urllib3/urllib3/compare/2.6.3...2.7.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-15 00:03:26 +02:00
halleriteandGitHub 01aeb004b8 feat(base): add RenderedTokens.sampled_mask for SFT/RL parity (#33) 2026-05-14 19:17:30 +02:00
eligottsandGitHub 562db77eff fix(qwen35): emit images inline in tool-response content (#25)
Publish / publish (push) Canceled after 0s
2026-05-13 18:51:12 +02:00
halleriteandGitHub 40620409ed fix(parsing): schema-aware tool-arg coercion for XML-style parsers (#28) 2026-05-13 16:55:06 +02:00
Robin NabelandGitHub f99428a35b add LagunaXS2Renderer for poolside/Laguna-XS.2 (#21) 2026-05-13 16:09:27 +02:00
halleriteandGitHub 2c2aa00d42 chore: license under Apache 2.0 (#27) 2026-05-13 13:49:37 +02:00
halleriteandGitHub 3ebfe7b67e feat(parsing): per-attempt ParsedToolCall with status + token spans (#22) 2026-05-13 13:32:22 +02:00
Jiajun LiandGitHub 073389004f examples: add online SGLang HTTP recipe (#23) 2026-05-13 03:12:04 +02:00
37 changed files with 5041 additions and 1036 deletions
+32 -8
View File
@@ -12,8 +12,16 @@ on:
- "renderers-v*"
jobs:
publish:
# 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:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/renderers-v')
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
@@ -28,8 +36,7 @@ jobs:
with:
fetch-depth: 0
- name: Resolve release tag
id: release
- name: Validate release tag
env:
EVENT_NAME: ${{ github.event_name }}
PUSHED_REF: ${{ github.ref_name }}
@@ -53,14 +60,31 @@ jobs:
;;
esac
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
- uses: astral-sh/setup-uv@v7
- name: Build renderers
run: uv build
- name: Upload dist artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
if-no-files-found: error
retention-days: 7
publish:
needs: build
runs-on: ubuntu-latest
environment: pypi-prod
permissions:
id-token: write
steps:
- name: Download dist artifacts
uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- name: Publish to PyPI
env:
PYPI_RENDERERS_TOKEN: ${{ secrets.PYPI_RENDERERS_TOKEN }}
run: uv publish --token "$PYPI_RENDERERS_TOKEN" dist/*
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Support. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or support.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Prime Intellect
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+4
View File
@@ -141,3 +141,7 @@ uv run pytest
```
Round-trip parity (render → parse → original) and token-level parity against `apply_chat_template` are tested per renderer. End-to-end validation runs against Reverse-Text, Wordle, OpenCode-Math, and RLM-SWE environments.
## License
Licensed under the [Apache License, Version 2.0](LICENSE).
+18
View File
@@ -31,6 +31,24 @@ CUDA_VISIBLE_DEVICES=1 uv run --script examples/sglang/multiturn_generate_sglang
The SGLang script uses `input_ids`, so SGLang does not apply a chat template.
It leaves `openai-harmony` at SGLang's pinned version for dependency resolution.
### SGLang HTTP Recipe (online)
For a token-in/token-out HTTP path against an already-running SGLang server:
```bash
sglang serve --model-path Qwen/Qwen3.5-4B \
--host 0.0.0.0 --port 30000 --tensor-parallel-size 1 --trust-remote-code &
uv run python examples/sglang/online_multiturn_sglang.py \
--base-url http://localhost:30000 --model Qwen/Qwen3.5-4B
```
The HTTP recipe posts `input_ids` to `/generate`; streaming is intentionally
unsupported because `parse_response`/`bridge_to_next_turn` require the full
completion. The source-checkout command above uses the local `renderers`
package; the PEP 723 `uv run --script` form requires a published package that
satisfies the script header.
## Transformers Multi-Turn Recipe
```bash
+255
View File
@@ -0,0 +1,255 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10,<3.14"
# dependencies = [
# "renderers>=0.1.6",
# "transformers>=5.3.0",
# "httpx>=0.27",
# "openai-harmony==0.0.4",
# "tiktoken",
# "jinja2",
# "numpy",
# ]
# ///
"""SGLang online generation from renderer-owned prompt token IDs.
Mirrors `multiturn_generate_sglang.py` but talks to an already-running SGLang
HTTP server over `/generate` instead of an in-process `sgl.Engine`. The
renderer owns chat templating and parsing; SGLang only does token-in,
token-out.
Streaming is intentionally not supported: `parse_response` and
`bridge_to_next_turn` both need the complete `completion_ids`.
Launch a server first, e.g.
sglang serve --model-path Qwen/Qwen3.5-4B \\
--host 0.0.0.0 --port 30000 --tensor-parallel-size 1 --trust-remote-code
then, from a source checkout,
uv run python examples/sglang/online_multiturn_sglang.py \\
--base-url http://localhost:30000 --model Qwen/Qwen3.5-4B
The PEP 723 `uv run --script` form requires a published `renderers` package
that satisfies the script header.
"""
from __future__ import annotations
import argparse
import asyncio
import json
from typing import Any
import httpx
from renderers.base import Renderer
from renderers.gpt_oss import GptOssRenderer
from renderers.qwen35 import Qwen35Renderer
from transformers import AutoTokenizer
TOOLS = [
{
"type": "function",
"function": {
"name": "multiply",
"description": "Multiply two integers.",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "integer"},
"b": {"type": "integer"},
},
"required": ["a", "b"],
},
},
}
]
def make_renderer(model: str, enable_thinking: bool | None) -> Renderer:
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
if model.startswith("Qwen/Qwen3.5-"):
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
if model == "openai/gpt-oss-20b":
return GptOssRenderer(tokenizer)
raise ValueError(f"unsupported demo model: {model}")
def completion_ids(output: dict, prompt_ids: list[int]) -> list[int]:
ids = list(output.get("output_ids") or output.get("token_ids") or [])
if not ids:
raise RuntimeError("SGLang did not return completion token IDs")
# Match offline recipe: strip prefix only if SGLang echoed the prompt back.
return ids[len(prompt_ids) :] if ids[: len(prompt_ids)] == prompt_ids else ids
async def generate_sglang(
*,
client: httpx.AsyncClient,
base_url: str,
renderer: Renderer,
prompt_ids: list[int],
max_new_tokens: int,
extra_key: str | None = None,
) -> dict[str, Any]:
body: dict[str, Any] = {
"input_ids": prompt_ids,
"sampling_params": {
"temperature": 0.0,
"max_new_tokens": max_new_tokens,
"stop_token_ids": renderer.get_stop_token_ids(),
"skip_special_tokens": False,
"no_stop_trim": True,
},
"stream": False,
}
if extra_key is not None:
body["extra_key"] = extra_key
response = await client.post(f"{base_url.rstrip('/')}/generate", json=body)
response.raise_for_status()
return response.json()
def print_parsed(label: str, turn: str, parsed) -> None:
print(f"\n[{label}] {turn}")
if parsed.reasoning_content:
print(f"reasoning: {parsed.reasoning_content[:240]}")
if parsed.tool_calls:
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
if parsed.content:
print(f"content: {parsed.content}")
async def run_one(
*,
client: httpx.AsyncClient,
base_url: str,
model: str,
enable_thinking: bool | None,
max_new_tokens: int,
) -> None:
label = (
model
if enable_thinking is None
else f"{model} enable_thinking={enable_thinking}"
)
print(f"\n=== {label} ===")
renderer = make_renderer(model, enable_thinking)
messages: list[dict[str, Any]] = [
{"role": "system", "content": "You are a concise tool-using assistant."},
{
"role": "user",
"content": "Use the multiply tool for 17 * 23, then summarize.",
},
]
# Turn 1: render locally, send token IDs. SGLang never sees messages.
prompt_ids = renderer.render_ids(messages, tools=TOOLS, add_generation_prompt=True)
output1 = await generate_sglang(
client=client,
base_url=base_url,
renderer=renderer,
prompt_ids=prompt_ids,
max_new_tokens=max_new_tokens,
)
completion1 = completion_ids(output1, prompt_ids)
parsed1 = renderer.parse_response(completion1)
print_parsed(label, "turn 1", parsed1)
assistant: dict[str, Any] = {"role": "assistant", "content": parsed1.content}
if parsed1.reasoning_content:
assistant["reasoning_content"] = parsed1.reasoning_content
if parsed1.tool_calls:
assistant["tool_calls"] = parsed1.tool_calls
messages.append(assistant)
if parsed1.tool_calls:
new_messages: list[dict[str, Any]] = []
for idx, tool_call in enumerate(parsed1.tool_calls):
fn = tool_call.get("function") or tool_call
tool_args = fn.get("arguments") or {}
if isinstance(tool_args, str):
tool_args = json.loads(tool_args)
new_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.get("id", f"call_{idx}"),
"name": fn.get("name", "multiply"),
"content": json.dumps(
{"result": int(tool_args["a"]) * int(tool_args["b"])}
),
}
)
else:
new_messages = [
{"role": "user", "content": "Give the final answer in one sentence."}
]
# Turn 2: bridge extends prompt_ids + completion1 exactly.
bridged_ids = renderer.bridge_to_next_turn(
prompt_ids, completion1, new_messages, tools=TOOLS
)
if bridged_ids is None:
raise RuntimeError("bridge_to_next_turn returned None")
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
prompt_ids + completion1
)
output2 = await generate_sglang(
client=client,
base_url=base_url,
renderer=renderer,
prompt_ids=bridged_ids,
max_new_tokens=max_new_tokens,
)
completion2 = completion_ids(output2, bridged_ids)
print_parsed(label, "turn 2", renderer.parse_response(completion2))
async def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--base-url",
default="http://localhost:30000",
help="SGLang HTTP server base URL.",
)
parser.add_argument(
"--model",
default="Qwen/Qwen3.5-4B",
help="Must match the model the SGLang server is serving.",
)
parser.add_argument(
"--enable-thinking",
choices=["true", "false", "both"],
default="both",
help="Qwen3.5 thinking mode. Ignored for gpt-oss.",
)
parser.add_argument("--max-new-tokens", type=int, default=512)
parser.add_argument("--timeout", type=float, default=600.0)
args = parser.parse_args()
if args.model.startswith("Qwen/Qwen3.5-"):
if args.enable_thinking == "both":
modes: list[bool | None] = [True, False]
else:
modes = [args.enable_thinking == "true"]
else:
modes = [None]
async with httpx.AsyncClient(timeout=args.timeout) as client:
for mode in modes:
await run_one(
client=client,
base_url=args.base_url,
model=args.model,
enable_thinking=mode,
max_new_tokens=args.max_new_tokens,
)
if __name__ == "__main__":
asyncio.run(main())
+8
View File
@@ -11,6 +11,8 @@ name = "renderers"
dynamic = ["version"]
description = "Chat template renderers — deterministic message-to-token conversion for LLM training"
readme = "README.md"
license = "Apache-2.0"
license-files = ["LICENSE"]
requires-python = ">=3.10,<3.14"
dependencies = [
"numpy",
@@ -22,6 +24,12 @@ dependencies = [
# OpenAI's reference implementation keeps us byte-identical with vLLM
# (which also uses it) and saves us mirroring a 330-line Jinja template.
"openai-harmony>=0.0.8",
# Crusoe's Rust BPE tokenizer; ~10x faster encode vs HF's tokenizers.
# ``load_tokenizer`` patches it in by default for every supported model
# except a small denylist (DeepSeek-V3 family, MiniMax-M2 family). The
# patch is bracketed around ``from_pretrained``, so subsequent
# ``AutoTokenizer`` calls outside the renderers package stay vanilla.
"fastokens>=0.1.1",
]
[tool.hatch.version]
+8
View File
@@ -15,6 +15,7 @@ from renderers.base import (
MultiModalData,
MultimodalRenderer,
ParsedResponse,
ParsedToolCall,
PlaceholderRange,
RenderedConversation,
RenderedTokens,
@@ -24,6 +25,7 @@ from renderers.base import (
ThinkingPart,
ToolCall,
ToolCallFunction,
ToolCallParseStatus,
ToolSpec,
VideoPart,
build_training_sample,
@@ -34,6 +36,7 @@ from renderers.base import (
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.client import OverlongPromptError
from renderers.deepseek_v3 import DeepSeekV3Renderer
from renderers.default import DefaultRenderer
from renderers.glm5 import GLM5Renderer
@@ -41,6 +44,7 @@ from renderers.glm45 import GLM45Renderer
from renderers.gpt_oss import GptOssRenderer
from renderers.kimi_k2 import KimiK2Renderer
from renderers.kimi_k25 import KimiK25Renderer
from renderers.laguna_xs2 import LagunaXS2Renderer
from renderers.minimax_m2 import MiniMaxM2Renderer
from renderers.nemotron3 import Nemotron3Renderer
from renderers.qwen3 import Qwen3Renderer
@@ -59,13 +63,16 @@ __all__ = [
"ImagePart",
"KimiK2Renderer",
"KimiK25Renderer",
"LagunaXS2Renderer",
"MULTIMODAL_MODELS",
"Message",
"MiniMaxM2Renderer",
"MultiModalData",
"MultimodalRenderer",
"Nemotron3Renderer",
"OverlongPromptError",
"ParsedResponse",
"ParsedToolCall",
"PlaceholderRange",
"Qwen3Renderer",
"Qwen3VLRenderer",
@@ -79,6 +86,7 @@ __all__ = [
"ThinkingPart",
"ToolCall",
"ToolCallFunction",
"ToolCallParseStatus",
"ToolSpec",
"VideoPart",
"__version__",
+389 -29
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import enum
import logging
import queue
import threading
@@ -147,8 +148,26 @@ class RenderedTokens:
"""Result of rendering messages to tokens.
Each token carries an index into the original message list so callers can
build per-token loss masks without re-rendering. Tokens from structural
scaffolding (generation prompt, im_start/im_end wrapping) carry index -1.
build per-token loss masks without re-rendering. Tokens from structural
scaffolding the renderer adds outside any single message (e.g. the
trailing generation prompt) carry index ``-1``.
``sampled_mask`` is a separate per-token signal: ``True`` if the model
would have produced this token at inference time (i.e. it appears in
the sampled completion), ``False`` if it is template-injected
scaffolding the model never emits (``<|im_start|>role\\n`` openers,
inter-turn ``\\n`` separators, system / user / tool content from
conversation history, etc.). This is distinct from
``message_indices``: a token can belong to an assistant message
(``message_indices[k] >= 0``) and still be scaffolding the template
adds around the model's actual completion. SFT loss masks should AND
both: train on tokens whose role is trainable AND that the model
would actually sample.
Empty ``sampled_mask`` (``[]``) means the renderer doesn't provide
this signal — consumers should fall back to attribution-only
masking. ``DefaultRenderer`` leaves it empty because the Jinja
template is opaque; hand-coded renderers populate it.
``multi_modal_data`` is populated by multimodal renderers (e.g.
``Qwen3VLRenderer``) when image / video content parts are present;
@@ -157,16 +176,232 @@ class RenderedTokens:
token_ids: list[int] = field(default_factory=list)
message_indices: list[int] = field(default_factory=list)
sampled_mask: list[bool] = field(default_factory=list)
message_roles: list[str] = field(default_factory=list)
multi_modal_data: "MultiModalData | None" = None
def tokens_per_message(
self, n_messages: int | None = None, *, sampled_only: bool = False
) -> list[int]:
"""Count rendered tokens attributed to each caller-relative message.
``out[i]`` is the number of tokens with ``message_indices[k] == i``,
i.e. tokens the renderer attributed to ``messages[i]``. This
includes template scaffolding the renderer wraps around the
message — the ``<|im_start|>role\\n`` opener, the closing
``<|im_end|>\\n``, etc. — because those are the renderer's own
attribution decision and are preserved verbatim here. Tokens with
``message_indices[k] == -1`` (scaffolding outside any single
message, e.g. the trailing generation prompt) are not counted.
With ``sampled_only=True``, counts only tokens the model would
have emitted at inference (``sampled_mask[k] is True``). For
example, length-penalty signals in RL: the template wraps each
assistant turn in scaffolding tokens (e.g. ``<|im_start|>assistant\\n``,
``<|im_end|>\\n``) that are constant-size and not chosen by the
model, so they shouldn't enter the penalty. For roles the model
never samples (``user``, ``tool``, ``system``), the
``sampled_only`` count is zero by construction. Renderers that
don't populate ``sampled_mask`` (``DefaultRenderer`` — the Jinja
template is opaque) return all zeros under ``sampled_only=True``.
``n_messages`` defaults to ``len(self.message_roles)``, which
every Renderer populates with the caller-relative message list
(caller's ``messages`` for ``render()``; ``new_messages`` for
``bridge_to_next_turn()``). Pass it explicitly only to truncate
— indices outside ``[0, n_messages)`` are ignored, so passing a
smaller value won't raise; it just drops the tail. Values larger
than ``len(self.message_roles)`` are clamped, so the returned
list never claims more messages than the renderer attributed.
Works on results from both :meth:`Renderer.render` and
:meth:`Renderer.bridge_to_next_turn`. For a bridge result the
indices are relative to the new messages the bridge added, not
the full conversation history; the prior portion is uniformly
``-1`` (and ``sampled_mask`` uniformly ``False``), so it
contributes nothing to either count.
"""
if n_messages is None:
n_messages = len(self.message_roles)
else:
n_messages = min(n_messages, len(self.message_roles))
out = [0] * n_messages
if sampled_only:
if len(self.sampled_mask) != len(self.token_ids):
return out
for idx, sampled in zip(self.message_indices, self.sampled_mask):
if sampled and 0 <= idx < n_messages:
out[idx] += 1
else:
for idx in self.message_indices:
if 0 <= idx < n_messages:
out[idx] += 1
return out
def message_token_spans(self) -> list[tuple[int, int] | None]:
"""Per-message ``(start, end)`` slices into :attr:`token_ids`.
``out[i]`` is the half-open span ``[start, end)`` such that
``token_ids[start:end]`` are the tokens attributed to
``messages[i]`` (or ``new_messages[i]`` for a bridge result).
Messages that contributed no tokens get ``None``. Renderer
scaffolding outside any message (``message_indices[k] == -1``)
is not represented.
Hand-coded renderers emit each message's tokens contiguously,
so the span is well-defined. The implementation tolerates
non-contiguous attribution by returning the outer span
``(first_k, last_k + 1)``; if you suspect interleaving, slice
``message_indices`` yourself to verify.
Returns ``len(self.message_roles)`` entries when ``message_roles``
is populated. Otherwise infers the count from
``max(message_indices) + 1`` — useful for manually-constructed
``RenderedTokens`` in tests but only correct when the last
message contributed at least one token.
Cheap to call: single pass over ``message_indices``. Re-call
rather than caching the result if you mutate the dataclass.
"""
if self.message_roles:
n_messages = len(self.message_roles)
else:
max_idx = -1
for idx in self.message_indices:
if idx > max_idx:
max_idx = idx
n_messages = max_idx + 1
firsts: list[int] = [-1] * n_messages
lasts: list[int] = [-1] * n_messages
for k, idx in enumerate(self.message_indices):
if 0 <= idx < n_messages:
if firsts[idx] == -1:
firsts[idx] = k
lasts[idx] = k
out: list[tuple[int, int] | None] = []
for i in range(n_messages):
if firsts[i] == -1:
out.append(None)
else:
out.append((firsts[i], lasts[i] + 1))
return out
def role_token_spans(self) -> dict[str, list[tuple[int, int]]]:
""":meth:`message_token_spans` regrouped by ``message_roles``.
Maps each role appearing in :attr:`message_roles` to a list of
``(start, end)`` spans — one per occurrence of that role, in
message order. Messages with no contributed tokens are skipped.
Returns an empty dict if :attr:`message_roles` is empty.
Intended for per-role statistics that operate on per-token
signals — e.g. ``logprobs[start:end]`` for each assistant span
to compute per-turn perplexity, or
``attention[start:end]`` for tool-response attention analysis.
"""
spans = self.message_token_spans()
out: dict[str, list[tuple[int, int]]] = {}
for role, span in zip(self.message_roles, spans):
if span is None:
out.setdefault(role, [])
continue
out.setdefault(role, []).append(span)
return out
def tokens_by_role(self, *, sampled_only: bool = False) -> dict[str, int]:
"""Sum :meth:`tokens_per_message` grouped by ``message_roles``.
Convenience for length-penalty bookkeeping in RL trainers:
``rendered.tokens_by_role(sampled_only=True)["assistant"]`` is
the count of tokens the model actually emitted across all
assistant turns — template scaffolding excluded.
``rendered.tokens_by_role()["tool"]`` is the raw count of
tool-response tokens (``sampled_only`` is zero for ``tool`` by
construction since the model never samples those).
Roles present in :attr:`message_roles` always appear in the
returned dict, even with post-filter count ``0``, so callers
can index directly without ``KeyError`` on conversations that
happen to lack a role. Returns an empty dict if
:attr:`message_roles` is empty.
"""
counts = self.tokens_per_message(sampled_only=sampled_only)
out: dict[str, int] = {}
for role, n in zip(self.message_roles, counts):
out[role] = out.get(role, 0) + n
return out
class ToolCallParseStatus(str, enum.Enum):
"""Per-attempt outcome of parsing a single ``<tool_call>`` block.
The renderer parser's job is JSON-syntax → ``dict`` (the parser-level
contract). Schema validation — required fields, argument types, tool
name lookup — is the *tool*'s job and is intentionally not done here.
See ``ParsedToolCall.status`` for what each value means.
Diverges from vLLM/SGLang on purpose. Both engines collapse parse
failures into either a single ``tools_called: bool`` (vLLM) or silent
drops (SGLang), with no way to express "the model emitted three
parallel tool calls and the second was malformed." Renderers expose
that information because verifier / RL-loss code needs it for
schema-adherence rubrics and selective token masking — use cases the
inference engines don't serve.
"""
OK = "ok"
INVALID_JSON = "invalid_json" # body wasn't valid JSON
UNCLOSED_BLOCK = "unclosed_block" # opening delim hit EOS / stop
MISSING_NAME = "missing_name" # parsed structurally, but no function name
MALFORMED_STRUCTURE = "malformed_structure" # format-specific shape error
@dataclass
class ParsedToolCall:
"""A single ``<tool_call>`` block as the renderer parsed it.
One record per *attempt* — successful and malformed calls both land
here, distinguished by ``status``. Ordering is preserved across the
response, so ``[OK, INVALID_JSON, OK]`` is a faithful record of "the
model emitted three parallel calls; the second was broken."
``token_span`` is a half-open ``[start, end)`` slice into the
completion's stripped token id stream (i.e. ``token_ids`` after
``_strip_stop_tokens``); some text-based parsers can't cheaply
recover token offsets and leave it ``None``. Useful for trainer-side
selective loss masking: zero the mask over the spans of non-OK
entries to avoid reinforcing malformed structures.
``raw`` is the decoded text of the block as the model emitted it
(before any JSON normalization). Always populated — for failed
attempts it's the only way to see what actually went wrong.
"""
raw: str
name: str | None = None
arguments: dict[str, Any] | str | None = None
token_span: tuple[int, int] | None = None
status: ToolCallParseStatus = ToolCallParseStatus.OK
id: str | None = None # native tool-call id when the format carries one (Kimi K2)
@dataclass
class ParsedResponse:
"""Result of parsing completion tokens back into a structured message."""
"""Result of parsing completion tokens back into a structured message.
``tool_calls`` is a list of every parse attempt — successful and
malformed alike. Filter with ``[tc for tc in r.tool_calls if
tc.status == ToolCallParseStatus.OK]`` to get only the calls that
came out clean. Empty list = the model didn't emit any tool calls
(different from "tried and failed entirely", which produces a list
with non-OK entries).
"""
content: str
reasoning_content: str | None = None
tool_calls: list[dict[str, Any]] | None = None
tool_calls: list[ParsedToolCall] = field(default_factory=list)
@dataclass
@@ -235,8 +470,23 @@ class Renderer(Protocol):
"""Render messages to token IDs (without attribution metadata)."""
...
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
"""Parse completion tokens back into a structured message."""
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
"""Parse completion tokens back into a structured message.
``tools`` is the same list passed to ``render`` for this turn.
XML-style formats (Qwen3.5, GLM, MiniMax, Laguna) render argument
values verbatim inside ``<arg_value>`` tags with no quoting, so
a value like ``true`` is ambiguous between bool and the string
``"true"``. When ``tools`` is supplied, the parser consults each
parameter's declared JSON-schema type to preserve string args
verbatim. Without ``tools``, parsers fall back to the historical
``json.loads``-with-text-fallback behavior.
"""
...
def get_stop_token_ids(self) -> list[int]:
@@ -262,6 +512,25 @@ class Renderer(Protocol):
list so far with ``add_generation_prompt=True`` — except prev
sampled tokens are kept verbatim rather than re-rendered).
Attribution on the returned ``RenderedTokens``:
- ``message_indices`` is ``-1`` over the entire prior portion
(length ``len(previous_ids)`` after :func:`trim_to_turn_close`)
because the bridge gets the prior as raw token lists with no
attribution. Over the bridge-added portion, indices are
relative to ``new_messages``: a token rendered as part of
``new_messages[i]`` carries ``i``, and inter-turn separators /
the trailing generation prompt carry ``-1``. So
``bridge.tokens_per_message(len(new_messages))`` gives the
per-new-message token count for length-penalty bookkeeping.
- ``sampled_mask`` is uniformly ``False`` across the entire
returned sequence. The bridge output is consumed as the next
turn's prompt; nothing it emits was model-sampled, and the
bridge has no way to recover which prior tokens were. If the
caller needs that distinction for the prior portion, they
have it directly: every token in ``prev_completion_ids`` was
sampled; every token in ``prev_prompt_ids`` was not.
Text-only renderers return :class:`RenderedTokens` with
``multi_modal_data=None``. Multimodal renderers (see
:class:`MultimodalRenderer`) populate ``multi_modal_data`` so
@@ -497,6 +766,8 @@ MODEL_RENDERER_MAP: dict[str, str] = {
"Qwen/Qwen3-14B": "qwen3",
"Qwen/Qwen3-32B": "qwen3",
"Qwen/Qwen3-30B-A3B": "qwen3",
"Qwen/Qwen3-30B-A3B-Instruct-2507": "qwen3",
"Qwen/Qwen3-30B-A3B-Thinking-2507": "qwen3",
"Qwen/Qwen3-235B-A22B": "qwen3",
# Qwen3.5. All seven sizes share the same renderer. The 4B / 9B /
# 35B-A3B / 122B-A10B / 397B-A17B chat template defaults
@@ -523,6 +794,7 @@ MODEL_RENDERER_MAP: dict[str, str] = {
"Qwen/Qwen3-VL-30B-A3B-Instruct": "qwen3-vl",
# GLM-5 family (GLM-4.7 reuses the GLM-5 template).
"zai-org/GLM-5": "glm-5",
"zai-org/GLM-5-FP8": "glm-5",
"zai-org/GLM-4.7-Flash": "glm-5",
"zai-org/GLM-5.1": "glm-5.1",
# GLM-4.5.
@@ -541,6 +813,8 @@ MODEL_RENDERER_MAP: dict[str, str] = {
# Nemotron 3.
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "nemotron-3",
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "nemotron-3",
# Poolside Laguna.
"poolside/Laguna-XS.2": "laguna-xs.2",
# GPT-OSS.
"openai/gpt-oss-20b": "gpt-oss",
"openai/gpt-oss-120b": "gpt-oss",
@@ -634,37 +908,108 @@ TRUSTED_REVISIONS: dict[str, str] = {
}
def load_tokenizer(model_name_or_path: str):
"""Load a tokenizer with the renderers-package security policy.
# Models for which ``fastokens`` is known to diverge from vanilla
# ``transformers.AutoTokenizer`` and therefore must NOT be patched.
# Empirical audit ran each entry of ``MODEL_RENDERER_MAP`` through both
# backends; 31/35 passed byte-identical. The four below either fail to
# load under fastokens (DeepSeek-V3 family — Metaspace pretokenizer not
# yet implemented) or are kept defensively pending an upstream fastokens
# fix (MiniMax-M2 family — see per-entry comments).
FASTOKENS_INCOMPATIBLE: frozenset[str] = frozenset(
{
# fastokens 0.1.1: ``ValueError: pre-tokenizer error: unsupported
# pre-tokenizer type: Metaspace`` — DeepSeek's tokenizer uses
# SentencePiece-style Metaspace pretokenization which fastokens
# doesn't yet implement.
"deepseek-ai/DeepSeek-V3",
"deepseek-ai/DeepSeek-V3-Base",
# MiniMax: kept defensive pending upstream fastokens fix
# https://github.com/crusoecloud/fastokens/pull/32 — that PR
# removes a stray attribute leaked by ``unpatch_transformers``
# which steers MiniMax (declared ``tokenizer_class =
# 'GPT2Tokenizer'`` → slow→fast conversion path) down a different
# load path on subsequent vanilla loads. Once the upstream fix
# is released, these two entries can be dropped after re-audit.
"MiniMaxAI/MiniMax-M2",
"MiniMaxAI/MiniMax-M2.5",
}
)
Default: ``trust_remote_code=False`` — the safe choice for every
model in ``MODEL_RENDERER_MAP`` *except* the Kimi-K2 family.
Models listed in ``TRUSTED_REVISIONS`` load with
``trust_remote_code=True`` AND ``revision=<pinned sha>`` — required
because their tokenizer config has an ``auto_map.AutoTokenizer``
entry pointing at a repo-supplied Python class
(``tokenization_kimi.TikTokenTokenizer``). Pinning the revision
means transformers executes only the reviewed commit's code, not
whatever ``HEAD`` points at when the call fires.
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.
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.
"""
import fastokens
from transformers import AutoTokenizer
fastokens.patch_transformers()
try:
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
finally:
fastokens.unpatch_transformers()
def load_tokenizer(
model_name_or_path: str,
*,
use_fastokens: bool = True,
):
"""Load a tokenizer with the renderers-package security + perf policy.
**Security** — 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, MiniMax-M2
family) skip the patch — fastokens 0.1.1 either fails to load them
or produces token-divergent output. Pass ``use_fastokens=False`` to
force the vanilla backend for any other model.
Unknown / fine-tuned model paths fall through to
``trust_remote_code=False``. Callers who legitimately need to load
a custom-code tokenizer outside this allow-list should call
``AutoTokenizer.from_pretrained`` themselves and pass the result to
``create_renderer`` (which doesn't load tokenizers — only
``create_renderer_pool`` does).
``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.
"""
from transformers import AutoTokenizer
kwargs: dict[str, Any] = {}
revision = TRUSTED_REVISIONS.get(model_name_or_path)
if revision is not None:
return AutoTokenizer.from_pretrained(
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 AutoTokenizer.from_pretrained(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,
trust_remote_code=True,
revision=revision,
type(exc).__name__,
str(exc)[:160],
)
return AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=False)
return AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
def _populate_registry():
@@ -677,6 +1022,7 @@ def _populate_registry():
from renderers.gpt_oss import GptOssRenderer
from renderers.kimi_k2 import KimiK2Renderer
from renderers.kimi_k25 import KimiK25Renderer
from renderers.laguna_xs2 import LagunaXS2Renderer
from renderers.minimax_m2 import MiniMaxM2Renderer
from renderers.nemotron3 import Nemotron3Renderer
from renderers.qwen3 import Qwen3Renderer
@@ -698,6 +1044,7 @@ def _populate_registry():
"deepseek-v3": DeepSeekV3Renderer,
"kimi-k2": KimiK2Renderer,
"kimi-k2.5": KimiK25Renderer,
"laguna-xs.2": LagunaXS2Renderer,
"nemotron-3": Nemotron3Renderer,
"gpt-oss": GptOssRenderer,
}
@@ -762,8 +1109,8 @@ def create_renderer(
tokenizer: HuggingFace tokenizer instance.
renderer: Renderer name ('qwen3', 'qwen3-vl', 'qwen3.5', 'qwen3.6',
'glm-5', 'glm-5.1', 'glm-4.5', 'minimax-m2', 'deepseek-v3',
'kimi-k2', 'kimi-k2.5', 'nemotron-3', 'gpt-oss', 'default')
or 'auto' to detect from model name.
'kimi-k2', 'kimi-k2.5', 'laguna-xs.2', 'nemotron-3',
'gpt-oss', 'default') or 'auto' to detect from model name.
tool_parser: Name of a tool parser registered in ``renderers.parsers``.
Only consumed by DefaultRenderer. Model-specific renderers
have their own parsing wired in.
@@ -866,12 +1213,25 @@ def build_training_sample(
Single render() call + message_indices → per-token mask.
Replaces build_incremental_token_mask (O(N) renders → O(1)).
When the renderer populates ``rendered.sampled_mask``, the loss mask
is the AND of role-based attribution and the sampled signal: only
tokens the model would have produced at inference are trainable.
This keeps SFT byte-aligned with the RL trajectory mask (where the
prompt / completion split achieves the same effect structurally).
Renderers that don't populate ``sampled_mask`` (empty list) fall
back to attribution-only masking — every token attributed to a
trainable role is trained on, including template-injected
``<|im_start|>role\\n`` openers.
"""
rendered = renderer.render(messages, tools=tools)
has_sampled_info = len(rendered.sampled_mask) == len(rendered.token_ids)
loss_mask: list[bool] = []
for msg_idx in rendered.message_indices:
for k, msg_idx in enumerate(rendered.message_indices):
if msg_idx < 0:
loss_mask.append(False)
elif has_sampled_info and not rendered.sampled_mask[k]:
loss_mask.append(False)
else:
loss_mask.append(role_to_mask(messages[msg_idx]))
return rendered.token_ids, loss_mask
+118 -59
View File
@@ -14,16 +14,97 @@ from __future__ import annotations
import asyncio
import base64
import logging
from collections.abc import Mapping
from typing import Any, cast
import numpy as np
from openai import AsyncOpenAI, BadRequestError
from openai import AsyncOpenAI
from renderers.base import Message, MultiModalData, Renderer, RendererPool, ToolSpec
from renderers.base import (
Message,
MultiModalData,
Renderer,
RendererPool,
ToolCallParseStatus,
ToolSpec,
)
_request_logger = logging.getLogger("renderers.client")
class OverlongPromptError(Exception):
"""The rendered prompt exceeds the engine's context window.
Raised by :func:`generate` when the rendered token sequence is strictly
longer than the resolved cap — either an explicit ``max_prompt_len`` the
caller passed in, or the engine's ``max_model_len`` discovered via
``GET /v1/models``. Caught client-side before the engine ever sees the
request, so callers route the failure to a deterministic policy (skip /
truncate / count) instead of round-tripping through an engine 4xx.
Named after the corresponding ``verifiers.errors.OverlongPromptError``;
the two are distinct classes (different package hierarchies) but the
concept is the same and downstream clients translate one to the other.
"""
def __init__(self, *, prompt_len: int, max_prompt_len: int) -> None:
self.prompt_len = prompt_len
self.max_prompt_len = max_prompt_len
super().__init__(
f"Prompt length ({prompt_len}) exceeds maximum "
f"context length ({max_prompt_len})."
)
# Per-process cache of resolved engine context-length caps, keyed by
# ``(base_url, model)``. ``None`` is the "we asked the engine and it didn't
# tell us" sentinel — distinct from "key missing" (haven't asked yet). The
# lock serializes the first lookup per key; cache hits avoid the lock.
_max_prompt_len_cache: dict[tuple[str, str], int | None] = {}
_max_prompt_len_lock = asyncio.Lock()
async def _resolve_max_prompt_len(client: AsyncOpenAI, model: str) -> int | None:
"""Discover ``max_model_len`` from the engine via ``GET /v1/models``.
OpenAI-API-compatible engines expose model metadata at this endpoint;
vLLM extends its ``ModelCard`` with a ``max_model_len`` field. Engines
that don't (SGLang as of this writing, third-party gateways, etc.) get
a cached ``None`` and the pre-flight overflow check silently disables —
callers fall back to whatever reactive handling they have for engine
4xx, which the verifiers ``@handle_openai_overlong_prompt`` decorator
already supplies for the prime-rl path.
Any exception during lookup (network error, non-JSON body, attribute
miss on a mock client in tests) is treated as "unknown cap": cached
``None`` so we don't retry on every call.
"""
key = (str(getattr(client, "base_url", "")), model)
if key in _max_prompt_len_cache:
return _max_prompt_len_cache[key]
async with _max_prompt_len_lock:
if key in _max_prompt_len_cache:
return _max_prompt_len_cache[key]
try:
payload = await client.get("/models", cast_to=cast(Any, dict[str, Any]))
except Exception as exc:
_request_logger.debug("max_prompt_len lookup failed: %s", exc)
_max_prompt_len_cache[key] = None
return None
value: int | None = None
for card in payload.get("data") or []:
if not isinstance(card, Mapping):
continue
if card.get("id") != model:
continue
raw = card.get("max_model_len")
if isinstance(raw, int) and raw > 0:
value = raw
break
_max_prompt_len_cache[key] = value
return value
async def _maybe_offload(renderer: Renderer | RendererPool, fn):
"""Run sync renderer work on a thread iff ``renderer`` is a pool.
@@ -51,6 +132,7 @@ async def generate(
cache_salt: str | None = None,
priority: int | None = None,
extra_headers: dict[str, str] | None = None,
max_prompt_len: int | None = None,
) -> dict[str, Any]:
"""Tokenize messages, call vLLM /inference/v1/generate, parse the response.
@@ -67,6 +149,16 @@ async def generate(
mm_placeholders, kwargs_data) before POSTing. The serializer imports
``vllm.*`` lazily so text-only consumers never pay for the import.
``max_prompt_len`` controls the pre-flight overflow check. When the
rendered prompt is strictly longer than the cap, the request is never
sent and ``OverlongPromptError`` is raised. If ``max_prompt_len`` is
``None`` (the default), the cap is auto-discovered once per
``(base_url, model)`` via ``GET /v1/models`` (vLLM's
``ModelCard.max_model_len`` extension); engines that don't expose it
cache a ``None`` cap and the pre-flight silently disables. Engine 4xx
that still slip through propagate raw — converting them into a domain
error is the calling client's job (its error shape is engine-specific).
Returns a dict with: request_id, prompt_ids, completion_ids,
completion_logprobs, content, reasoning_content, tool_calls,
finish_reason, routed_experts.
@@ -89,6 +181,13 @@ async def generate(
prompt_ids, stop_token_ids, mm_data = await _maybe_offload(renderer, _prepare)
if max_prompt_len is None:
max_prompt_len = await _resolve_max_prompt_len(client, model)
if max_prompt_len is not None and len(prompt_ids) > max_prompt_len:
raise OverlongPromptError(
prompt_len=len(prompt_ids), max_prompt_len=max_prompt_len
)
sp: dict[str, Any] = dict(sampling_params or {})
sp["stop_token_ids"] = stop_token_ids
sp["logprobs"] = 1
@@ -128,22 +227,13 @@ async def generate(
}
if extra_headers:
post_kwargs["options"] = cast(Any, {"headers": extra_headers})
try:
data = await client.post(endpoint, **post_kwargs)
except BadRequestError as exc:
_log_overlong_prompt_diagnostic(
prompt_ids=prompt_ids,
messages=messages,
max_tokens=sp.get("max_tokens"),
exc=exc,
)
raise
data = await client.post(endpoint, **post_kwargs)
choice = (data.get("choices") or [{}])[0]
completion_ids = choice.get("token_ids") or []
parsed = await _maybe_offload(
renderer, lambda: renderer.parse_response(completion_ids)
renderer, lambda: renderer.parse_response(completion_ids, tools=tools)
)
# ChatCompletionLogProbs flatten: {"content": [{"logprob": ...}, ...]}
@@ -162,11 +252,17 @@ async def generate(
# /inference/v1/generate returns finish_reason in {"stop","length",...} —
# never "tool_calls" (a chat-completions concept). Promote stop→tool_calls
# when we extracted tool calls client-side, so OpenAI-compatible agent
# loops continue past the tool turn instead of treating the response as
# final.
# when we extracted at least one well-formed tool call client-side, so
# OpenAI-compatible agent loops continue past the tool turn instead of
# treating the response as final. Malformed attempts (INVALID_JSON,
# UNCLOSED_BLOCK, ...) don't qualify — those still surface on
# ``parsed.tool_calls`` so verifiers can inspect them, but they don't
# trigger the tool-loop continuation.
finish_reason = choice.get("finish_reason")
if parsed.tool_calls and finish_reason == "stop":
ok_tool_calls = [
tc for tc in parsed.tool_calls if tc.status == ToolCallParseStatus.OK
]
if ok_tool_calls and finish_reason == "stop":
finish_reason = "tool_calls"
return {
@@ -212,6 +308,7 @@ def _build_mm_features(
to change. Don't pre-build the abstraction with one engine in tree.
"""
from renderers.qwen3_vl import Qwen3VLRenderer
from renderers.qwen35 import Qwen35Renderer
# Type dispatch only needs the renderer class. Pools expose
# ``renderer_cls`` as a snapshot attribute, so we don't have to check
@@ -220,7 +317,10 @@ def _build_mm_features(
renderer.renderer_cls if isinstance(renderer, RendererPool) else type(renderer)
)
if issubclass(renderer_cls, Qwen3VLRenderer):
# Qwen3-VL and Qwen3.5 both ship ``pixel_values`` + ``image_grid_thw``
# via the shared Qwen2-VL field factory. ``spatial_merge_size=2`` is
# the family default and matches every Qwen-VL processor in tree.
if issubclass(renderer_cls, (Qwen3VLRenderer, Qwen35Renderer)):
return _build_qwen_vl_features(mm_data, spatial_merge_size=2)
raise NotImplementedError(
@@ -292,44 +392,3 @@ def _build_qwen_vl_features(
out["kwargs_data"] = None
return out
def _log_overlong_prompt_diagnostic(
*,
prompt_ids: list[int],
messages: list[Message],
max_tokens: int | None,
exc: BadRequestError,
) -> None:
"""Log a structured snapshot when vLLM rejects with 4xx — usually overlong.
Captures total prompt length, per-message role + character count, and
the first chunk of the response body.
"""
body_text = ""
response = getattr(exc, "response", None)
if response is not None:
body_text = (response.text or "")[:500].replace("\n", " ")
msg_summary = []
for i, m in enumerate(messages):
role = m.get("role", "?")
content = m.get("content")
if isinstance(content, str):
content_len = len(content)
elif isinstance(content, list):
content_len = sum(
len(p.get("text", "")) if isinstance(p, dict) else 0 for p in content
)
else:
content_len = 0
tool_calls = m.get("tool_calls")
tc_count = len(tool_calls) if tool_calls else 0
msg_summary.append(f"[{i}]{role}(c={content_len},tc={tc_count})")
_request_logger.warning(
"vllm 4xx prompt_len=%d messages=%d max_tokens=%s per_msg=%s response_body=%s",
len(prompt_ids),
len(messages),
max_tokens,
" ".join(msg_summary),
body_text,
)
+83 -34
View File
@@ -113,20 +113,23 @@ class DeepSeekV3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
# ── 1. BOS token ─────────────────────────────────────────────
emit_special(self._bos, -1)
emit_special(self._bos, -1, is_sampled=False)
# ── 2. Collect system messages at the start ───────────────────
# All leading system messages are concatenated with "\n\n" and emitted
@@ -148,7 +151,7 @@ class DeepSeekV3Renderer:
if sys_parts:
# Attribute the concatenated system text to the first system message (index 0).
emit_text("\n\n".join(sys_parts), 0)
emit_text("\n\n".join(sys_parts), 0, is_sampled=False)
# ── 3. Render non-system messages ─────────────────────────────
num_messages = len(messages)
@@ -163,8 +166,8 @@ class DeepSeekV3Renderer:
content = "".join(
p.get("text", "") for p in content if isinstance(p, dict)
)
emit_special(self._user_token, i)
emit_text(str(content), i)
emit_special(self._user_token, i, is_sampled=False)
emit_text(str(content), i, is_sampled=False)
elif role == "user":
content = msg.get("content") or ""
@@ -177,8 +180,8 @@ class DeepSeekV3Renderer:
else ""
for p in content
)
emit_special(self._user_token, i)
emit_text(str(content), i)
emit_special(self._user_token, i, is_sampled=False)
emit_text(str(content), i, is_sampled=False)
elif role == "assistant":
self._render_assistant(
@@ -202,11 +205,16 @@ class DeepSeekV3Renderer:
# Don't add <|Assistant|> after tool outputs — content flows directly.
last_role = messages[-1]["role"] if messages else None
if last_role != "tool":
emit_special(self._assistant_token, -1)
emit_special(self._assistant_token, -1, is_sampled=False)
if self._enable_thinking:
emit_text("<think>\n", -1)
emit_text("<think>\n", -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
@@ -221,7 +229,12 @@ class DeepSeekV3Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — args land in a ```json fence, schema not needed
) -> ParsedResponse:
return parse_deepseek_v3(
self._tokenizer,
token_ids,
@@ -261,12 +274,29 @@ class DeepSeekV3Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
ext.extend(self._encode(text))
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
for i, msg in enumerate(new_messages):
role = msg.get("role")
@@ -309,7 +339,13 @@ class DeepSeekV3Renderer:
if self._enable_thinking:
emit_text("<think>\n", -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
message_roles=[m.get("role") or "" for m in new_messages],
)
# ------------------------------------------------------------------
# Assistant rendering
@@ -349,17 +385,24 @@ class DeepSeekV3Renderer:
tool_calls = msg.get("tool_calls") or []
# ``<|Assistant|>`` is template-injected scaffolding — at
# inference the chat template emits it as the generation prompt
# and the model never samples it. Marking it ``is_sampled=False``
# keeps the SFT loss mask aligned with what the model would
# actually have produced. When the previous message is a tool
# response, the template skips this token entirely (content
# flows directly out of ``<|tool▁outputs▁end|>``).
if not prev_is_tool:
emit_special(self._assistant_token, msg_idx)
emit_special(self._assistant_token, msg_idx, is_sampled=False)
if not tool_calls:
emit_text(content, msg_idx)
emit_text(content, msg_idx, is_sampled=True)
else:
# Emit any pre-tool-call content first.
emit_text(content, msg_idx)
emit_text(content, msg_idx, is_sampled=True)
# Tool call section.
emit_special(self._tool_calls_begin, msg_idx)
emit_special(self._tool_calls_begin, msg_idx, is_sampled=True)
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
@@ -371,14 +414,17 @@ class DeepSeekV3Renderer:
)
# Format: <|tool▁call▁begin|>function<|tool▁sep|>{name}\n```json\n{args}\n```<|tool▁call▁end|>
# tool_sep is a special token; type ("function") and name+args are plain text.
emit_special(self._tool_call_begin, msg_idx)
emit_text("function", msg_idx)
emit_special(self._tool_sep, msg_idx)
emit_text(f"{name}\n```json\n{args_str}\n```", msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_end, msg_idx)
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text("function", msg_idx, is_sampled=True)
emit_special(self._tool_sep, msg_idx, is_sampled=True)
emit_text(f"{name}\n```json\n{args_str}\n```", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_end, msg_idx, is_sampled=True)
emit_special(self._eos, msg_idx)
# ``<|end▁of▁sentence|>`` is the model's stop signal — it
# samples this to end its turn, so it is part of the sampled
# stream.
emit_special(self._eos, msg_idx, is_sampled=True)
# ------------------------------------------------------------------
# Tool (tool-response) rendering
@@ -392,6 +438,9 @@ class DeepSeekV3Renderer:
emit_special,
emit_text,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
@@ -402,11 +451,11 @@ class DeepSeekV3Renderer:
content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
if not prev_is_tool:
emit_special(self._tool_outputs_begin, msg_idx)
emit_special(self._tool_outputs_begin, msg_idx, is_sampled=False)
emit_special(self._tool_output_begin, msg_idx)
emit_text(str(content), msg_idx)
emit_special(self._tool_output_end, msg_idx)
emit_special(self._tool_output_begin, msg_idx, is_sampled=False)
emit_text(str(content), msg_idx, is_sampled=False)
emit_special(self._tool_output_end, msg_idx, is_sampled=False)
if not next_is_tool:
emit_special(self._tool_outputs_end, msg_idx)
emit_special(self._tool_outputs_end, msg_idx, is_sampled=False)
+13 -3
View File
@@ -143,7 +143,12 @@ class DefaultRenderer:
token_ids = full_ids
message_indices.extend([-1] * len(gen_tokens))
return RenderedTokens(token_ids=token_ids, message_indices=message_indices)
message_roles = [m.get("role") or "" for m in messages]
return RenderedTokens(
token_ids=token_ids,
message_indices=message_indices,
message_roles=message_roles,
)
def _apply(self, messages, *, tools=None, add_generation_prompt=False) -> list[int]:
kwargs = dict(self._chat_template_kwargs)
@@ -167,14 +172,19 @@ class DefaultRenderer:
messages, tools=tools, add_generation_prompt=add_generation_prompt
)
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — DefaultRenderer relies on configured tool_parser, schema not consulted here
) -> ParsedResponse:
# 1. Extract tool calls while we still have token ids (most formats
# use special-token delimiters, so id-level matching is reliable).
if self._tool_parser is not None:
content_ids, tool_calls = self._tool_parser.extract(list(token_ids))
else:
content_ids = list(token_ids)
tool_calls = None
tool_calls = []
# 2. Decode (keep special tokens so a downstream reasoning parser can
# still see things like <think>/</think> when they're tokens).
+106 -45
View File
@@ -127,28 +127,31 @@ class GLM45Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
# ── Prefix ──────────────────────────────────────────────────
emit_special(self._gmask, -1)
emit_special(self._sop, -1)
emit_special(self._gmask, -1, is_sampled=False)
emit_special(self._sop, -1, is_sampled=False)
# ── Tools in system prompt ──────────────────────────────────
if tools:
emit_special(self._system, -1)
emit_special(self._system, -1, is_sampled=False)
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
tool_text += _TOOLS_FOOTER
emit_text(tool_text, -1)
emit_text(tool_text, -1, is_sampled=False)
# ── Compute last_user_index ─────────────────────────────────
last_ui = self._last_user_index(messages)
@@ -159,15 +162,15 @@ class GLM45Renderer:
content = self._visible_text(msg.get("content"))
if role == "system":
emit_special(self._system, i)
emit_text("\n" + content, i)
emit_special(self._system, i, is_sampled=False)
emit_text("\n" + content, i, is_sampled=False)
elif role == "user":
emit_special(self._user, i)
emit_special(self._user, i, is_sampled=False)
user_text = "\n" + content
if not self._enable_thinking and not content.endswith("/nothink"):
user_text += "/nothink"
emit_text(user_text, i)
emit_text(user_text, i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -193,13 +196,18 @@ class GLM45Renderer:
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._assistant, -1)
emit_special(self._assistant, -1, is_sampled=False)
if not self._enable_thinking:
emit_text("\n", -1)
emit_special(self._think, -1)
emit_special(self._think_end, -1)
emit_text("\n", -1, is_sampled=False)
emit_special(self._think, -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
@@ -214,7 +222,12 @@ class GLM45Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
return parse_glm(
self._tokenizer,
token_ids,
@@ -227,6 +240,7 @@ class GLM45Renderer:
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]:
@@ -260,12 +274,29 @@ class GLM45Renderer:
last_prev = previous_ids[-1]
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
ext.extend(self._encode(text))
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
for i, msg in enumerate(new_messages):
role = msg.get("role")
@@ -297,7 +328,13 @@ class GLM45Renderer:
emit_special(self._think, -1)
emit_special(self._think_end, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
message_roles=[m.get("role") or "" for m in new_messages],
)
def _render_assistant(
self,
@@ -322,24 +359,37 @@ class GLM45Renderer:
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._assistant, msg_idx)
# ``<|assistant|>\n`` is template-injected scaffolding — at
# inference the chat template emits these as the generation
# prompt and the model never samples them. Everything after
# (think block + content + tool calls) is the model-sampled
# portion.
#
# GLM-4.5 does NOT emit an explicit per-turn close token inside
# the assistant message; the next message's role marker
# (``<|user|>`` / ``<|observation|>`` / ``<|endoftext|>``) acts
# as the stop signal at inference, and those tokens are
# attributed to the *next* message (or are absent on the final
# turn). So no sampled stop-signal token lives inside this
# assistant span — content / think / tool_calls carry the
# is_sampled=True signal.
emit_special(self._assistant, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
if (msg_idx > last_user_index or preserve_thinking) and reasoning_content:
emit_text("\n", msg_idx)
emit_special(self._think, msg_idx)
emit_text(reasoning_content.strip(), msg_idx)
emit_special(self._think_end, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_text(reasoning_content.strip(), msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
else:
emit_text("\n", msg_idx)
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
# Tool calls — keep content + \n contiguous to preserve BPE merges
tool_calls = msg.get("tool_calls") or []
if content.strip() and tool_calls:
emit_text("\n" + content.strip() + "\n", msg_idx)
emit_text("\n" + content.strip() + "\n", msg_idx, is_sampled=True)
elif content.strip():
emit_text("\n" + content.strip(), msg_idx)
emit_text("\n" + content.strip(), msg_idx, is_sampled=True)
for tc in tool_calls:
func = tc.get("function") or tc
@@ -347,9 +397,9 @@ class GLM45Renderer:
arguments = func.get("arguments", {})
if not content.strip():
emit_text("\n", msg_idx)
emit_special(self._tool_call_tok, msg_idx)
emit_text(name + "\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_tok, msg_idx, is_sampled=True)
emit_text(name + "\n", msg_idx, is_sampled=True)
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
@@ -359,18 +409,22 @@ class GLM45Renderer:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
emit_special(self._arg_key, msg_idx)
emit_text(arg_name, msg_idx)
emit_special(self._arg_key_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._arg_value, msg_idx)
emit_special(self._arg_key, msg_idx, is_sampled=True)
emit_text(arg_name, msg_idx, is_sampled=True)
emit_special(self._arg_key_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._arg_value, msg_idx, is_sampled=True)
if isinstance(arg_value, str):
emit_text(arg_value, msg_idx)
emit_text(arg_value, msg_idx, is_sampled=True)
else:
emit_text(json.dumps(arg_value, ensure_ascii=False), msg_idx)
emit_special(self._arg_value_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._tool_call_end_tok, msg_idx)
emit_text(
json.dumps(arg_value, ensure_ascii=False),
msg_idx,
is_sampled=True,
)
emit_special(self._arg_value_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, msg_idx, is_sampled=True)
def _render_tool(
self,
@@ -381,9 +435,16 @@ class GLM45Renderer:
emit_special,
emit_text,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
if not prev_is_tool:
emit_special(self._observation, msg_idx)
emit_special(self._observation, msg_idx, is_sampled=False)
emit_text("\n<tool_response>\n" + content + "\n</tool_response>", msg_idx)
emit_text(
"\n<tool_response>\n" + content + "\n</tool_response>",
msg_idx,
is_sampled=False,
)
+107 -42
View File
@@ -142,28 +142,33 @@ class GLM5Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
# ── Prefix ──────────────────────────────────────────────────
emit_special(self._gmask, -1)
emit_special(self._sop, -1)
# ``[gMASK]<sop>`` is unconditional template scaffolding at the
# very start of the stream — the model never samples these.
emit_special(self._gmask, -1, is_sampled=False)
emit_special(self._sop, -1, is_sampled=False)
# ── Tools in system prompt ──────────────────────────────────
if tools:
emit_special(self._system, -1)
emit_special(self._system, -1, is_sampled=False)
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += self._format_tool_spec(tool) + "\n"
tool_text += _TOOLS_FOOTER
emit_text(tool_text, -1)
emit_text(tool_text, -1, is_sampled=False)
# ── Compute last_user_index ─────────────────────────────────
last_ui = self._last_user_index(messages)
@@ -174,12 +179,12 @@ class GLM5Renderer:
content = self._visible_text(msg.get("content"))
if role == "system":
emit_special(self._system, i)
emit_text(content, i)
emit_special(self._system, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
elif role == "user":
emit_special(self._user, i)
emit_text(content, i)
emit_special(self._user, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -204,14 +209,22 @@ class GLM5Renderer:
)
# ── Generation prompt ───────────────────────────────────────
# Gen prompt tokens are what the chat template prepends before
# sampling starts — the model continues from these, never emits
# them. Always is_sampled=False.
if add_generation_prompt:
emit_special(self._assistant, -1)
emit_special(self._assistant, -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1)
emit_special(self._think, -1, is_sampled=False)
else:
emit_special(self._think_end, -1)
emit_special(self._think_end, -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
@@ -226,7 +239,12 @@ class GLM5Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
return parse_glm(
self._tokenizer,
token_ids,
@@ -239,6 +257,7 @@ class GLM5Renderer:
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]:
@@ -276,12 +295,29 @@ class GLM5Renderer:
last_prev = previous_ids[-1]
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
ext.extend(self._encode(text))
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
for i, msg in enumerate(new_messages):
role = msg.get("role")
@@ -314,7 +350,13 @@ class GLM5Renderer:
else:
emit_special(self._think_end, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
message_roles=[m.get("role") or "" for m in new_messages],
)
def _render_assistant(
self,
@@ -339,7 +381,12 @@ class GLM5Renderer:
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._assistant, msg_idx)
# ``<|assistant|>`` is template-injected: the chat template emits
# it as the generation prompt at inference, and the model never
# samples it. Same for the ``<think>`` open / standalone
# ``</think>`` separator that the template wraps around the
# assistant body — see the per-branch comments below.
emit_special(self._assistant, msg_idx, is_sampled=False)
# Chat-template default: keep ``<think>`` only on the in-flight cycle
# (post-last-user). Past-cycle assistants drop their reasoning.
@@ -352,19 +399,30 @@ class GLM5Renderer:
) and reasoning_content
if include_thinking:
emit_special(self._think, msg_idx)
emit_text(reasoning_content.strip(), msg_idx)
emit_special(self._think_end, msg_idx)
# ``<think>`` matches the gen-prompt's trailing token at
# inference (gen prompt = ``<|assistant|><think>``), so it's
# template-injected scaffolding. The reasoning text and the
# closing ``</think>`` are what the model actually samples.
emit_special(self._think, msg_idx, is_sampled=False)
emit_text(reasoning_content.strip(), msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
elif self.empty_think_on_last_assistant and msg_idx > last_user_index:
# GLM-5.1: wrap the last assistant with an empty <think></think>
# even without reasoning, matching the Jinja template.
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
# even without reasoning, matching the Jinja template. With
# ``enable_thinking=True`` the gen prompt already includes
# ``<think>``; the model then samples ``</think>`` to close an
# empty think block. So ``<think>`` is scaffolding,
# ``</think>`` is sampled.
emit_special(self._think, msg_idx, is_sampled=False)
emit_special(self._think_end, msg_idx, is_sampled=True)
else:
emit_special(self._think_end, msg_idx)
# Lone ``</think>`` separator the template injects when no
# reasoning is rendered (historical assistants, GLM-5 default
# with no thinking). Not sampled.
emit_special(self._think_end, msg_idx, is_sampled=False)
if content.strip():
emit_text(content.strip(), msg_idx)
emit_text(content.strip(), msg_idx, is_sampled=True)
# Tool calls (directly after content, no newlines)
tool_calls = msg.get("tool_calls") or []
@@ -373,8 +431,8 @@ class GLM5Renderer:
name = func.get("name", "")
arguments = func.get("arguments", {})
emit_special(self._tool_call_tok, msg_idx)
emit_text(name, msg_idx)
emit_special(self._tool_call_tok, msg_idx, is_sampled=True)
emit_text(name, msg_idx, is_sampled=True)
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
@@ -384,16 +442,20 @@ class GLM5Renderer:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
emit_special(self._arg_key, msg_idx)
emit_text(arg_name, msg_idx)
emit_special(self._arg_key_end, msg_idx)
emit_special(self._arg_value, msg_idx)
emit_special(self._arg_key, msg_idx, is_sampled=True)
emit_text(arg_name, msg_idx, is_sampled=True)
emit_special(self._arg_key_end, msg_idx, is_sampled=True)
emit_special(self._arg_value, msg_idx, is_sampled=True)
if isinstance(arg_value, str):
emit_text(arg_value, msg_idx)
emit_text(arg_value, msg_idx, is_sampled=True)
else:
emit_text(json.dumps(arg_value, ensure_ascii=False), msg_idx)
emit_special(self._arg_value_end, msg_idx)
emit_special(self._tool_call_end_tok, msg_idx)
emit_text(
json.dumps(arg_value, ensure_ascii=False),
msg_idx,
is_sampled=True,
)
emit_special(self._arg_value_end, msg_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, msg_idx, is_sampled=True)
def _render_tool(
self,
@@ -404,14 +466,17 @@ class GLM5Renderer:
emit_special,
emit_text,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
if not prev_is_tool:
emit_special(self._observation, msg_idx)
emit_special(self._observation, msg_idx, is_sampled=False)
emit_special(self._tool_response_tok, msg_idx)
emit_text(content, msg_idx)
emit_special(self._tool_response_end_tok, msg_idx)
emit_special(self._tool_response_tok, msg_idx, is_sampled=False)
emit_text(content, msg_idx, is_sampled=False)
emit_special(self._tool_response_end_tok, msg_idx, is_sampled=False)
class GLM51Renderer(GLM5Renderer):
+81 -15
View File
@@ -198,10 +198,45 @@ class GptOssRenderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit(ids: list[int], msg_idx: int) -> None:
def emit(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_harmony_message(
hm_ids: list[int], msg_idx: int, *, is_assistant: bool
) -> None:
"""Emit one harmony-rendered message, splitting its tokens into
template scaffolding vs model-sampled content.
Harmony per-message layout:
<|start|> role [' to=' recipient] [<|channel|> name] <|message|>
<body...>
<|end|> | <|return|> | <|call|>
Everything up to and including ``<|message|>`` is the
generation-prompt header the template injects before the
model starts sampling. For assistant turns the body and the
terminator (``<|end|>`` / ``<|return|>`` / ``<|call|>``) are
what the model actually produces, so they are
``is_sampled=True``. For non-assistant turns (user, system,
developer, tool) the whole message is conversation history
the model never samples — every token is
``is_sampled=False``.
"""
try:
msg_marker = hm_ids.index(self._message)
except ValueError:
# Defensive: a harmony message without <|message|> is
# malformed. Treat the whole thing as scaffolding.
emit(hm_ids, msg_idx, is_sampled=False)
return
header = hm_ids[: msg_marker + 1]
body = hm_ids[msg_marker + 1 :]
emit(header, msg_idx, is_sampled=False)
emit(body, msg_idx, is_sampled=is_assistant)
# ── Build harmony prefix (system + developer) ───────────────────
# When tools are present, harmony's conversation-level renderer
@@ -248,15 +283,17 @@ class GptOssRenderer:
# Attribute the whole prefix block to first_system_idx if the
# caller supplied a system message (so its content has *some*
# caller-relative attribution); otherwise to -1 (pure scaffolding).
# The whole prefix is pure template scaffolding — never sampled.
prefix_origin = first_system_idx if first_system_idx is not None else -1
emit(prefix_tokens, prefix_origin)
emit(prefix_tokens, prefix_origin, is_sampled=False)
# ── Iterate the rest of the messages ────────────────────────────
last_idx = len(messages) - 1
for i, msg in enumerate(messages):
if i == first_system_idx:
continue # already emitted as developer
preserve_thinking = msg.get("role") == "assistant" and (
is_assistant = msg.get("role") == "assistant"
preserve_thinking = is_assistant and (
should_preserve_past_thinking(
messages,
i,
@@ -267,13 +304,15 @@ class GptOssRenderer:
for hm in self._to_harmony_messages(
msg, preserve_thinking=preserve_thinking
):
emit(self._enc.render(hm), i)
emit_harmony_message(self._enc.render(hm), i, is_assistant=is_assistant)
# When the conversation ends on an assistant final-channel turn,
# ``apply_chat_template`` (and ``render_conversation_for_training``)
# close it with ``<|return|>`` instead of ``<|end|>`` to mark the
# final assistant turn as terminal. Per-message rendering always
# uses ``<|end|>``, so patch it here when applicable.
# uses ``<|end|>``, so patch it here when applicable. The sampled
# bit on the terminator slot stays True — both ``<|end|>`` and
# ``<|return|>`` are stop signals the model emits.
if (
not add_generation_prompt
and last_idx >= 0
@@ -285,14 +324,20 @@ class GptOssRenderer:
tokens[-1] = self._return
# ── Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
# Pure template scaffolding the model continues from — never sampled.
if add_generation_prompt:
emit([self._start], -1)
emit(self._encode("assistant"), -1)
emit([self._channel], -1)
emit(self._encode("analysis"), -1)
emit([self._message], -1)
emit([self._start], -1, is_sampled=False)
emit(self._encode("assistant"), -1, is_sampled=False)
emit([self._channel], -1, is_sampled=False)
emit(self._encode("analysis"), -1, is_sampled=False)
emit([self._message], -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
@@ -307,7 +352,12 @@ class GptOssRenderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — harmony args land in a JSON object, schema not needed
) -> ParsedResponse:
return parse_gpt_oss(
self._tokenizer,
token_ids,
@@ -353,22 +403,38 @@ class GptOssRenderer:
if previous_ids is None:
return None
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False``). The harmony encoder
# renders each ``new_messages[i]`` as a single block, so every
# token in that block carries index ``i``; the trailing
# generation prompt uses ``-1``.
ext: list[int] = []
for msg in new_messages:
ext_indices: list[int] = []
for i, msg in enumerate(new_messages):
role = msg.get("role")
if role not in ("tool", "user", "system", "developer"):
return None
for hm in self._to_harmony_messages(msg):
ext.extend(self._enc.render(hm))
ids = self._enc.render(hm)
ext.extend(ids)
ext_indices.extend([i] * len(ids))
# Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
gen_before = len(ext)
ext.append(self._start)
ext.extend(self._encode("assistant"))
ext.append(self._channel)
ext.extend(self._encode("analysis"))
ext.append(self._message)
ext_indices.extend([-1] * (len(ext) - gen_before))
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
message_roles=[m.get("role") or "" for m in new_messages],
)
# ── message conversion ───────────────────────────────────────────────────
+114 -66
View File
@@ -165,17 +165,20 @@ class KimiK2Renderer:
token_ids: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
token_ids.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
token_ids.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
# Compute last non-tool-call assistant index to determine thinking preservation
last_plain_assistant_idx = -1
@@ -205,29 +208,29 @@ class KimiK2Renderer:
oi = orig_idx(i)
if role == "system":
emit_special(self._im_system, oi)
emit_text("system", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
emit_special(self._im_system, oi, is_sampled=False)
emit_text("system", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
# Jinja emits a literal newline only after the auto-injected
# system's <|im_end|> (see _ensure_system_message's contract).
if i == auto_system_idx:
emit_text("\n", oi)
emit_text("\n", oi, is_sampled=False)
elif role == "tool_declare":
emit_special(self._im_system, oi)
emit_text("tool_declare", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
emit_special(self._im_system, oi, is_sampled=False)
emit_text("tool_declare", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
elif role == "user":
emit_special(self._im_user, oi)
emit_text("user", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
emit_special(self._im_user, oi, is_sampled=False)
emit_text("user", oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
elif role == "assistant":
# Kimi strips reasoning from historical assistant turns and
@@ -251,20 +254,27 @@ class KimiK2Renderer:
)
else:
# Unknown role: use system-style formatting
emit_special(self._im_system, oi)
emit_text(role, oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
# Unknown role: use system-style formatting. Not a sampled
# assistant turn — every token is template-injected from the
# caller's POV, so is_sampled=False across the whole emission.
emit_special(self._im_system, oi, is_sampled=False)
emit_text(role, oi, is_sampled=False)
emit_special(self._im_middle, oi, is_sampled=False)
emit_text(content, oi, is_sampled=False)
emit_special(self._im_end, oi, is_sampled=False)
# Generation prompt
if add_generation_prompt:
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
return RenderedTokens(token_ids=token_ids, message_indices=indices)
return RenderedTokens(
token_ids=token_ids,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
@@ -279,7 +289,12 @@ class KimiK2Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — section-JSON wire format quotes strings, schema not needed
) -> ParsedResponse:
return parse_kimi_k2(
self._tokenizer,
token_ids,
@@ -319,12 +334,29 @@ class KimiK2Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
ext.extend(self._encode(text))
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
for i, msg in enumerate(new_messages):
role = msg.get("role")
@@ -344,17 +376,17 @@ class KimiK2Renderer:
content = "".join(parts)
if role == "user":
emit_special(self._im_user, i)
emit_text("user", i)
emit_special(self._im_middle, i)
emit_text(content, i)
emit_special(self._im_end, i)
emit_special(self._im_user, i, is_sampled=False)
emit_text("user", i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
elif role == "system":
emit_special(self._im_system, i)
emit_text("system", i)
emit_special(self._im_middle, i)
emit_text(content, i)
emit_special(self._im_end, i)
emit_special(self._im_system, i, is_sampled=False)
emit_text("system", i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
emit_text(content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
elif role == "tool":
self._render_tool(
msg, i, content, emit_special=emit_special, emit_text=emit_text
@@ -363,11 +395,17 @@ class KimiK2Renderer:
return None
# Generation prompt.
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
message_roles=[m.get("role") or "" for m in new_messages],
)
def _render_assistant(
self,
@@ -379,9 +417,14 @@ class KimiK2Renderer:
emit_special,
emit_text,
) -> None:
emit_special(self._im_assistant, msg_idx)
emit_text("assistant", msg_idx)
emit_special(self._im_middle, msg_idx)
# ``<|im_assistant|>assistant<|im_middle|>`` is template-injected
# scaffolding — at inference the chat template emits these as the
# generation prompt and the model never samples them. Marking the
# role tag as ``is_sampled=False`` keeps the SFT loss mask aligned
# with what the model would actually have produced.
emit_special(self._im_assistant, msg_idx, is_sampled=False)
emit_text("assistant", msg_idx, is_sampled=False)
emit_special(self._im_middle, msg_idx, is_sampled=False)
# Kimi K2's Jinja template has no reasoning-content support: the
# assistant turn renders its ``content`` verbatim, including any
@@ -389,12 +432,12 @@ class KimiK2Renderer:
# ``reasoning_content`` field is dropped (the template never reads
# it). ``is_last_turn`` is unused here for the same reason.
_ = is_last_turn
emit_text(content, msg_idx)
emit_text(content, msg_idx, is_sampled=True)
# Tool calls
tool_calls = msg.get("tool_calls") or []
if tool_calls:
emit_special(self._tool_calls_section_begin, msg_idx)
emit_special(self._tool_calls_section_begin, msg_idx, is_sampled=True)
for tc in tool_calls:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
@@ -408,14 +451,16 @@ class KimiK2Renderer:
# caller to provide an id in ``functions.{name}:{idx}`` form
# (that's where the Kimi parser recovers the function name).
tc_id = tc.get("id") or ""
emit_special(self._tool_call_begin, msg_idx)
emit_text(tc_id, msg_idx)
emit_special(self._tool_call_argument_begin, msg_idx)
emit_text(args_str, msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_section_end, msg_idx)
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text(tc_id, msg_idx, is_sampled=True)
emit_special(self._tool_call_argument_begin, msg_idx, is_sampled=True)
emit_text(args_str, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_section_end, msg_idx, is_sampled=True)
emit_special(self._im_end, msg_idx)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream.
emit_special(self._im_end, msg_idx, is_sampled=True)
def _render_tool(
self,
@@ -426,12 +471,15 @@ class KimiK2Renderer:
emit_special,
emit_text,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
name = msg.get("name") or "tool"
tool_call_id = msg.get("tool_call_id") or ""
emit_special(self._im_system, msg_idx)
emit_text(name, msg_idx)
emit_special(self._im_middle, msg_idx)
emit_text(f"## Return of {tool_call_id}\n", msg_idx)
emit_text(content, msg_idx)
emit_special(self._im_end, msg_idx)
emit_special(self._im_system, msg_idx, is_sampled=False)
emit_text(name, msg_idx, is_sampled=False)
emit_special(self._im_middle, msg_idx, is_sampled=False)
emit_text(f"## Return of {tool_call_id}\n", msg_idx, is_sampled=False)
emit_text(content, msg_idx, is_sampled=False)
emit_special(self._im_end, msg_idx, is_sampled=False)
+257 -105
View File
@@ -31,13 +31,16 @@ from renderers.base import (
Message,
MultiModalData,
ParsedResponse,
ParsedToolCall,
PlaceholderRange,
RenderedTokens,
ToolCallParseStatus,
ToolSpec,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.parsing import parse_kimi_k2_section
from renderers.qwen3_vl import (
_image_hash,
_is_image_part,
@@ -420,12 +423,27 @@ def _parse_kimi_k2_response(
stop_ids: set[int],
think_open_ids: list[int],
think_close_ids: list[int],
tool_calls_section_begin_id: int | None,
tool_calls_section_end_id: int | None,
tool_call_begin_id: int | None,
tool_call_argument_begin_id: int | None,
tool_call_end_id: int | None,
) -> ParsedResponse:
"""Parse Kimi K2/K2.5 completion tokens.
Strips the stop token, decodes to text, then extracts:
- reasoning from ``<think>...</think>`` blocks
- tool calls from ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``
Primary path: walk token IDs via :func:`parse_kimi_k2_section`. That gives
every ``ParsedToolCall`` a ``token_span`` pointing back into the
(stop-stripped) input — what the trainer needs for selective loss masking.
Fallback path: regex on decoded text. Only used when none of the section
delimiters appear as special tokens, which in practice means the model
emitted the literal ``<|tool_call_section_begin|>`` string (the singular
variant is *not* in the K2.5 special-token vocab — confirmed by tokenizer
probe). Spans stay ``None`` here since text positions don't cheaply map
back to token offsets across BPE.
``<think>...</think>`` is always text-extracted from the content slice
(K2.5 emits them as plain text, not special tokens).
"""
# Strip stop token
ids = list(token_ids)
@@ -434,13 +452,79 @@ def _parse_kimi_k2_response(
ids = ids[:i]
break
# Decode all tokens (including any special tokens that are text-like)
text = tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
# Token-ID path — produces spans. Only run if every relevant special
# token resolved at init (i.e. is in the tokenizer's vocab).
tool_calls: list[ParsedToolCall] = []
have_special_tokens = (
tool_calls_section_begin_id is not None
and tool_calls_section_end_id is not None
and tool_call_begin_id is not None
and tool_call_argument_begin_id is not None
and tool_call_end_id is not None
)
if have_special_tokens:
content_ids, tool_calls = parse_kimi_k2_section(
tokenizer,
ids,
tool_calls_section_begin_ids={tool_calls_section_begin_id},
tool_calls_section_end_ids={tool_calls_section_end_id},
tool_call_begin_id=tool_call_begin_id,
tool_call_argument_begin_id=tool_call_argument_begin_id,
tool_call_end_id=tool_call_end_id,
)
text = (
tokenizer.decode(content_ids, skip_special_tokens=False)
if content_ids
else ""
)
else:
text = tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
# Extract reasoning from <think>...</think>. Partition on <think> first so
# any tokens BEFORE the open tag (e.g. the assistant role tag, when the
# caller slices the completion to include the prompt's gen-prompt-equivalent)
# don't leak into reasoning_content.
# Fallback path: model emitted literal-text section delimiters (singular
# variant) rather than special tokens. Spans unavailable here.
if not tool_calls:
tc_match = _TOOL_CALLS_SECTION_RE.search(text)
if tc_match:
text = text[: tc_match.start()]
tool_section = (
tc_match.group(1)
if tc_match.group(1) is not None
else tc_match.group(2)
)
for m in _TOOL_CALL_RE.finditer(tool_section):
tool_id = m.group(1).strip()
args_str = m.group(2).strip()
name_part = tool_id.split(":", 1)[0]
func_name = (
name_part.split(".", 1)[1] if "." in name_part else name_part
)
arguments: dict[str, Any] | str
invalid_json = False
try:
arguments = json.loads(args_str)
except json.JSONDecodeError:
arguments = args_str
invalid_json = True
if not func_name:
status = ToolCallParseStatus.MISSING_NAME
elif invalid_json:
status = ToolCallParseStatus.INVALID_JSON
else:
status = ToolCallParseStatus.OK
tool_calls.append(
ParsedToolCall(
raw=m.group(0),
name=func_name or None,
arguments=arguments,
status=status,
id=tool_id or None,
)
)
# Extract reasoning from <think>...</think> in the content text. Partition
# on <think> first so any tokens BEFORE the open tag (e.g. the assistant
# role tag, when the caller slices the completion to include the prompt's
# gen-prompt-equivalent) don't leak into reasoning_content.
reasoning: str | None = None
if "<think>" in text:
_, _, after_open = text.partition("<think>")
@@ -449,11 +533,12 @@ def _parse_kimi_k2_response(
reasoning = reasoning_raw.strip("\n") or None
text = text.strip("\n")
else:
# Truncated reasoning (no closing tag)
# Truncated reasoning (no closing tag) — discard any partial
# tool-call attempts since the model never finished thinking.
return ParsedResponse(
content="",
reasoning_content=after_open.strip() or None,
tool_calls=None,
tool_calls=[],
)
elif "</think>" in text:
# Sampler stripped the prefilled <think> open tag — see
@@ -463,35 +548,6 @@ def _parse_kimi_k2_response(
reasoning = before.strip("\n") or None
text = after.strip("\n")
# Extract tool calls section
tool_calls: list[dict[str, Any]] | None = None
tc_match = _TOOL_CALLS_SECTION_RE.search(text)
if tc_match:
text = text[: tc_match.start()]
tool_section = (
tc_match.group(1) if tc_match.group(1) is not None else tc_match.group(2)
)
parsed_calls = []
for m in _TOOL_CALL_RE.finditer(tool_section):
tool_id = m.group(1).strip()
args_str = m.group(2).strip()
# Extract function name from "functions.name:index" format
name_part = tool_id.split(":", 1)[0]
func_name = name_part.split(".", 1)[1] if "." in name_part else name_part
try:
arguments = json.loads(args_str)
except json.JSONDecodeError:
arguments = args_str # preserve raw string if invalid JSON
parsed_calls.append(
{
"type": "function",
"id": tool_id,
"function": {"name": func_name, "arguments": arguments},
}
)
if parsed_calls:
tool_calls = parsed_calls
return ParsedResponse(
content=text.strip(),
reasoning_content=reasoning.strip() if reasoning else None,
@@ -692,22 +748,25 @@ class KimiK25Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
mm_hashes: dict[str, list[str]] = {}
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
mm_items: dict[str, list[dict[str, Any]]] = {}
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_image(part: dict[str, Any], msg_idx: int) -> None:
def emit_image(part: dict[str, Any], msg_idx: int, *, is_sampled: bool) -> None:
"""Emit Kimi K2.5's image wrap and accumulate ``mm_data``.
Template-equivalent expansion per image:
@@ -722,13 +781,13 @@ class KimiK25Renderer:
text, or the ``<|im_end|>`` close).
"""
_, out, _num_patches, h = self._process_image(part)
emit_special(self._media_begin, msg_idx)
emit_text("image", msg_idx)
emit_special(self._media_content, msg_idx)
emit_special(self._media_begin, msg_idx, is_sampled=is_sampled)
emit_text("image", msg_idx, is_sampled=is_sampled)
emit_special(self._media_content, msg_idx, is_sampled=is_sampled)
offset = len(tokens)
emit_special(self._media_pad, msg_idx)
emit_special(self._media_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._media_pad, msg_idx, is_sampled=is_sampled)
emit_special(self._media_end, msg_idx, is_sampled=is_sampled)
emit_text("\n", msg_idx, is_sampled=is_sampled)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=1)
@@ -750,26 +809,29 @@ class KimiK25Renderer:
# fires when tools are present. Match that with our own TS encoder.
if tools:
tools_ts = _encode_tools_typescript(tools)
emit_special(self._im_system, -1)
emit_text("tool_declare", -1)
emit_special(self._im_middle, -1)
emit_text(tools_ts, -1)
emit_special(self._im_end, -1)
emit_special(self._im_system, -1, is_sampled=False)
emit_text("tool_declare", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
emit_text(tools_ts, -1, is_sampled=False)
emit_special(self._im_end, -1, is_sampled=False)
# ── Iterate messages ─────────────────────────────────────────
for i, msg in enumerate(messages):
role = msg.get("role", "")
# set_roles: role tag + role_name + <|im_middle|>
# set_roles: role tag + role_name + <|im_middle|> — these are
# template-injected scaffolding the model never samples (the
# generation prompt emits them at inference for assistants;
# user / system / tool roles are conversation history).
if role == "user":
emit_special(self._im_user, i)
emit_special(self._im_user, i, is_sampled=False)
elif role == "assistant":
emit_special(self._im_assistant, i)
emit_special(self._im_assistant, i, is_sampled=False)
else:
emit_special(self._im_system, i)
emit_special(self._im_system, i, is_sampled=False)
role_name = msg.get("name") or role
emit_text(role_name, i)
emit_special(self._im_middle, i)
emit_text(role_name, i, is_sampled=False)
emit_special(self._im_middle, i, is_sampled=False)
# Body
if role == "assistant":
@@ -788,6 +850,13 @@ class KimiK25Renderer:
emit_special=emit_special,
emit_text=emit_text,
)
# ``<|im_end|>`` is the model's stop signal — it samples
# this to end its turn, so it is part of the sampled
# stream. Kimi K2.5 has no inter-turn ``\n`` separator
# (unlike Qwen3), so the turn-close token is the last
# sampled token.
emit_special(self._im_end, i, is_sampled=True)
continue
elif role == "tool":
self._render_tool_body(
msg,
@@ -795,9 +864,12 @@ class KimiK25Renderer:
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
emit_image=emit_image,
)
elif msg.get("content") is not None:
# User / other content branches — images allowed.
# User / other content branches — images allowed. All
# non-assistant content is conversation history, never
# sampled by the model.
self._emit_content(
msg.get("content"),
i,
@@ -805,21 +877,22 @@ class KimiK25Renderer:
emit_text,
emit_ids,
emit_image=emit_image,
is_sampled=False,
)
emit_special(self._im_end, i)
emit_special(self._im_end, i, is_sampled=False)
# ── Generation prompt ────────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
emit_special(self._im_assistant, -1, is_sampled=False)
emit_text("assistant", -1, is_sampled=False)
emit_special(self._im_middle, -1, is_sampled=False)
if self._enable_thinking:
# Prefill open <think> tag to trigger thinking mode
emit_text("<think>", -1)
emit_text("<think>", -1, is_sampled=False)
else:
# Empty <think></think> to disable thinking
emit_text("<think></think>", -1)
emit_text("<think></think>", -1, is_sampled=False)
mm_data: MultiModalData | None = None
if mm_hashes or mm_placeholders or mm_items:
@@ -832,6 +905,8 @@ class KimiK25Renderer:
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
multi_modal_data=mm_data,
)
@@ -848,22 +923,44 @@ class KimiK25Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — section-JSON wire format quotes strings, schema not needed
) -> ParsedResponse:
stop_ids: set[int] = {self._im_end}
if self._endoftext is not None:
stop_ids.add(self._endoftext)
# Restore the synthetic <think> prefill if it was stripped by the sampler
# Restore the synthetic <think> prefill if it was stripped by the
# sampler. ``parse`` then walks ``normalized``, so any token_span we
# emit is in the *normalized* frame. We track the prepend offset and
# shift spans back so they refer to the caller's ``token_ids``.
normalized = self._normalize_response_tokens(list(token_ids))
prepend_offset = len(normalized) - len(token_ids)
return _parse_kimi_k2_response(
parsed = _parse_kimi_k2_response(
self._tokenizer,
normalized,
stop_ids=stop_ids,
think_open_ids=self._think_open_ids,
think_close_ids=self._think_close_ids,
tool_calls_section_begin_id=self._tool_calls_section_begin,
tool_calls_section_end_id=self._tool_calls_section_end,
tool_call_begin_id=self._tool_call_begin,
tool_call_argument_begin_id=self._tool_call_argument_begin,
tool_call_end_id=self._tool_call_end,
)
if prepend_offset:
for tc in parsed.tool_calls:
if tc.token_span is not None:
start, end = tc.token_span
tc.token_span = (start - prepend_offset, end - prepend_offset)
return parsed
def get_stop_token_ids(self) -> list[int]:
stop = [self._im_end]
if self._endoftext is not None:
@@ -899,30 +996,52 @@ class KimiK25Renderer:
return None
# Seed combined-token list with prior turn so placeholder offsets
# are absolute in the bridged sequence.
# are absolute in the bridged sequence. Parallel
# ``indices``/``sampled`` are seeded with ``-1``/``False`` for the
# prior portion — the bridge has no attribution info for
# ``previous_ids``. Bridge-added tokens get proper ``msg_idx``
# (relative to ``new_messages``) and uniformly ``False``
# ``sampled``: nothing the bridge emits was model-sampled.
tokens: list[int] = list(previous_ids)
indices: list[int] = [-1] * len(previous_ids)
sampled: list[bool] = [False] * len(previous_ids)
new_hashes: dict[str, list[str]] = {}
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
tokens.extend(self._encode(text))
def emit_ids(ids: list[int], _msg_idx: int = -1) -> None:
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_image(part: dict[str, Any], _msg_idx: int = -1) -> None:
def emit_ids(
ids: list[int], msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_image(
part: dict[str, Any], msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
_, out, _num_patches, h = self._process_image(part)
emit_special(self._media_begin)
emit_text("image")
emit_special(self._media_content)
emit_special(self._media_begin, msg_idx)
emit_text("image", msg_idx)
emit_special(self._media_content, msg_idx)
offset = len(tokens)
emit_special(self._media_pad)
emit_special(self._media_end)
emit_text("\n")
emit_special(self._media_pad, msg_idx)
emit_special(self._media_end, msg_idx)
emit_text("\n", msg_idx)
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=1)
@@ -956,6 +1075,7 @@ class KimiK25Renderer:
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
emit_image=emit_image,
)
elif msg.get("content") is not None:
self._emit_content(
@@ -965,6 +1085,7 @@ class KimiK25Renderer:
emit_text,
emit_ids,
emit_image=emit_image,
is_sampled=False,
)
emit_special(self._im_end, i)
@@ -1001,8 +1122,14 @@ class KimiK25Renderer:
for modality, vals in new_items.items():
merged_items.setdefault(modality, []).extend(vals)
bridge_roles = [m.get("role") or "" for m in new_messages]
if not (merged_hashes or merged_placeholders or merged_items):
return RenderedTokens(token_ids=tokens)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=bridge_roles,
)
mm_data = MultiModalData(
mm_hashes=merged_hashes,
@@ -1011,7 +1138,9 @@ class KimiK25Renderer:
)
return RenderedTokens(
token_ids=tokens,
message_indices=[-1] * len(tokens),
message_indices=indices,
sampled_mask=sampled,
message_roles=bridge_roles,
multi_modal_data=mm_data,
)
@@ -1028,6 +1157,7 @@ class KimiK25Renderer:
emit_ids,
*,
emit_image=None,
is_sampled: bool,
) -> None:
"""Emit message content, handling strings, multipart lists, and (when
``emit_image`` is supplied) image parts.
@@ -1046,7 +1176,7 @@ class KimiK25Renderer:
if content is None:
return
if isinstance(content, str):
emit_text(content, msg_idx)
emit_text(content, msg_idx, is_sampled=is_sampled)
return
if isinstance(content, list):
for part in content:
@@ -1059,19 +1189,21 @@ class KimiK25Renderer:
if emit_image is None:
# Silently drop — caller didn't opt into multimodal.
continue
emit_image(part, msg_idx)
emit_image(part, msg_idx, is_sampled=is_sampled)
continue
if is_video:
raise NotImplementedError(
"Video parts are not yet supported by KimiK25Renderer."
)
if ptype == "text":
emit_text(part.get("text", ""), msg_idx)
emit_text(part.get("text", ""), msg_idx, is_sampled=is_sampled)
elif ptype == "thinking":
# Thinking parts in non-assistant roles are rendered as text
thinking = part.get("thinking", "")
if thinking:
emit_text(f"<think>{thinking}</think>", msg_idx)
emit_text(
f"<think>{thinking}</think>", msg_idx, is_sampled=is_sampled
)
# Other part types are silently skipped
def _render_assistant_body(
@@ -1129,17 +1261,20 @@ class KimiK25Renderer:
else:
text_content = content or ""
# Hist/suffix split: hist drops reasoning, suffix keeps it.
# Override flag preserves reasoning on hist when caller asks for it.
# Assistant body is model-sampled content: ``<think>...</think>``
# block, text content, and any tool_calls section all live in
# the sampled stream. The closing ``<|im_end|>`` is emitted by
# ``render`` (also is_sampled=True; it's the model's stop
# signal).
if is_suffix or (preserve_thinking and reasoning_content):
emit_text(f"<think>{reasoning_content}</think>", msg_idx)
emit_text(f"<think>{reasoning_content}</think>", msg_idx, is_sampled=True)
else:
emit_text("<think></think>", msg_idx)
emit_text(text_content, msg_idx)
emit_text("<think></think>", msg_idx, is_sampled=True)
emit_text(text_content, msg_idx, is_sampled=True)
tool_calls = msg.get("tool_calls") or []
if tool_calls:
emit_special(self._tool_calls_section_begin, msg_idx)
emit_special(self._tool_calls_section_begin, msg_idx, is_sampled=True)
for tc in tool_calls:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
@@ -1153,12 +1288,12 @@ class KimiK25Renderer:
# ``functions.{name}:{idx}`` form (Kimi's parser recovers
# the function name from that field).
tool_id = tc.get("id") or ""
emit_special(self._tool_call_begin, msg_idx)
emit_text(tool_id, msg_idx)
emit_special(self._tool_call_argument_begin, msg_idx)
emit_text(args_str, msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_section_end, msg_idx)
emit_special(self._tool_call_begin, msg_idx, is_sampled=True)
emit_text(tool_id, msg_idx, is_sampled=True)
emit_special(self._tool_call_argument_begin, msg_idx, is_sampled=True)
emit_text(args_str, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._tool_calls_section_end, msg_idx, is_sampled=True)
def _render_tool_body(
self,
@@ -1168,6 +1303,7 @@ class KimiK25Renderer:
emit_special,
emit_text,
emit_ids,
emit_image=None,
) -> None:
"""Emit tool-result body (after the role tag): ``## Return of {id}\\n``
+ content. No ``<|im_end|>``; caller emits that.
@@ -1175,12 +1311,28 @@ class KimiK25Renderer:
The K2.5 template emits the ``## Return of …`` header unconditionally
— when ``tool_call_id`` is missing the interpolation yields empty
string and you get ``## Return of \\n``. We mirror that.
``emit_image`` is threaded through to ``_emit_content`` so image parts
inside ``content`` lists (browser-agent screenshots, etc.) render as
``<|media_begin|>image<|media_content|><|media_pad|><|media_end|>``
inline. Without it those parts are silently dropped.
"""
# Tool messages are conversation-history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
tool_call_id = msg.get("tool_call_id") or ""
emit_text(f"## Return of {tool_call_id}\n", msg_idx)
emit_text(f"## Return of {tool_call_id}\n", msg_idx, is_sampled=False)
content = msg.get("content")
if content is not None:
self._emit_content(content, msg_idx, emit_special, emit_text, emit_ids)
self._emit_content(
content,
msg_idx,
emit_special,
emit_text,
emit_ids,
emit_image=emit_image,
is_sampled=False,
)
def _normalize_response_tokens(self, response: list[int]) -> list[int]:
"""Restore the synthetic ``<think>`` prefill if the sampler stripped it.
+431
View File
@@ -0,0 +1,431 @@
"""Laguna-XS.2 Renderer.
Main properties:
- Prefix is the single token ``〈|EOS|〉`` (also the EOS / stop token).
- Role markers are block-style: ``<system>...</system>``, ``<user>...</user>``,
``<assistant>...</assistant>``, ``<tool_response>...</tool_response>``. Of
these, only ``<assistant>`` / ``</assistant>`` are single (added) tokens
in the tokenizer; everything else is plain text and BPEs into multiple
subwords.
- Assistant turn has an explicit close: ``</assistant>`` is the canonical
stop token (alongside ``〈|EOS|〉``).
- 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``).
- 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.
"""
from __future__ import annotations
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Content,
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
)
from renderers.parsing import parse_laguna_xs2
_DEFAULT_SYSTEM_MESSAGE = (
"You are a helpful, conversationally-fluent assistant made by Poolside. "
"You are here to be helpful to users through natural language conversations."
)
_TOOLS_HEADER = (
"\n\n### 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"
)
_TOOLS_FOOTER_THINKING = (
"</available_tools>\n\n"
"Wrap your thinking in '<think>', '</think>' tags, followed by a function call. "
"For each function call, return an unescaped XML-like object with function name "
"and arguments within '<tool_call>' and '</tool_call>' tags, like here:\n"
"<think> your thoughts here </think>\n"
"<tool_call>function-name\n"
"<arg_key>argument-key</arg_key>\n"
"<arg_value>value-of-argument-key</arg_value>\n"
"</tool_call>"
)
_TOOLS_FOOTER_NO_THINKING = (
"</available_tools>\n\n"
"For each function call, return an unescaped XML-like object with function name "
"and arguments within '<tool_call>' and '</tool_call>' tags, like here:\n"
"<tool_call>function-name\n"
"<arg_key>argument-key</arg_key>\n"
"<arg_value>value-of-argument-key</arg_value>\n"
"</tool_call>"
)
class LagunaXS2Renderer:
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = False,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
# Accepted for protocol uniformity. The chat template renders
# reasoning on every assistant message regardless, so flipping
# these flags has no effect on the byte-level output.
self._preserve_all_thinking = preserve_all_thinking
self._preserve_thinking_between_tool_calls = (
preserve_thinking_between_tool_calls
)
self._eos = self._token_id("〈|EOS|〉")
self._think = self._token_id("<think>")
self._think_end = self._token_id("</think>")
self._assistant = self._token_id("<assistant>")
self._assistant_end = self._token_id("</assistant>")
self._tool_call = self._token_id("<tool_call>")
self._tool_call_end = self._token_id("</tool_call>")
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: Content | None) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
parts.append(item.get("text", ""))
return "".join(parts)
return ""
@staticmethod
def _thinking_text(content: Content | None) -> str:
"""Concatenate ``ThinkingPart`` entries from list-form content.
Used as a reasoning source in ``_render_assistant`` when neither
``reasoning`` nor ``reasoning_content`` is present on the message.
Returns ``""`` for any non-list input.
"""
if not isinstance(content, list):
return ""
parts: list[str] = []
for item in content:
if isinstance(item, dict) and item.get("type") == "thinking":
parts.append(item.get("thinking", ""))
return "".join(parts)
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] = []
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
emit_special(self._eos, -1, is_sampled=False)
# ── System header (absorbs messages[0] if it's a system message) ──
system_content = _DEFAULT_SYSTEM_MESSAGE
system_msg_idx = -1
if messages and messages[0].get("role") == "system":
system_content = self._visible_text(messages[0].get("content"))
system_msg_idx = 0
has_sys_content = bool(system_content and system_content.strip())
# Mirrors the template's ``(system_message and system_message.strip()) or tools``
# 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,
)
if has_sys_content:
emit_text(system_content.rstrip(), system_msg_idx, is_sampled=False)
if tools:
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
tool_text += (
_TOOLS_FOOTER_THINKING
if self._enable_thinking
else _TOOLS_FOOTER_NO_THINKING
)
emit_text(tool_text, -1, is_sampled=False)
emit_text("\n</system>\n", -1, is_sampled=False)
# ── Per-message loop ──────────────────────────────────────────
for i, msg in enumerate(messages):
content = self._visible_text(msg.get("content"))
match msg["role"]:
case "system":
# Already consumed in the header block.
if i == 0:
continue
emit_text(
"<system>\n" + content + "\n</system>\n", i, is_sampled=False
)
case "user":
emit_text("<user>\n" + content + "\n</user>\n", i, is_sampled=False)
case "assistant":
self._render_assistant(
msg, i, content, emit_special=emit_special, emit_text=emit_text
)
case "tool":
emit_text(
"<tool_response>\n" + content + "\n</tool_response>\n",
i,
is_sampled=False,
)
# ── Generation prompt ─────────────────────────────────────────
if add_generation_prompt:
emit_special(self._assistant, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1, is_sampled=False)
else:
emit_special(self._think_end, -1, is_sampled=False)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> list[int]:
return self.render(
messages,
tools=tools,
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
return parse_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,
)
def get_stop_token_ids(self) -> list[int]:
return [self._assistant_end, self._eos]
def bridge_to_next_turn(
self,
previous_prompt_ids: list[int],
previous_completion_ids: list[int],
new_messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
) -> RenderedTokens | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
# The canonical assistant-turn close is ``</assistant>``. ``〈|EOS|〉``
# also stops generation; either being the final token means the turn
# ended cleanly. Truncation (no stop token at the tail) synthesises
# ``</assistant>\n`` — the same scaffold the template emits.
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)
previous_ids.extend(self._encode("\n"))
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
if role == "user":
emit_text("<user>\n" + content + "\n</user>\n", i)
elif role == "system":
emit_text("<system>\n" + content + "\n</system>\n", i)
elif role == "tool":
emit_text("<tool_response>\n" + content + "\n</tool_response>\n", i)
else:
return None
emit_special(self._assistant, -1)
emit_text("\n", -1)
if self._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,
message_roles=[m.get("role") or "" for m in new_messages],
)
def _render_assistant(
self,
msg: Message,
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
) -> None:
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
else:
# When the caller stores reasoning as a ``ThinkingPart`` inside
# a list-form ``content`` (e.g. after parse_response →
# reserialize), pull it out here so it survives the re-render.
part_thinking = self._thinking_text(msg.get("content"))
if part_thinking:
reasoning_content = part_thinking
# ``<assistant>\n`` is template-injected scaffolding — the chat
# template emits these as the generation prompt at inference and
# the model never samples them. Marking the role tag as
# ``is_sampled=False`` keeps the SFT loss mask aligned with what
# the model would actually have produced.
emit_special(self._assistant, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
if reasoning_content:
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content.strip() + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
else:
emit_special(self._think_end, msg_idx, is_sampled=True)
# Combined newline-after-</think> with optional content. Bundling
# preserves BPE merges across the boundary.
post_think_text = "\n"
if content.strip():
post_think_text += content.strip() + "\n"
emit_text(post_think_text, msg_idx, is_sampled=True)
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)
inner = name + "\n"
if isinstance(arguments, dict):
for k, v in arguments.items():
inner += "<arg_key>" + k + "</arg_key>\n"
if isinstance(v, str):
val_text = v
else:
val_text = json.dumps(v, ensure_ascii=False)
inner += "<arg_value>" + val_text + "</arg_value>\n"
emit_text(inner, msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=True)
# ``</assistant>`` is the model's stop signal (alongside
# ``〈|EOS|〉``) — it samples this to end its turn, so it's part of
# the sampled stream. The trailing ``\n`` is template-appended
# between turns and never sampled.
emit_special(self._assistant_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
+123 -45
View File
@@ -118,15 +118,18 @@ class MiniMaxM2Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
# ── Extract system message ──────────────────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -134,8 +137,8 @@ class MiniMaxM2Renderer:
conversation: list[Message] = messages[1:] if first_is_system else messages
# ── System block (always present) ───────────────────────────
emit_special(self._bos, sys_idx)
emit_special(self._role, sys_idx)
emit_special(self._bos, sys_idx, is_sampled=False)
emit_special(self._role, sys_idx, is_sampled=False)
sys_content = (
self._visible_text(messages[0].get("content")) if first_is_system else ""
@@ -152,9 +155,9 @@ class MiniMaxM2Renderer:
system_text += _TOOLS_FOOTER_PREFIX
system_text += _TOOLS_INSTRUCTIONS
emit_text(system_text, sys_idx)
emit_special(self._eos, sys_idx)
emit_text("\n", sys_idx)
emit_text(system_text, sys_idx, is_sampled=False)
emit_special(self._eos, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
# ── Compute last_user_index (relative to conversation) ──────
last_ui = -1
@@ -169,10 +172,14 @@ class MiniMaxM2Renderer:
orig_idx = ci + (1 if first_is_system else 0)
if role == "user":
emit_special(self._role, orig_idx)
emit_text("user\n" + self._visible_text(msg.get("content")), orig_idx)
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
emit_special(self._role, orig_idx, is_sampled=False)
emit_text(
"user\n" + self._visible_text(msg.get("content")),
orig_idx,
is_sampled=False,
)
emit_special(self._eos, orig_idx, is_sampled=False)
emit_text("\n", orig_idx, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -203,12 +210,17 @@ class MiniMaxM2Renderer:
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._role, -1)
emit_text("ai\n", -1)
emit_special(self._think, -1)
emit_text("\n", -1)
emit_special(self._role, -1, is_sampled=False)
emit_text("ai\n", -1, is_sampled=False)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
@@ -223,7 +235,12 @@ class MiniMaxM2Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
return parse_minimax(
self._tokenizer,
token_ids,
@@ -232,6 +249,7 @@ class MiniMaxM2Renderer:
think_end_id=self._think_end,
tool_call_id=self._tool_call_tok,
tool_call_end_id=self._tool_call_end_tok,
tools=tools,
)
def get_stop_token_ids(self) -> list[int]:
@@ -262,12 +280,29 @@ class MiniMaxM2Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
ext.extend(self._encode(text))
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
# Trailing ``\n`` after the ``[e~[`` turn close — see ``render()``.
emit_text("\n", -1)
@@ -303,7 +338,13 @@ class MiniMaxM2Renderer:
emit_special(self._think, -1)
emit_text("\n", -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
message_roles=[m.get("role") or "" for m in new_messages],
)
def _render_assistant(
self,
@@ -329,26 +370,53 @@ class MiniMaxM2Renderer:
reasoning_content = before.strip("\n")
content = after.strip("\n")
emit_special(self._role, orig_idx)
# ``]~b]ai\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 marker and tag as
# ``is_sampled=False`` keeps the SFT loss mask aligned with what
# the model would actually have produced.
emit_special(self._role, orig_idx, is_sampled=False)
# Build the full text between ]~b]ai and [e~[ with special tokens
# interspersed. Keep text segments contiguous to preserve BPE merges.
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges.
tool_calls = msg.get("tool_calls") or []
emit_thinking = reasoning_content and (
conv_idx > last_user_index or preserve_thinking
)
if reasoning_content and (conv_idx > last_user_index or preserve_thinking):
emit_text("ai\n", orig_idx)
emit_special(self._think, orig_idx)
emit_text("\n" + reasoning_content + "\n", orig_idx)
emit_special(self._think_end, orig_idx)
if emit_thinking:
# The thinking branch has the ``<think>`` special token
# immediately after ``ai\n``, which forces a tokenizer
# boundary — splitting ``ai\n`` (not_sampled) from the
# ``<think>``-led body (sampled) is BPE-safe.
emit_text("ai\n", orig_idx, is_sampled=False)
emit_special(self._think, orig_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", orig_idx, is_sampled=True)
emit_special(self._think_end, orig_idx, is_sampled=True)
# \n\n + content must be contiguous for BPE
after_think = "\n\n" + content if content else "\n\n"
body = "\n\n" + content if content else "\n\n"
else:
after_think = "ai\n" + content if content else "ai\n"
body = content
# Empty body + tool_calls would emit ``"\n"`` next, and
# ``ai\n`` + ``\n`` BPE-merges into a single ``\n\n`` token
# in this tokenizer. Fold the boundary ``\n`` into the
# role-tag emission so the merged token stays whole. The
# combined token is is_sampled=False — the conservative
# choice for SFT (don't train on a token whose first byte
# is template scaffolding).
if tool_calls and not body:
emit_text("ai\n\n", orig_idx, is_sampled=False)
else:
emit_text("ai\n", orig_idx, is_sampled=False)
if tool_calls:
# \n before <minimax:tool_call> must be contiguous with preceding text
emit_text(after_think + "\n", orig_idx)
emit_special(self._tool_call_tok, orig_idx)
# \n before <minimax:tool_call> must be contiguous with preceding text.
# The empty-body / non-thinking case folded the leading \n
# into the role-tag emission above; skip it here.
if emit_thinking or body:
emit_text(body + "\n", orig_idx, is_sampled=True)
emit_special(self._tool_call_tok, orig_idx, is_sampled=True)
invoke_block = "\n"
for tc in tool_calls:
@@ -380,13 +448,16 @@ class MiniMaxM2Renderer:
)
invoke_block += "</invoke>\n"
emit_text(invoke_block, orig_idx)
emit_special(self._tool_call_end_tok, orig_idx)
else:
emit_text(after_think, orig_idx)
emit_text(invoke_block, orig_idx, is_sampled=True)
emit_special(self._tool_call_end_tok, orig_idx, is_sampled=True)
elif body:
emit_text(body, orig_idx, is_sampled=True)
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
# ``[e~[`` is the model's stop signal — it samples this to end
# its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
emit_special(self._eos, orig_idx, is_sampled=True)
emit_text("\n", orig_idx, is_sampled=False)
def _render_tool(
self,
@@ -398,6 +469,9 @@ class MiniMaxM2Renderer:
emit_special,
emit_text,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
prev_is_tool = conv_idx > 0 and conversation[conv_idx - 1]["role"] == "tool"
next_is_tool = (
conv_idx + 1 < len(conversation)
@@ -405,8 +479,8 @@ class MiniMaxM2Renderer:
)
if not prev_is_tool:
emit_special(self._role, orig_idx)
emit_text("tool", orig_idx)
emit_special(self._role, orig_idx, is_sampled=False)
emit_text("tool", orig_idx, is_sampled=False)
content = self._visible_text(msg.get("content"))
# Leading ``\n`` before ``<response>`` only on the first of a
@@ -415,8 +489,12 @@ class MiniMaxM2Renderer:
# through a single emit_text call instead of splitting the merge.
prefix = "" if prev_is_tool else "\n"
suffix = "\n" if next_is_tool else ""
emit_text(prefix + "<response>" + content + "</response>" + suffix, orig_idx)
emit_text(
prefix + "<response>" + content + "</response>" + suffix,
orig_idx,
is_sampled=False,
)
if not next_is_tool:
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
emit_special(self._eos, orig_idx, is_sampled=False)
emit_text("\n", orig_idx, is_sampled=False)
+105 -58
View File
@@ -240,17 +240,20 @@ class Nemotron3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -259,8 +262,8 @@ class Nemotron3Renderer:
# Nemotron 3: system prompt BEFORE tools block
sys_idx = orig_idx(0) if first_is_system else -1
emit_special(self._im_start, sys_idx)
emit_text("system\n", sys_idx)
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n", sys_idx, is_sampled=False)
# Build system content: user's system text first, then tools
if first_is_system:
@@ -284,17 +287,17 @@ class Nemotron3Renderer:
else:
full_sys = tools_block
emit_text(full_sys, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
emit_text(full_sys, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
elif first_is_system:
sys_idx = orig_idx(0)
sys_content = self._render_content(messages[0].get("content")).strip()
emit_special(self._im_start, sys_idx)
emit_text("system\n" + sys_content, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n" + sys_content, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
# Track the most-recent plain (non-tool-call) assistant so we can
# preserve its reasoning while stripping reasoning from earlier
@@ -319,10 +322,10 @@ class Nemotron3Renderer:
continue # Already handled above
elif role == "user":
emit_special(self._im_start, msg_orig_idx)
emit_text("user\n" + content, msg_orig_idx)
emit_special(self._im_end, msg_orig_idx)
emit_text("\n", msg_orig_idx)
emit_special(self._im_start, msg_orig_idx, is_sampled=False)
emit_text("user\n" + content, msg_orig_idx, is_sampled=False)
emit_special(self._im_end, msg_orig_idx, is_sampled=False)
emit_text("\n", msg_orig_idx, is_sampled=False)
elif role == "assistant":
is_last_turn = i >= last_plain_assistant_idx
@@ -359,17 +362,22 @@ class Nemotron3Renderer:
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
else:
# Disable-thinking suffix: <think></think> with no trailing newlines
emit_special(self._think, -1)
emit_special(self._think_end, -1)
emit_special(self._think, -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
@@ -384,7 +392,12 @@ class Nemotron3Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — args land in a JSON object, schema not needed
) -> ParsedResponse:
stop_ids = {self._im_end}
if self._endoftext is not None:
stop_ids.add(self._endoftext)
@@ -432,12 +445,29 @@ class Nemotron3Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
ext.extend(self._encode(text))
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
emit_text("\n", -1)
@@ -477,7 +507,13 @@ class Nemotron3Renderer:
emit_special(self._think, -1)
emit_special(self._think_end, -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
message_roles=[m.get("role") or "" for m in new_messages],
)
# ------------------------------------------------------------------
# Assistant message rendering
@@ -510,8 +546,13 @@ class Nemotron3Renderer:
reasoning_content = reasoning_content.strip()
emit_special(self._im_start, msg_idx)
emit_text("assistant\n", msg_idx)
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
# at inference the chat template emits these as the generation
# prompt and the model never samples them. Marking the role tag
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced.
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# Nemotron 3 keeps reasoning on the most-recent plain assistant but
# strips it from historical turns, which collapse to an empty
@@ -526,35 +567,35 @@ class Nemotron3Renderer:
content_suffix = "\n" if tool_calls else ""
if reasoning_content and (is_last_turn or preserve_thinking):
emit_special(self._think, msg_idx)
emit_text("\n" + reasoning_content + "\n", msg_idx)
emit_special(self._think_end, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
# Single \n separator (not \n\n like Qwen3.5)
emit_text("\n" + content + content_suffix, msg_idx)
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=True)
elif reasoning_content:
# Historical assistant whose reasoning got stripped — template
# keeps a single \n between the collapsed <think></think> and
# the content as a marker that reasoning existed.
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
emit_text("\n" + content + content_suffix, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text("\n" + content + content_suffix, msg_idx, is_sampled=True)
else:
# No reasoning ever — <think></think> glued directly to content.
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
emit_text(content + content_suffix, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text(content + content_suffix, msg_idx, is_sampled=True)
# 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_idx, tc in enumerate(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)
emit_text("\n<function=" + name + ">\n", msg_idx)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_text("\n<function=" + name + ">\n", msg_idx, is_sampled=True)
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
@@ -577,15 +618,19 @@ class Nemotron3Renderer:
+ value_str
+ "\n</parameter>\n",
msg_idx,
is_sampled=True,
)
emit_text("</function>\n", msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_text("</function>\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
# Trailing \n after </tool_call> (Nemotron 3 specific)
emit_text("\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
# ------------------------------------------------------------------
# Tool message rendering
@@ -602,7 +647,9 @@ class Nemotron3Renderer:
emit_special,
emit_text,
) -> None:
# Consecutive tool messages are grouped under a single <|im_start|>user block
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
@@ -610,17 +657,17 @@ class Nemotron3Renderer:
oi = msg_orig_idx
if not prev_is_tool:
emit_special(self._im_start, oi)
emit_text("user\n", oi)
emit_special(self._im_start, oi, is_sampled=False)
emit_text("user\n", oi, is_sampled=False)
# else: the previous tool's trailing \n already provides the
# separator into this block.
emit_special(self._tool_response, oi)
emit_text("\n" + content + "\n", oi)
emit_special(self._tool_response_end, oi)
emit_special(self._tool_response, oi, is_sampled=False)
emit_text("\n" + content + "\n", oi, is_sampled=False)
emit_special(self._tool_response_end, oi, is_sampled=False)
# Nemotron 3: trailing \n after </tool_response>
emit_text("\n", oi)
emit_text("\n", oi, is_sampled=False)
if not next_is_tool:
emit_special(self._im_end, oi)
emit_text("\n", oi)
emit_special(self._im_end, oi, is_sampled=False)
emit_text("\n", oi, is_sampled=False)
+168 -52
View File
@@ -19,6 +19,8 @@ import json
import re
from typing import Protocol, runtime_checkable
from renderers.base import ParsedToolCall, ToolCallParseStatus
# ── Shared helpers ───────────────────────────────────────────────────
@@ -54,15 +56,17 @@ def _token_id(tokenizer, token: str) -> int | None:
class ToolParser(Protocol):
"""Extracts tool calls from completion token ids.
``extract`` returns a tuple ``(content_ids, tool_calls)`` where
``content_ids`` is the remaining content token ids with the tool-call
section removed, and ``tool_calls`` is a list of
``{"function": {"name": str, "arguments": dict | str}}`` dicts or
``None`` when no tool call was found.
``extract`` returns ``(content_ids, tool_calls)`` where ``content_ids``
is the remaining content token ids with the tool-call section removed,
and ``tool_calls`` is a list of :class:`ParsedToolCall` records — one
per attempted block. Empty list = the model emitted no tool calls;
callers filter by ``status == OK`` for the clean subset.
"""
def __init__(self, tokenizer): ...
def extract(self, token_ids: list[int]) -> tuple[list[int], list[dict] | None]: ...
def extract(
self, token_ids: list[int]
) -> tuple[list[int], list[ParsedToolCall]]: ...
@runtime_checkable
@@ -87,14 +91,14 @@ class Qwen3ToolParser:
self._tc_id = _token_id(tokenizer, "<tool_call>")
self._tc_end_id = _token_id(tokenizer, "</tool_call>")
def extract(self, ids: list[int]) -> tuple[list[int], list[dict] | None]:
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
if self._tc_id is None:
return ids, None
return ids, []
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
return ids, []
content_ids = ids[:tc_start]
tool_calls: list[dict] = []
tool_calls: list[ParsedToolCall] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
@@ -103,25 +107,52 @@ class Qwen3ToolParser:
if self._tc_end_id is not None
else -1
)
unclosed = end == -1
if end == -1:
end = len(ids)
tc_text = _decode(self._tokenizer, ids[i + 1 : end]).strip()
span = (i, end + (0 if unclosed else 1))
if unclosed:
tool_calls.append(
ParsedToolCall(
raw=tc_text,
token_span=span,
status=ToolCallParseStatus.UNCLOSED_BLOCK,
)
)
break
try:
parsed = json.loads(tc_text)
tool_calls.append(
{
"function": {
"name": parsed.get("name", ""),
"arguments": parsed.get("arguments", {}),
}
}
)
except json.JSONDecodeError:
pass
tool_calls.append(
ParsedToolCall(
raw=tc_text,
token_span=span,
status=ToolCallParseStatus.INVALID_JSON,
)
)
else:
name = parsed.get("name", "") if isinstance(parsed, dict) else ""
arguments = (
parsed.get("arguments", {}) if isinstance(parsed, dict) else {}
)
tool_calls.append(
ParsedToolCall(
raw=tc_text,
name=name or None,
arguments=arguments,
token_span=span,
status=(
ToolCallParseStatus.MISSING_NAME
if not name
else ToolCallParseStatus.OK
),
)
)
i = end + 1
else:
i += 1
return content_ids, (tool_calls or None)
return content_ids, tool_calls
class Qwen35ToolParser:
@@ -132,13 +163,13 @@ class Qwen35ToolParser:
self._tc_id = _token_id(tokenizer, "<tool_call>")
self._tc_end_id = _token_id(tokenizer, "</tool_call>")
def extract(self, ids: list[int]) -> tuple[list[int], list[dict] | None]:
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
if self._tc_id is None:
return ids, None
return ids, []
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
tool_calls: list[dict] = []
return ids, []
tool_calls: list[ParsedToolCall] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
@@ -148,30 +179,60 @@ class Qwen35ToolParser:
else -1
)
if end == -1:
raw = _decode(self._tokenizer, ids[i + 1 :])
tool_calls.append(
ParsedToolCall(
raw=raw,
token_span=(i, len(ids)),
status=ToolCallParseStatus.UNCLOSED_BLOCK,
)
)
break
block_text = _decode(self._tokenizer, ids[i + 1 : end])
span = (i, end + 1)
name_match = re.search(r"<function=([^>]+)>", block_text)
if name_match:
name = name_match.group(1)
arguments: dict = {}
for pm in re.finditer(
r"<parameter=([^>]+)>\n?(.*?)\n?</parameter>",
block_text,
re.DOTALL,
):
arg_name = pm.group(1)
arg_value = pm.group(2).strip()
try:
arguments[arg_name] = json.loads(arg_value)
except (json.JSONDecodeError, ValueError):
arguments[arg_name] = arg_value
if not name_match:
tool_calls.append(
{"function": {"name": name, "arguments": arguments}}
ParsedToolCall(
raw=block_text,
token_span=span,
status=ToolCallParseStatus.MALFORMED_STRUCTURE,
)
)
i = end + 1
continue
name = name_match.group(1)
arguments: dict = {}
any_json_fallback = False
for pm in re.finditer(
r"<parameter=([^>]+)>\n?(.*?)\n?</parameter>",
block_text,
re.DOTALL,
):
arg_name = pm.group(1)
arg_value = pm.group(2).strip()
try:
arguments[arg_name] = json.loads(arg_value)
except (json.JSONDecodeError, ValueError):
arguments[arg_name] = arg_value
any_json_fallback = True
tool_calls.append(
ParsedToolCall(
raw=block_text,
name=name,
arguments=arguments,
token_span=span,
status=(
ToolCallParseStatus.INVALID_JSON
if any_json_fallback
else ToolCallParseStatus.OK
),
)
)
i = end + 1
else:
i += 1
return ids[:tc_start], (tool_calls or None)
return ids[:tc_start], tool_calls
class GlmToolParser:
@@ -186,13 +247,13 @@ class GlmToolParser:
self._av_id = _token_id(tokenizer, "<arg_value>")
self._ave_id = _token_id(tokenizer, "</arg_value>")
def extract(self, ids: list[int]) -> tuple[list[int], list[dict] | None]:
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
if self._tc_id is None:
return ids, None
return ids, []
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
tool_calls: list[dict] = []
return ids, []
tool_calls: list[ParsedToolCall] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
@@ -202,9 +263,21 @@ class GlmToolParser:
else -1
)
if end == -1:
raw = _decode(self._tokenizer, ids[i + 1 :])
tool_calls.append(
ParsedToolCall(
raw=raw,
token_span=(i, len(ids)),
status=ToolCallParseStatus.UNCLOSED_BLOCK,
)
)
break
block = ids[i + 1 : end]
block_text = _decode(self._tokenizer, block)
span = (i, end + 1)
first_ak = _find(block, self._ak_id) if self._ak_id is not None else -1
any_json_fallback = False
structure_broke = False
if first_ak == -1:
name = _decode(self._tokenizer, block).strip()
arguments: dict = {}
@@ -220,6 +293,7 @@ class GlmToolParser:
else -1
)
if ake == -1:
structure_broke = True
break
key = _decode(self._tokenizer, block[j + 1 : ake]).strip()
av = (
@@ -228,6 +302,7 @@ class GlmToolParser:
else -1
)
if av == -1:
structure_broke = True
break
ave = (
_find(block, self._ave_id, av + 1)
@@ -235,6 +310,7 @@ class GlmToolParser:
else -1
)
if ave == -1:
structure_broke = True
break
val_text = _decode(
self._tokenizer, block[av + 1 : ave]
@@ -243,14 +319,31 @@ class GlmToolParser:
arguments[key] = json.loads(val_text)
except (json.JSONDecodeError, ValueError):
arguments[key] = val_text
any_json_fallback = True
j = ave + 1
else:
j += 1
tool_calls.append({"function": {"name": name, "arguments": arguments}})
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 ids[:tc_start], (tool_calls or None)
return ids[:tc_start], tool_calls
class DeepSeekV3ToolParser:
@@ -264,12 +357,12 @@ class DeepSeekV3ToolParser:
self._tc_end = _token_id(tokenizer, "<|tool▁call▁end|>")
self._sep = _token_id(tokenizer, "<|tool▁sep|>")
def extract(self, ids: list[int]) -> tuple[list[int], list[dict] | None]:
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
if self._tcs_begin is None:
return ids, None
return ids, []
section_start = _find(ids, self._tcs_begin)
if section_start == -1:
return ids, None
return ids, []
content_ids = ids[:section_start]
section_end = (
_find(ids, self._tcs_end, section_start + 1)
@@ -278,9 +371,10 @@ class DeepSeekV3ToolParser:
)
if section_end == -1:
section_end = len(ids)
inner_offset = section_start + 1
section_ids = ids[section_start + 1 : section_end]
tool_calls: list[dict] = []
tool_calls: list[ParsedToolCall] = []
i = 0
while i < len(section_ids):
if self._tc_begin is None or section_ids[i] != self._tc_begin:
@@ -291,23 +385,45 @@ class DeepSeekV3ToolParser:
if self._tc_end is not None
else -1
)
unclosed = end == -1
if end == -1:
end = len(section_ids)
block_text = _decode(self._tokenizer, section_ids[i + 1 : end])
span = (inner_offset + i, inner_offset + end + (0 if unclosed else 1))
# Format: "function<|tool▁sep|>{name}\n```json\n{args}\n```"
name_match = re.search(r"^\s*\w+.*?([A-Za-z0-9_]+)\s*\n", block_text)
name = name_match.group(1) if name_match else ""
args: dict | str = {}
invalid_json = False
json_match = re.search(r"```json\s*(.*?)\s*```", block_text, re.DOTALL)
if json_match:
try:
args = json.loads(json_match.group(1))
except (json.JSONDecodeError, ValueError):
args = json_match.group(1)
tool_calls.append({"function": {"name": name, "arguments": args}})
invalid_json = True
if unclosed:
status = ToolCallParseStatus.UNCLOSED_BLOCK
elif not name:
status = ToolCallParseStatus.MISSING_NAME
elif invalid_json:
status = ToolCallParseStatus.INVALID_JSON
else:
status = ToolCallParseStatus.OK
tool_calls.append(
ParsedToolCall(
raw=block_text,
name=name or None,
arguments=args,
token_span=span,
status=status,
)
)
i = end + 1
if unclosed:
break
return content_ids, (tool_calls or None)
return content_ids, tool_calls
# ── Reasoning parsers ────────────────────────────────────────────────
+665 -183
View File
File diff suppressed because it is too large Load Diff
+105 -51
View File
@@ -107,24 +107,27 @@ class Qwen3Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
# ── 1. System + tools ───────────────────────────────────────
first_is_system = messages[0].get("role") == "system"
if tools:
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx)
emit_special(self._im_start, sys_idx, is_sampled=False)
tool_text = "system\n"
if first_is_system:
tool_text += (messages[0].get("content") or "") + "\n\n"
@@ -132,14 +135,16 @@ class Qwen3Renderer:
for tool in tools:
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
tool_text += _TOOLS_FOOTER
emit_text(tool_text, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
emit_text(tool_text, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
elif first_is_system:
emit_special(self._im_start, 0)
emit_text("system\n" + (messages[0].get("content") or ""), 0)
emit_special(self._im_end, 0)
emit_text("\n", 0)
emit_special(self._im_start, 0, is_sampled=False)
emit_text(
"system\n" + (messages[0].get("content") or ""), 0, is_sampled=False
)
emit_special(self._im_end, 0, is_sampled=False)
emit_text("\n", 0, is_sampled=False)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
@@ -153,16 +158,16 @@ class Qwen3Renderer:
if role == "system":
if i == 0:
continue
emit_special(self._im_start, i)
emit_text(role + "\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
emit_special(self._im_start, i, is_sampled=False)
emit_text(role + "\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
elif role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
emit_special(self._im_start, i, is_sampled=False)
emit_text("user\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -189,12 +194,17 @@ class Qwen3Renderer:
# ── 4. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if not self._enable_thinking:
emit_text("<think>\n\n</think>\n\n", -1)
emit_text("<think>\n\n</think>\n\n", -1, is_sampled=False)
return RenderedTokens(token_ids=tokens, message_indices=indices)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
)
def render_ids(
self,
@@ -209,7 +219,12 @@ class Qwen3Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — hermes wire format quotes strings, schema not needed
) -> ParsedResponse:
return parse_qwen3(
self._tokenizer,
token_ids,
@@ -246,12 +261,29 @@ class Qwen3Renderer:
return None
ext: list[int] = []
ext_indices: list[int] = []
ext_sampled: list[bool] = []
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ext.append(token_id)
ext_indices.append(msg_idx)
ext_sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
ext.extend(self._encode(text))
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
ext.extend(ids)
ext_indices.extend([msg_idx] * len(ids))
ext_sampled.extend([is_sampled] * len(ids))
# Trailing ``\n`` after the turn-close token. ``render()`` emits this
# as part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
@@ -287,7 +319,13 @@ class Qwen3Renderer:
if not self._enable_thinking:
emit_text("<think>\n\n</think>\n\n", -1)
return RenderedTokens(token_ids=previous_ids + ext)
total_len = len(previous_ids) + len(ext)
return RenderedTokens(
token_ids=previous_ids + ext,
message_indices=[-1] * len(previous_ids) + ext_indices,
sampled_mask=[False] * total_len,
message_roles=[m.get("role") or "" for m in new_messages],
)
def _render_assistant(
self,
@@ -313,11 +351,20 @@ class Qwen3Renderer:
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._im_start, msg_idx)
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
# at inference the chat template emits these as the generation
# prompt and the model never samples them. Marking the role tag
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced.
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# Build the full text between <|im_start|> and <|im_end|> with tool call
# special tokens interspersed. We must keep text segments contiguous to
# preserve BPE merges (e.g., ".\n" is a single token in Qwen3).
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges (e.g., ".\n" is a single token in
# Qwen3); the only split we introduce here is at ``\n`` after the
# role tag, which the existing renderer already treats as a
# token boundary (cf. ``_render_tool``).
tool_calls = msg.get("tool_calls") or []
emit_in_template_window = msg_idx > last_query_index and (
@@ -325,17 +372,17 @@ class Qwen3Renderer:
)
emit_via_override = preserve_thinking and bool(reasoning_content)
if emit_in_template_window or emit_via_override:
prefix = (
"assistant\n<think>\n"
body = (
"<think>\n"
+ reasoning_content.strip("\n")
+ "\n</think>\n\n"
+ content.lstrip("\n")
)
else:
prefix = "assistant\n" + content
body = content
if not tool_calls:
emit_text(prefix, msg_idx)
emit_text(body, msg_idx, is_sampled=True)
else:
for tc_idx, tc in enumerate(tool_calls):
func = tc.get("function") or tc
@@ -350,19 +397,23 @@ class Qwen3Renderer:
# Text before this tool_call (includes separator)
if tc_idx == 0:
separator = "\n" if content else ""
emit_text(prefix + separator, msg_idx)
emit_text(body + separator, msg_idx, is_sampled=True)
else:
emit_text("\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call, msg_idx)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_text(
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
msg_idx,
is_sampled=True,
)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
def _render_tool(
self,
@@ -373,20 +424,23 @@ class Qwen3Renderer:
emit_special,
emit_text,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
)
if not prev_is_tool:
emit_special(self._im_start, msg_idx)
emit_text("user", msg_idx)
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("user", msg_idx, is_sampled=False)
emit_text("\n", msg_idx)
emit_special(self._tool_response, msg_idx)
emit_text("\n" + content + "\n", msg_idx)
emit_special(self._tool_response_end, msg_idx)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._tool_response, msg_idx, is_sampled=False)
emit_text("\n" + content + "\n", msg_idx, is_sampled=False)
emit_special(self._tool_response_end, msg_idx, is_sampled=False)
if not next_is_tool:
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
+177 -76
View File
@@ -290,28 +290,34 @@ class Qwen35Renderer:
tokens: list[int] = []
indices: list[int] = []
sampled: list[bool] = []
mm_hashes: dict[str, list[str]] = {}
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
mm_items: dict[str, list[dict[str, Any]]] = {}
def emit_ids(ids: list[int], msg_idx: int) -> None:
def emit_ids(ids: list[int], msg_idx: int, *, is_sampled: bool) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
def emit_special(token_id: int, msg_idx: int, *, is_sampled: bool) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
def emit_text(text: str, msg_idx: int, *, is_sampled: bool) -> None:
emit_ids(self._encode(text), msg_idx, is_sampled=is_sampled)
def emit_image(part: dict[str, Any], msg_idx: int) -> None:
# Image placeholders only appear in user / tool messages; the
# model never samples them. Pin is_sampled=False here so
# callers don't need to thread the flag through.
_, out, n, h = self._process_image(part)
emit_special(self._vision_start, msg_idx)
emit_special(self._vision_start, msg_idx, is_sampled=False)
offset = len(tokens)
for _ in range(n):
emit_special(self._image_pad, msg_idx)
emit_special(self._vision_end, msg_idx)
emit_special(self._image_pad, msg_idx, is_sampled=False)
emit_special(self._vision_end, msg_idx, is_sampled=False)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -332,12 +338,14 @@ class Qwen35Renderer:
concatenates strings before tokenization. This preserves BPE
byte-parity against ``apply_chat_template``.
"""
emit_special(self._im_start, msg_idx)
# Every token in a user message is conversation history that
# the model never samples at inference.
emit_special(self._im_start, msg_idx, is_sampled=False)
buf: list[str] = ["user\n"]
def flush_buf() -> None:
if buf:
emit_text("".join(buf), msg_idx)
emit_text("".join(buf), msg_idx, is_sampled=False)
buf.clear()
for item in content_list:
@@ -358,8 +366,8 @@ class Qwen35Renderer:
else:
raise ValueError(f"Unexpected content item: {item}")
flush_buf()
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -368,8 +376,8 @@ class Qwen35Renderer:
# System message index for attribution
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx)
emit_text("system\n", sys_idx)
emit_special(self._im_start, sys_idx, is_sampled=False)
emit_text("system\n", sys_idx, is_sampled=False)
# Tools header + JSON definitions
tool_text = _TOOLS_HEADER
@@ -384,15 +392,15 @@ class Qwen35Renderer:
if sys_content:
tool_text += "\n\n" + sys_content
emit_text(tool_text, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
emit_text(tool_text, sys_idx, is_sampled=False)
emit_special(self._im_end, sys_idx, is_sampled=False)
emit_text("\n", sys_idx, is_sampled=False)
elif first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
emit_special(self._im_start, 0)
emit_text("system\n" + sys_content, 0)
emit_special(self._im_end, 0)
emit_text("\n", 0)
emit_special(self._im_start, 0, is_sampled=False)
emit_text("system\n" + sys_content, 0, is_sampled=False)
emit_special(self._im_end, 0, is_sampled=False)
emit_text("\n", 0, is_sampled=False)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
@@ -412,10 +420,10 @@ class Qwen35Renderer:
if self._content_has_media(raw_content):
emit_user_with_media(raw_content, i)
else:
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
emit_special(self._im_start, i, is_sampled=False)
emit_text("user\n" + content, i, is_sampled=False)
emit_special(self._im_end, i, is_sampled=False)
emit_text("\n", i, is_sampled=False)
elif role == "assistant":
preserve_thinking = should_preserve_past_thinking(
@@ -439,9 +447,9 @@ class Qwen35Renderer:
self._render_tool(
messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
emit_image=emit_image,
)
else:
@@ -449,16 +457,16 @@ class Qwen35Renderer:
# ── 4. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
emit_special(self._im_start, -1, is_sampled=False)
emit_text("assistant\n", -1, is_sampled=False)
if self._enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n", -1, is_sampled=False)
else:
emit_special(self._think, -1)
emit_text("\n\n", -1)
emit_special(self._think_end, -1)
emit_text("\n\n", -1)
emit_special(self._think, -1, is_sampled=False)
emit_text("\n\n", -1, is_sampled=False)
emit_special(self._think_end, -1, is_sampled=False)
emit_text("\n\n", -1, is_sampled=False)
mm_data: MultiModalData | None = None
if mm_hashes or mm_placeholders or mm_items:
@@ -471,6 +479,8 @@ class Qwen35Renderer:
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=[m.get("role") or "" for m in messages],
multi_modal_data=mm_data,
)
@@ -487,7 +497,12 @@ class Qwen35Renderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None,
) -> ParsedResponse:
return parse_qwen35(
self._tokenizer,
token_ids,
@@ -496,6 +511,7 @@ class Qwen35Renderer:
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]:
@@ -528,24 +544,40 @@ class Qwen35Renderer:
# Seed combined-token list with prior turn so placeholder offsets
# are absolute in the bridged sequence (matching ``render()``).
# Parallel ``indices``/``sampled`` are seeded with ``-1``/``False``
# for the prior portion — the bridge has no attribution info for
# ``previous_ids``. Bridge-added tokens get proper ``msg_idx``
# (relative to ``new_messages``) and uniformly ``False``
# ``sampled``: nothing the bridge emits was model-sampled.
tokens: list[int] = list(previous_ids)
indices: list[int] = [-1] * len(previous_ids)
sampled: list[bool] = [False] * len(previous_ids)
new_hashes: dict[str, list[str]] = {}
new_placeholders: dict[str, list[PlaceholderRange]] = {}
new_items: dict[str, list[dict[str, Any]]] = {}
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
def emit_special(
token_id: int, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
tokens.append(token_id)
indices.append(msg_idx)
sampled.append(is_sampled)
def emit_text(text: str, _msg_idx: int = -1) -> None:
tokens.extend(self._encode(text))
def emit_text(
text: str, msg_idx: int = -1, *, is_sampled: bool = False
) -> None:
ids = self._encode(text)
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
sampled.extend([is_sampled] * len(ids))
def emit_image(part: dict[str, Any]) -> None:
def emit_image(part: dict[str, Any], msg_idx: int = -1) -> None:
_, out, n, h = self._process_image(part)
emit_special(self._vision_start)
emit_special(self._vision_start, msg_idx)
offset = len(tokens)
for _ in range(n):
emit_special(self._image_pad)
emit_special(self._vision_end)
emit_special(self._image_pad, msg_idx)
emit_special(self._vision_end, msg_idx)
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -557,13 +589,13 @@ class Qwen35Renderer:
}
)
def emit_user_with_media(content_list: list[Any]) -> None:
emit_special(self._im_start)
def emit_user_with_media(content_list: list[Any], msg_idx: int) -> None:
emit_special(self._im_start, msg_idx)
buf: list[str] = ["user\n"]
def flush_buf() -> None:
if buf:
emit_text("".join(buf))
emit_text("".join(buf), msg_idx)
buf.clear()
for item in content_list:
@@ -572,7 +604,7 @@ class Qwen35Renderer:
elif isinstance(item, dict):
if _is_image_part(item):
flush_buf()
emit_image(item)
emit_image(item, msg_idx)
elif _is_video_part(item):
raise NotImplementedError(
"Video parts are not yet supported by Qwen35Renderer."
@@ -584,8 +616,8 @@ class Qwen35Renderer:
else:
raise ValueError(f"Unexpected content item: {item}")
flush_buf()
emit_special(self._im_end)
emit_text("\n")
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# Trailing ``\n`` after ``<|im_end|>`` — ``render()`` emits it as
# part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
@@ -598,7 +630,7 @@ class Qwen35Renderer:
content = self._render_content(raw_content).strip()
if role == "user":
if self._content_has_media(raw_content):
emit_user_with_media(raw_content)
emit_user_with_media(raw_content, i)
else:
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
@@ -613,9 +645,9 @@ class Qwen35Renderer:
self._render_tool(
new_messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
emit_image=emit_image,
)
else:
return None
@@ -655,8 +687,14 @@ class Qwen35Renderer:
for modality, vals in new_items.items():
merged_items.setdefault(modality, []).extend(vals)
bridge_roles = [m.get("role") or "" for m in new_messages]
if not (merged_hashes or merged_placeholders or merged_items):
return RenderedTokens(token_ids=tokens)
return RenderedTokens(
token_ids=tokens,
message_indices=indices,
sampled_mask=sampled,
message_roles=bridge_roles,
)
mm_data = MultiModalData(
mm_hashes=merged_hashes,
@@ -665,7 +703,9 @@ class Qwen35Renderer:
)
return RenderedTokens(
token_ids=tokens,
message_indices=[-1] * len(tokens),
message_indices=indices,
sampled_mask=sampled,
message_roles=bridge_roles,
multi_modal_data=mm_data,
)
@@ -725,20 +765,30 @@ class Qwen35Renderer:
reasoning_content = reasoning_content.strip()
emit_special(self._im_start, msg_idx)
# ``<|im_start|>assistant\n`` is template-injected scaffolding —
# at inference the chat template emits these as the generation
# prompt and the model never samples them. Marking the role tag
# as ``is_sampled=False`` keeps the SFT loss mask aligned with
# what the model would actually have produced. The split between
# ``assistant`` and ``\n`` is a safe BPE boundary in the Qwen
# tokenizer (``\n`` after the role is its own token).
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("assistant\n", msg_idx, is_sampled=False)
# Build the model-sampled portion (think block + content + tool
# calls). Text segments stay contiguous within each is_sampled
# span to preserve BPE merges.
emit_thinking = self._should_render_thinking(msg_idx, last_query_index) or (
preserve_thinking and bool(reasoning_content)
)
if emit_thinking:
# Include thinking block
emit_text("assistant\n", msg_idx)
emit_special(self._think, msg_idx)
emit_text("\n" + reasoning_content + "\n", msg_idx)
emit_special(self._think_end, msg_idx)
emit_text("\n\n" + content, msg_idx)
emit_special(self._think, msg_idx, is_sampled=True)
emit_text("\n" + reasoning_content + "\n", msg_idx, is_sampled=True)
emit_special(self._think_end, msg_idx, is_sampled=True)
emit_text("\n\n" + content, msg_idx, is_sampled=True)
else:
emit_text("assistant\n" + content, msg_idx)
emit_text(content, msg_idx, is_sampled=True)
# Tool calls
tool_calls = msg.get("tool_calls") or []
@@ -751,13 +801,13 @@ class Qwen35Renderer:
# Separator before <tool_call>
if tc_idx == 0:
if content.strip():
emit_text("\n\n", msg_idx)
emit_text("\n\n", msg_idx, is_sampled=True)
# else: no separator
else:
emit_text("\n", msg_idx)
emit_text("\n", msg_idx, is_sampled=True)
emit_special(self._tool_call, msg_idx)
emit_text("\n<function=" + name + ">\n", msg_idx)
emit_special(self._tool_call, msg_idx, is_sampled=True)
emit_text("\n<function=" + name + ">\n", msg_idx, is_sampled=True)
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
@@ -777,13 +827,17 @@ class Qwen35Renderer:
+ value_str
+ "\n</parameter>\n",
msg_idx,
is_sampled=True,
)
emit_text("</function>\n", msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_text("</function>\n", msg_idx, is_sampled=True)
emit_special(self._tool_call_end, msg_idx, is_sampled=True)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn, so it is part of the sampled stream. The trailing
# ``\n`` is template-appended between turns and never sampled.
emit_special(self._im_end, msg_idx, is_sampled=True)
emit_text("\n", msg_idx, is_sampled=False)
# ------------------------------------------------------------------
# Tool message rendering
@@ -793,26 +847,73 @@ class Qwen35Renderer:
self,
messages: list[Message],
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
emit_image,
) -> None:
# Consecutive tool messages are grouped under a single <|im_start|>user block
# Consecutive tool messages share a single <|im_start|>user ... <|im_end|>
# envelope. Whether to open and close the envelope depends only on the
# neighbouring roles, never on the content type of this or any other
# tool message — keep this predicate text/media-agnostic.
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False. The bridge's
# local emit_special / emit_text accept the is_sampled kwarg for
# signature compatibility but ignore it.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
)
raw_content = messages[msg_idx].get("content")
if not prev_is_tool:
emit_special(self._im_start, msg_idx)
emit_text("user", msg_idx)
emit_special(self._im_start, msg_idx, is_sampled=False)
emit_text("user", msg_idx, is_sampled=False)
emit_text("\n", msg_idx)
emit_special(self._tool_response, msg_idx)
emit_text("\n" + content + "\n", msg_idx)
emit_special(self._tool_response_end, msg_idx)
emit_text("\n", msg_idx, is_sampled=False)
emit_special(self._tool_response, msg_idx, is_sampled=False)
if self._content_has_media(raw_content):
# Mirror the chat template's ``render_content`` macro for list
# content: text segments BPE-encode together up to a media
# boundary, then each image emits ``<|vision_start|>`` + N×
# ``<|image_pad|>`` + ``<|vision_end|>`` inline.
# ``_content_has_media`` returns False unless content is a list,
# but the type checker can't follow that through the call.
assert isinstance(raw_content, list)
buf: list[str] = ["\n"]
def flush_buf() -> None:
if buf:
emit_text("".join(buf), msg_idx, is_sampled=False)
buf.clear()
for item in raw_content:
if isinstance(item, str):
buf.append(item)
elif isinstance(item, dict):
if _is_image_part(item):
flush_buf()
emit_image(item, msg_idx)
elif _is_video_part(item):
raise NotImplementedError(
"Video parts are not yet supported by Qwen35Renderer."
)
elif "text" in item:
buf.append(item["text"])
else:
raise ValueError(f"Unexpected content item: {item}")
else:
raise ValueError(f"Unexpected content item: {item}")
flush_buf()
emit_text("\n", msg_idx, is_sampled=False)
else:
content = self._render_content(raw_content).strip()
emit_text("\n" + content + "\n", msg_idx, is_sampled=False)
emit_special(self._tool_response_end, msg_idx, is_sampled=False)
if not next_is_tool:
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._im_end, msg_idx, is_sampled=False)
emit_text("\n", msg_idx, is_sampled=False)
+139 -70
View File
@@ -70,9 +70,14 @@ def _is_image_part(item: Any) -> bool:
t = item.get("type")
if t in ("image", "image_url"):
return True
# Permissive fallback: chat templates check ``'image' in content`` to
# accept loosely-shaped image parts, so mirror that.
return "image" in item or "image_url" in item
if t is not None:
return False
# Untyped fallback for loosely-shaped image parts. Require a truthy
# value: HF Arrow schema unification (Dataset.from_list over a list of
# heterogeneous content dicts) fills missing keys with None, so any
# text part round-tripped through a Dataset will have ``image_url: None``
# as a key. Mere key presence isn't enough.
return bool(item.get("image")) or bool(item.get("image_url"))
def _is_video_part(item: Any) -> bool:
@@ -81,7 +86,9 @@ def _is_video_part(item: Any) -> bool:
t = item.get("type")
if t in ("video", "video_url"):
return True
return "video" in item or "video_url" in item
if t is not None:
return False
return bool(item.get("video")) or bool(item.get("video_url"))
def _load_pil_image(item: dict[str, Any]):
@@ -162,14 +169,24 @@ class _Emitter:
hit a special token (or end of message). Two text fragments emitted
back-to-back end up in the same flush, exactly matching how the
chat template concatenates string outputs before the final encode.
Per-token ``sampled_mask`` is tracked alongside ``token_ids`` /
``message_indices``: every ``text(..., is_sampled=...)`` and
``special(..., is_sampled=...)`` call stamps its emitted tokens with
the supplied flag. A text fragment with a different ``is_sampled``
value than the current buffer triggers a flush first — split points
are always at the ``is_sampled`` boundary, which the caller is
expected to place at a ``\\n`` boundary so BPE merges don't drift.
"""
def __init__(self, encode_fn, msg_idx: int = -1):
self._encode = encode_fn
self.token_ids: list[int] = []
self.message_indices: list[int] = []
self.sampled: list[bool] = []
self._buf: str = ""
self._buf_idx: int = msg_idx
self._buf_sampled: bool = False
self.msg_idx = msg_idx
def set_msg_idx(self, msg_idx: int) -> None:
@@ -182,22 +199,27 @@ class _Emitter:
self.msg_idx = msg_idx
self._buf_idx = msg_idx
def text(self, text: str) -> None:
def text(self, text: str, *, is_sampled: bool) -> None:
if not text:
return
# Adjacent text under different msg_idx is rare in this template
# — but if it happens, flush so attribution stays accurate.
if self._buf and self._buf_idx != self.msg_idx:
# Adjacent text under different msg_idx or is_sampled is rare in
# this template — but flush at those boundaries so attribution
# and the sampled signal stay accurate.
if self._buf and (
self._buf_idx != self.msg_idx or self._buf_sampled != is_sampled
):
self._flush()
if not self._buf:
self._buf_idx = self.msg_idx
self._buf_sampled = is_sampled
self._buf += text
def special(self, token_id: int) -> None:
def special(self, token_id: int, *, is_sampled: bool) -> None:
if self._buf:
self._flush()
self.token_ids.append(token_id)
self.message_indices.append(self.msg_idx)
self.sampled.append(is_sampled)
def cursor(self) -> int:
"""Current token offset after flushing — used to anchor placeholder ranges."""
@@ -213,6 +235,7 @@ class _Emitter:
ids = self._encode(self._buf)
self.token_ids.extend(ids)
self.message_indices.extend([self._buf_idx] * len(ids))
self.sampled.extend([self._buf_sampled] * len(ids))
self._buf = ""
@@ -384,12 +407,15 @@ class Qwen3VLRenderer:
mm_items: dict[str, list[dict[str, Any]]] = {}
def emit_image(part: dict[str, Any]) -> None:
# Image placeholders are prompt-side scaffolding the user
# message attaches — the model never samples ``<|vision_start|>``
# / ``<|image_pad|>`` / ``<|vision_end|>``.
_, out, n, h = self._process_image(part)
em.special(self._vision_start)
em.special(self._vision_start, is_sampled=False)
offset = em.cursor()
for _ in range(n):
em.special(self._image_pad)
em.special(self._vision_end)
em.special(self._image_pad, is_sampled=False)
em.special(self._vision_end, is_sampled=False)
mm_hashes.setdefault("image", []).append(h)
mm_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -402,16 +428,20 @@ class Qwen3VLRenderer:
)
def render_media_content(content: Any) -> None:
"""Emit a user/tool content list with media handled inline."""
"""Emit a user/tool content list with media handled inline.
User / tool content is conversation context the model never
samples — every text fragment goes in as ``is_sampled=False``.
"""
if isinstance(content, str):
em.text(content)
em.text(content, is_sampled=False)
return
if not isinstance(content, list):
em.text(self._render_text_content(content))
em.text(self._render_text_content(content), is_sampled=False)
return
for item in content:
if isinstance(item, str):
em.text(item)
em.text(item, is_sampled=False)
elif isinstance(item, dict):
if _is_image_part(item):
emit_image(item)
@@ -420,7 +450,7 @@ class Qwen3VLRenderer:
"Video parts are not yet supported by Qwen3VLRenderer."
)
elif "text" in item:
em.text(item["text"])
em.text(item["text"], is_sampled=False)
# ── 1. System + tools ───────────────────────────────────────
first_is_system = messages[0].get("role") == "system"
@@ -428,7 +458,7 @@ class Qwen3VLRenderer:
if tools:
sys_idx = 0 if first_is_system else -1
em.set_msg_idx(sys_idx)
em.special(self._im_start)
em.special(self._im_start, is_sampled=False)
buf = "system\n"
if first_is_system:
buf += self._render_text_content(messages[0].get("content")) + "\n\n"
@@ -436,15 +466,18 @@ class Qwen3VLRenderer:
for tool in tools:
buf += "\n" + json.dumps(tool, ensure_ascii=False)
buf += _TOOLS_FOOTER
em.text(buf)
em.special(self._im_end)
em.text("\n")
em.text(buf, is_sampled=False)
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
elif first_is_system:
em.set_msg_idx(0)
em.special(self._im_start)
em.text("system\n" + self._render_text_content(messages[0].get("content")))
em.special(self._im_end)
em.text("\n")
em.special(self._im_start, is_sampled=False)
em.text(
"system\n" + self._render_text_content(messages[0].get("content")),
is_sampled=False,
)
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
# ── 2. Iterate messages ─────────────────────────────────────
for i, msg in enumerate(messages):
@@ -456,11 +489,11 @@ class Qwen3VLRenderer:
em.set_msg_idx(i)
if role == "user":
em.special(self._im_start)
em.text("user\n")
em.special(self._im_start, is_sampled=False)
em.text("user\n", is_sampled=False)
render_media_content(msg.get("content"))
em.special(self._im_end)
em.text("\n")
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
elif role == "assistant":
self._render_assistant(msg, em)
@@ -474,8 +507,8 @@ class Qwen3VLRenderer:
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
em.set_msg_idx(-1)
em.special(self._im_start)
em.text("assistant\n")
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
em.finalize()
@@ -490,6 +523,8 @@ class Qwen3VLRenderer:
return RenderedTokens(
token_ids=em.token_ids,
message_indices=em.message_indices,
sampled_mask=em.sampled,
message_roles=[m.get("role") or "" for m in messages],
multi_modal_data=mm_data,
)
@@ -506,7 +541,12 @@ class Qwen3VLRenderer:
add_generation_prompt=add_generation_prompt,
).token_ids
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
def parse_response(
self,
token_ids: list[int],
*,
tools: list[ToolSpec] | None = None, # noqa: ARG002 — hermes wire format quotes strings, schema not needed
) -> ParsedResponse:
return parse_qwen3(
self._tokenizer,
token_ids,
@@ -552,11 +592,21 @@ class Qwen3VLRenderer:
if previous_ids is None:
return None
# Bridge populates ``message_indices`` (relative to ``new_messages``)
# and ``sampled_mask`` (uniformly ``False`` — every token the
# bridge emits is template scaffolding for the next prompt, not
# something the model sampled). Downstream consumers can run
# :meth:`RenderedTokens.tokens_per_message` on the bridge output
# to get per-new-message token counts without re-rendering.
em = _Emitter(self._encode)
# Seed the emitter with the prior turn's tokens so cursor() reports
# absolute offsets in the combined sequence.
# absolute offsets in the combined sequence. Per-token attribution
# for the prior portion is unknown to the bridge (it only has
# prev_prompt_ids + prev_completion_ids as raw lists), so seed
# both side channels with the "no info" sentinel.
em.token_ids = list(previous_ids)
em.message_indices = [-1] * len(previous_ids)
em.sampled = [False] * len(previous_ids)
new_hashes: dict[str, list[str]] = {}
new_placeholders: dict[str, list[PlaceholderRange]] = {}
@@ -564,11 +614,11 @@ class Qwen3VLRenderer:
def emit_image(part: dict[str, Any]) -> None:
_, out, n, h = self._process_image(part)
em.special(self._vision_start)
em.special(self._vision_start, is_sampled=False)
offset = em.cursor()
for _ in range(n):
em.special(self._image_pad)
em.special(self._vision_end)
em.special(self._image_pad, is_sampled=False)
em.special(self._vision_end, is_sampled=False)
new_hashes.setdefault("image", []).append(h)
new_placeholders.setdefault("image", []).append(
PlaceholderRange(offset=offset, length=n)
@@ -582,14 +632,14 @@ class Qwen3VLRenderer:
def render_media_content(content: Any) -> None:
if isinstance(content, str):
em.text(content)
em.text(content, is_sampled=False)
return
if not isinstance(content, list):
em.text(self._render_text_content(content))
em.text(self._render_text_content(content), is_sampled=False)
return
for item in content:
if isinstance(item, str):
em.text(item)
em.text(item, is_sampled=False)
elif isinstance(item, dict):
if _is_image_part(item):
emit_image(item)
@@ -598,34 +648,34 @@ class Qwen3VLRenderer:
"Video parts are not yet supported by Qwen3VLRenderer."
)
elif "text" in item:
em.text(item["text"])
em.text(item["text"], is_sampled=False)
em.set_msg_idx(-1)
em.text("\n")
em.text("\n", is_sampled=False)
for i, msg in enumerate(new_messages):
role = msg.get("role")
em.set_msg_idx(i)
if role == "user":
em.special(self._im_start)
em.text("user\n")
em.special(self._im_start, is_sampled=False)
em.text("user\n", is_sampled=False)
render_media_content(msg.get("content"))
em.special(self._im_end)
em.text("\n")
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
elif role == "system":
em.special(self._im_start)
em.text("system\n")
em.special(self._im_start, is_sampled=False)
em.text("system\n", is_sampled=False)
render_media_content(msg.get("content"))
em.special(self._im_end)
em.text("\n")
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
elif role == "tool":
self._render_tool(new_messages, i, em, render_media_content)
else:
return None
em.set_msg_idx(-1)
em.special(self._im_start)
em.text("assistant\n")
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
em.finalize()
# Merge prev mm_data with the new turn's items.
@@ -661,6 +711,9 @@ class Qwen3VLRenderer:
return RenderedTokens(
token_ids=em.token_ids,
message_indices=em.message_indices,
sampled_mask=em.sampled,
message_roles=[m.get("role") or "" for m in new_messages],
multi_modal_data=mm_data,
)
@@ -669,18 +722,24 @@ class Qwen3VLRenderer:
original_content = msg.get("content")
tool_calls = msg.get("tool_calls") or []
em.special(self._im_start)
# ``<|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. Splitting the text
# at the ``\n`` after the role tag is safe: Qwen3 BPE treats
# ``\n`` as a token boundary.
em.special(self._im_start, is_sampled=False)
em.text("assistant\n", is_sampled=False)
prefix = "assistant\n" + content
# Body (content + tool calls) is the model-sampled portion.
if not tool_calls:
em.text(prefix)
em.text(content, is_sampled=True)
else:
for tc_idx, tc in enumerate(tool_calls):
if tc_idx == 0:
separator = "\n" if original_content else ""
em.text(prefix + separator)
em.text(content + separator, is_sampled=True)
else:
em.text("\n")
em.text("\n", is_sampled=True)
func = tc.get("function") or tc
name = func.get("name", "")
@@ -691,12 +750,18 @@ class Qwen3VLRenderer:
else json.dumps(arguments, ensure_ascii=False)
)
em.special(self._tool_call)
em.text('\n{"name": "' + name + '", "arguments": ' + args_str + "}\n")
em.special(self._tool_call_end)
em.special(self._tool_call, is_sampled=True)
em.text(
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
is_sampled=True,
)
em.special(self._tool_call_end, is_sampled=True)
em.special(self._im_end)
em.text("\n")
# ``<|im_end|>`` is the model's stop signal — it samples this to
# end its turn. The trailing ``\n`` is template-appended between
# turns and never sampled.
em.special(self._im_end, is_sampled=True)
em.text("\n", is_sampled=False)
def _render_tool(
self,
@@ -705,22 +770,26 @@ class Qwen3VLRenderer:
em: _Emitter,
render_media_content,
) -> None:
# Tool messages are conversation history injected by the runtime
# between assistant turns — the model never samples any of these
# tokens, so every emission is is_sampled=False. (render_media_content
# also stamps is_sampled=False on its emissions.)
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
next_is_tool = (
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
)
if not prev_is_tool:
em.special(self._im_start)
em.text("user")
em.special(self._im_start, is_sampled=False)
em.text("user", is_sampled=False)
em.text("\n")
em.special(self._tool_response)
em.text("\n")
em.text("\n", is_sampled=False)
em.special(self._tool_response, is_sampled=False)
em.text("\n", is_sampled=False)
render_media_content(messages[msg_idx].get("content"))
em.text("\n")
em.special(self._tool_response_end)
em.text("\n", is_sampled=False)
em.special(self._tool_response_end, is_sampled=False)
if not next_is_tool:
em.special(self._im_end)
em.text("\n")
em.special(self._im_end, is_sampled=False)
em.text("\n", is_sampled=False)
+1
View File
@@ -32,6 +32,7 @@ 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"),
("poolside/Laguna-XS.2", "auto"),
("openai/gpt-oss-20b", "gpt-oss"),
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
]
+236 -40
View File
@@ -2,8 +2,13 @@ import asyncio
import base64
import numpy as np
from renderers.base import ParsedResponse, RenderedTokens
import pytest
from renderers.base import (
ParsedResponse,
ParsedToolCall,
RenderedTokens,
ToolCallParseStatus,
)
from renderers.client import generate
@@ -24,18 +29,22 @@ class _FakeRenderer:
def get_stop_token_ids(self):
return [99]
def parse_response(self, completion_ids: list[int]) -> ParsedResponse:
def parse_response(
self, completion_ids: list[int], *, tools=None
) -> ParsedResponse:
assert completion_ids == [7, 8]
# Stores tools so tests can assert the client plumbed them through.
self._last_parse_tools = tools
return ParsedResponse(
content="done",
reasoning_content="think",
tool_calls=[
{
"function": {
"name": "echo",
"arguments": {"text": "hello"},
}
}
ParsedToolCall(
raw='{"name": "echo", "arguments": {"text": "hello"}}',
name="echo",
arguments={"text": "hello"},
status=ToolCallParseStatus.OK,
)
],
)
@@ -80,11 +89,12 @@ class _FakeClient:
def test_generate_builds_request_body_and_parses_response():
client = _FakeClient()
renderer = _FakeRenderer()
result = asyncio.run(
generate(
client=client,
renderer=_FakeRenderer(),
renderer=renderer,
messages=[{"role": "user", "content": "hi"}],
model="test-model",
tools=[{"type": "function", "function": {"name": "echo"}}],
@@ -93,6 +103,12 @@ def test_generate_builds_request_body_and_parses_response():
)
)
# The client must plumb `tools` through to parse_response so XML-style
# parsers can preserve declared-string args verbatim.
assert renderer._last_parse_tools == [
{"type": "function", "function": {"name": "echo"}}
]
assert len(client.calls) == 1
# /inference/v1/generate is mounted at the server root, so we post to
# an absolute URL stripped of the OpenAI SDK's automatic /v1 prefix.
@@ -111,26 +127,61 @@ def test_generate_builds_request_body_and_parses_response():
},
}
# finish_reason promoted from "stop" → "tool_calls" because the renderer
# extracted tool calls client-side.
assert result == {
"request_id": "gen-test",
"prompt_ids": [1, 2, 3],
"completion_ids": [7, 8],
"completion_logprobs": [-0.1, -0.2],
"content": "done",
"reasoning_content": "think",
"tool_calls": [
{
"function": {
"name": "echo",
"arguments": {"text": "hello"},
}
}
],
"finish_reason": "tool_calls",
"routed_experts": [[[1]], [[2]]],
"multi_modal_data": None,
}
# extracted at least one well-formed tool call client-side.
assert result["finish_reason"] == "tool_calls"
assert result["content"] == "done"
assert result["reasoning_content"] == "think"
assert result["prompt_ids"] == [1, 2, 3]
assert result["completion_ids"] == [7, 8]
assert result["completion_logprobs"] == [-0.1, -0.2]
assert result["routed_experts"] == [[[1]], [[2]]]
assert result["multi_modal_data"] is None
assert result["request_id"] == "gen-test"
assert len(result["tool_calls"]) == 1
tc = result["tool_calls"][0]
assert tc.name == "echo"
assert tc.arguments == {"text": "hello"}
assert tc.status == ToolCallParseStatus.OK
class _MalformedToolRenderer(_FakeRenderer):
"""Returns only a malformed tool-call attempt — finish_reason must stay "stop"."""
def parse_response(
self, completion_ids: list[int], *, tools=None
) -> ParsedResponse:
return ParsedResponse(
content="",
reasoning_content=None,
tool_calls=[
ParsedToolCall(
raw='{"name": "echo", broken',
status=ToolCallParseStatus.INVALID_JSON,
)
],
)
def test_generate_does_not_promote_finish_reason_for_malformed_tool_calls():
"""A malformed tool-call attempt must NOT promote finish_reason to
"tool_calls" — only well-formed (status=OK) calls qualify. The
malformed attempt is still preserved in ``tool_calls`` for verifier
inspection, but the agent loop should not treat the turn as a
successful tool invocation.
"""
client = _FakeClient()
result = asyncio.run(
generate(
client=client,
renderer=_MalformedToolRenderer(),
messages=[{"role": "user", "content": "hi"}],
model="test-model",
tools=[{"type": "function", "function": {"name": "echo"}}],
)
)
assert result["finish_reason"] == "stop"
assert len(result["tool_calls"]) == 1
assert result["tool_calls"][0].status == ToolCallParseStatus.INVALID_JSON
class _NoRenderRenderer(_FakeRenderer):
@@ -163,30 +214,42 @@ def test_generate_uses_prebuilt_prompt_ids_without_rendering():
# ---------------------------------------------------------------------------
def test_generate_serializes_multimodal_features_for_qwen3_vl():
@pytest.mark.parametrize(
"model_id,renderer_class_path",
[
("Qwen/Qwen3-VL-4B-Instruct", "renderers.qwen3_vl:Qwen3VLRenderer"),
("Qwen/Qwen3.5-2B", "renderers.qwen35:Qwen35Renderer"),
],
ids=["qwen3_vl", "qwen35"],
)
def test_generate_serializes_multimodal_features_for_qwen_vl_family(
model_id, renderer_class_path
):
"""When the renderer emits ``MultiModalData``, ``generate`` translates
it into vLLM's ``features`` payload (mm_hashes + mm_placeholders +
base64-encoded kwargs_data) and sticks it in the request body."""
import pytest as _pytest
base64-encoded kwargs_data) and sticks it in the request body. Covers
every renderer routed through ``_build_qwen_vl_features``."""
import importlib
_pytest.importorskip("torch")
_pytest.importorskip("vllm", reason="vllm needed for features serialization")
pytest.importorskip("torch")
pytest.importorskip("vllm", reason="vllm needed for features serialization")
import torch as _torch
from renderers.base import (
MultiModalData,
PlaceholderRange,
load_tokenizer,
)
from renderers.qwen3_vl import Qwen3VLRenderer
# Build a minimal real Qwen3VLRenderer so type dispatch in
mod_name, cls_name = renderer_class_path.split(":")
renderer_cls = getattr(importlib.import_module(mod_name), cls_name)
# Build a minimal real renderer so type dispatch in
# _build_mm_features hits the qwen branch. The tokenizer is only
# touched in __init__ to grab special-token ids; render() / etc.
# aren't called here because we pre-supply prompt_ids + mm_data.
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
renderer = Qwen3VLRenderer(tokenizer)
tokenizer = load_tokenizer(model_id)
renderer = renderer_cls(tokenizer)
# Two synthetic 1×2×2 images. Field factory expects pixel_values
# shape ``(sum_HW, embed_dim)`` and grid_thw shape ``(N, 3)``; the
@@ -240,3 +303,136 @@ def test_generate_serializes_multimodal_features_for_qwen3_vl():
# Items are base64 strings (encode_mm_kwargs_item output).
for item in features["kwargs_data"]["image"]:
assert isinstance(item, str) and len(item) > 0
# ---------------------------------------------------------------------------
# Prompt overflow handling.
# ---------------------------------------------------------------------------
class _LongRenderer(_FakeRenderer):
"""Renders a 10-token prompt regardless of input — enough to overflow a
small ``max_prompt_len``."""
def render(self, messages, *, tools=None, add_generation_prompt=False):
from renderers.base import RenderedTokens
return RenderedTokens(token_ids=list(range(10)))
def test_generate_raises_overlong_prompt_when_explicit_cap_exceeded():
"""Pre-flight overflow check: when an explicit ``max_prompt_len`` is set
and the rendered prompt is longer, ``generate`` raises
``OverlongPromptError`` without dispatching the request to the engine."""
from renderers.client import OverlongPromptError
client = _FakeClient()
renderer = _LongRenderer()
with pytest.raises(OverlongPromptError) as excinfo:
asyncio.run(
generate(
client=client,
renderer=renderer,
messages=[{"role": "user", "content": "hi"}],
model="test-model",
max_prompt_len=4,
)
)
assert excinfo.value.prompt_len == 10
assert excinfo.value.max_prompt_len == 4
assert client.calls == [], "request must not be dispatched on pre-flight fail"
def test_generate_allows_prompt_at_max_prompt_len():
"""A prompt exactly equal to ``max_prompt_len`` is allowed (the check is
strict ``>``); only longer prompts trip the pre-flight."""
client = _FakeClient()
renderer = _LongRenderer()
result = asyncio.run(
generate(
client=client,
renderer=renderer,
messages=[{"role": "user", "content": "hi"}],
model="test-model",
max_prompt_len=10,
)
)
assert len(client.calls) == 1
assert result["prompt_ids"] == list(range(10))
def test_generate_auto_discovers_max_prompt_len_from_models_endpoint():
"""When ``max_prompt_len`` is ``None`` (default), ``generate`` discovers
the cap via ``GET /v1/models`` and reads ``ModelCard.max_model_len``.
The result is cached per ``(base_url, model)`` so subsequent calls
don't re-query."""
from renderers.client import OverlongPromptError, _max_prompt_len_cache
class _ClientWithModels(_FakeClient):
def __init__(self):
super().__init__()
self.base_url = "http://disco-host:8000/v1"
self.models_calls = 0
async def get(self, path, *, cast_to):
self.models_calls += 1
assert path == "/models"
return {
"object": "list",
"data": [
{"id": "test-model", "max_model_len": 4},
{"id": "other", "max_model_len": 999},
],
}
# Clear cache so this test isn't affected by earlier ones.
_max_prompt_len_cache.clear()
client = _ClientWithModels()
renderer = _LongRenderer()
with pytest.raises(OverlongPromptError) as excinfo:
asyncio.run(
generate(
client=client,
renderer=renderer,
messages=[{"role": "user", "content": "hi"}],
model="test-model",
)
)
assert excinfo.value.max_prompt_len == 4
assert excinfo.value.prompt_len == 10
assert client.models_calls == 1, "lookup must hit /models once"
assert client.calls == [], "pre-flight must short-circuit the request"
def test_generate_caches_max_prompt_len_lookup_failure():
"""When ``GET /v1/models`` fails (e.g. mock client without ``.get``),
the lookup result is cached as ``None`` and the pre-flight quietly
disables — the request still goes through, callers fall back to
whatever reactive overflow handling they have."""
from renderers.client import _max_prompt_len_cache
# _FakeClient has no .get method → AttributeError → cached None.
_max_prompt_len_cache.clear()
client = _FakeClient()
client.base_url = "http://no-models:8000/v1"
result = asyncio.run(
generate(
client=client,
renderer=_LongRenderer(),
messages=[{"role": "user", "content": "hi"}],
model="test-model",
)
)
# Request was dispatched (no pre-flight rejection) and round-tripped.
assert len(client.calls) == 1
assert result["prompt_ids"] == list(range(10))
assert _max_prompt_len_cache[("http://no-models:8000/v1", "test-model")] is None
+172
View File
@@ -0,0 +1,172 @@
"""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; MiniMax tokenizers diverge on literal
special-token text). 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",
"MiniMaxAI/MiniMax-M2",
"MiniMaxAI/MiniMax-M2.5",
}
)
# ---------------------------------------------------------------------------
# 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 or "MiniMax" 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
+206
View File
@@ -299,11 +299,142 @@ def _build_cases(make_part, image):
]
def _build_tool_image_cases(make_part, image):
"""Tool-message image scenarios. Targets renderers that emit image
placeholders inside ``<tool_response>`` blocks. Browser-agent style
trajectories produce post-action screenshots as tool responses, so
handling images here is load-bearing for that workload."""
return [
pytest.param(
[
{"role": "user", "content": "Take a screenshot."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c1",
"type": "function",
"function": {"name": "screenshot", "arguments": {}},
}
],
},
{
"role": "tool",
"tool_call_id": "c1",
"content": [
{"type": "text", "text": "Screenshot captured."},
make_part(image),
],
},
],
False,
id="tool_response_with_image",
),
pytest.param(
[
{"role": "user", "content": "Screenshot then describe."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c1",
"type": "function",
"function": {"name": "screenshot", "arguments": {}},
}
],
},
{
"role": "tool",
"tool_call_id": "c1",
"content": [
{"type": "text", "text": "Done:"},
make_part(image),
],
},
{"role": "assistant", "content": "A square."},
{"role": "user", "content": "Now show me the next page."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c2",
"type": "function",
"function": {"name": "screenshot", "arguments": {}},
}
],
},
{
"role": "tool",
"tool_call_id": "c2",
"content": [
{"type": "text", "text": "Next page:"},
make_part(image),
],
},
],
False,
id="multi_turn_tool_response_images",
),
pytest.param(
[
{"role": "user", "content": "Run a few tools."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c1",
"type": "function",
"function": {"name": "ping", "arguments": {}},
},
{
"id": "c2",
"type": "function",
"function": {"name": "screenshot", "arguments": {}},
},
{
"id": "c3",
"type": "function",
"function": {"name": "ping", "arguments": {}},
},
],
},
{"role": "tool", "tool_call_id": "c1", "content": "pong"},
{
"role": "tool",
"tool_call_id": "c2",
"content": [
{"type": "text", "text": "Screenshot:"},
make_part(image),
],
},
{"role": "tool", "tool_call_id": "c3", "content": "pong"},
],
False,
id="consecutive_tools_mixed_media",
),
]
# ---------------------------------------------------------------------------
# Tests.
# ---------------------------------------------------------------------------
def _supports_tool_message_images(renderer) -> bool:
"""True iff this renderer emits image placeholders inside tool-response
content. Renderers without the feature silently drop image parts in tool
content; as they grow the feature they get added here and the test starts
asserting against them."""
from renderers.kimi_k25 import KimiK25Renderer
from renderers.qwen35 import Qwen35Renderer
return isinstance(renderer, (Qwen35Renderer, KimiK25Renderer))
@pytest.mark.parametrize(
"mm_model_name,modality", _CASES, ids=[f"{m}|{mo}" for m, mo in _CASES]
)
@@ -513,6 +644,44 @@ def test_modality_registry_models_route_to_renderer():
)
@pytest.mark.parametrize(
"mm_model_name,modality", _CASES, ids=[f"{m}|{mo}" for m, mo in _CASES]
)
def test_tool_response_image_byte_parity(mm_model_name, modality, tiny_image):
"""Tool-message image parity vs ``processor.apply_chat_template`` + ``processor(...)``.
Browser-agent SFT traces carry post-action screenshots as ``tool``
responses. Renderers that drop those image parts silently — historically
every Qwen-VL family renderer did — produce token streams that diverge
from the HF processor and lose most of the visual learning signal.
Skipped for renderers that haven't grown the feature yet; flips to a
real assertion as they do.
"""
if modality != "image":
pytest.skip("Tool-response media path is image-only for now.")
if not _hf_snapshot_cached(mm_model_name):
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
kit = _modality_kit(modality, mm_model_name)
tokenizer, processor, renderer = _load_processor_and_renderer(mm_model_name)
if not _supports_tool_message_images(renderer):
pytest.skip(
f"{type(renderer).__name__} does not yet emit images inside tool responses"
)
for case in _build_tool_image_cases(kit["make_part"], tiny_image):
messages, add_gp = case.values
ours = renderer.render_ids(messages, add_generation_prompt=add_gp)
theirs = kit["processor_input_ids"](processor, messages, add_gp)
assert ours == theirs, (
f"{mm_model_name} / tool / case={case.id}: "
f"renderer diverges from processor.\n"
f" len(ours)={len(ours)} len(theirs)={len(theirs)}\n"
f" ours[:60]={ours[:60]}\n theirs[:60]={theirs[:60]}"
)
def test_qwen3_vl_renderer_exposes_image_modality():
"""The flagship multimodal renderer is concretely Qwen3VLRenderer.
@@ -526,3 +695,40 @@ def test_qwen3_vl_renderer_exposes_image_modality():
renderer = create_renderer(tokenizer, renderer="auto")
assert isinstance(renderer, Qwen3VLRenderer)
assert "image" in MULTIMODAL_MODELS[model]
def test_is_image_part_treats_type_field_as_authoritative():
"""``Dataset.from_list`` unifies the Arrow schema across the elements
of a list-typed column. A content list mixing text and image parts
round-trips with ``image_url: None`` added to every text part (and
``text: None`` added to every image part). The classifier must treat
the ``type`` field as authoritative when present — falling back to
a key-presence check on ``image_url`` would misclassify the text
part and the renderer would later raise on ``_load_pil_image(None)``.
"""
from renderers.qwen3_vl import _is_image_part, _is_video_part
# Typed parts classify by their ``type``.
assert _is_image_part(
{"type": "image_url", "image_url": {"url": "data:image/png;base64,XXX"}}
)
assert _is_image_part({"type": "image", "image": object()})
assert _is_video_part(
{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,XXX"}}
)
# Schema-unified text parts — typed as text, with a None zombie key
# for the sibling modality — must NOT classify as image / video.
schema_unified_text = {"type": "text", "text": "hello", "image_url": None}
assert not _is_image_part(schema_unified_text)
assert not _is_video_part(schema_unified_text)
schema_unified_text_with_video = {"type": "text", "text": "hi", "video_url": None}
assert not _is_video_part(schema_unified_text_with_video)
# Untyped fallback only fires when ``type`` is absent, and requires
# a truthy value (mere key presence isn't enough).
assert _is_image_part({"image_url": {"url": "data:..."}})
assert _is_image_part({"image": object()})
assert not _is_image_part({"image_url": None})
assert not _is_image_part({"image": None})
assert not _is_video_part({"video_url": None})
+62 -20
View File
@@ -7,7 +7,7 @@ Runs against every (model, renderer) pair.
from functools import lru_cache
from renderers import create_renderer
from renderers.base import load_tokenizer
from renderers.base import ToolCallParseStatus, load_tokenizer
@lru_cache
@@ -62,18 +62,26 @@ def test_qwen3_vl_parse_json_tool_call():
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert parsed.content == "Need a tool."
assert parsed.tool_calls == [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
]
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "get_weather"
assert tc.arguments == {"city": "Paris"}
def test_qwen3_vl_malformed_tool_call_falls_back_to_content():
"""When <tool_call>...</tool_call> contains malformed JSON, match
vLLM's hermes_tool_parser behavior: preserve the raw tokens as
content rather than returning empty content + empty tool_calls.
Without this, the orchestrator raises EmptyModelResponseError and
wastes inference compute on retries — diverging from main's
behavior on hermes tool envs (Qwen3, etc.).
def test_qwen3_vl_malformed_tool_call_surfaces_as_invalid_json():
"""A malformed ``<tool_call>`` block lands as a non-OK ``ParsedToolCall``
rather than getting silently merged back into ``content``.
Before the per-call status redesign, the parser mirrored vLLM's
hermes parser and stuffed the raw block into ``content`` to avoid
downstream ``EmptyModelResponseError``. That hid the malformed signal
from verifiers — they couldn't tell "model wrote prose" from "model
tried a tool call and produced broken JSON." Now the failed attempt
is preserved with ``status=INVALID_JSON`` and ``raw`` text, which
also satisfies the EmptyModelResponseError prevention contract: the
response is non-empty (it has a tool-call attempt) without lying
about what kind of output the model produced.
"""
tokenizer, renderer = _qwen3_vl()
# Note the trailing comma — malformed JSON
@@ -83,13 +91,47 @@ def test_qwen3_vl_malformed_tool_call_falls_back_to_content():
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
# Parser must not collapse response: either content has the raw
# tokens OR there's at least a tool_call attempt. Concretely, we
# want content to be non-empty so the caller doesn't raise
# EmptyModelResponseError.
assert parsed.tool_calls is None, "Malformed JSON should not parse as a tool call"
assert parsed.content, (
"Malformed tool_call should fall back to raw content, not empty "
"(else caller raises EmptyModelResponseError)"
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.INVALID_JSON
assert "get_weather" in tc.raw
assert tc.token_span is not None
@lru_cache
def _kimi_k25():
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
renderer = create_renderer(tokenizer, renderer="auto")
return tokenizer, renderer
def test_kimi_k25_tool_call_carries_token_span():
"""K2.5 was the lone parser without token spans before — its inline
text-walking implementation couldn't cheaply map regex hits back to
token offsets. We now walk token IDs via ``parse_kimi_k2_section`` for
the special-token path; spans must round-trip and point at a sensible
range within the original input token_ids.
"""
tokenizer, renderer = _kimi_k25()
# K2.5 tool-call wire shape: section + per-call special tokens.
text = (
"<|tool_calls_section_begin|>"
"<|tool_call_begin|>functions.get_weather:0"
"<|tool_call_argument_begin|>"
'{"city": "Tokyo"}'
"<|tool_call_end|>"
"<|tool_calls_section_end|>"
)
token_ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(token_ids)
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "get_weather"
assert tc.arguments == {"city": "Tokyo"}
assert tc.token_span is not None
start, end = tc.token_span
assert 0 <= start < end <= len(token_ids), (
f"span {tc.token_span} out of range for {len(token_ids)} input tokens"
)
assert "get_weather" in parsed.content
+13 -7
View File
@@ -4,7 +4,7 @@ These test that parse_response never crashes and returns sensible results
even with adversarial or truncated model output.
"""
from renderers.base import ParsedResponse
from renderers.base import ParsedResponse, ParsedToolCall
# ── Truncation ───────────────────────────────────────────────────────
@@ -78,7 +78,7 @@ def test_content_only_no_thinking(model_name, tokenizer, renderer):
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert "Hello" in parsed.content
assert parsed.tool_calls is None
assert parsed.tool_calls == []
# ── Tool call edge cases ─────────────────────────────────────────────
@@ -128,11 +128,17 @@ def test_reasoning_is_string_or_none(model_name, tokenizer, renderer):
assert parsed.reasoning_content is None or isinstance(parsed.reasoning_content, str)
def test_tool_calls_is_list_or_none(model_name, tokenizer, renderer):
"""tool_calls must be list or None, never empty list."""
def test_tool_calls_is_list_of_parsed_tool_call(model_name, tokenizer, renderer):
"""tool_calls is always a (possibly empty) list of ParsedToolCall — never None.
Empty list = "model did not emit any tool calls". A list with non-OK
entries = "model tried and the parser caught the failure"; those are
deliberately preserved so verifier / RL-loss code can see them. This
replaces the older list-or-None convention.
"""
text = "Hello!"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert parsed.tool_calls is None or (
isinstance(parsed.tool_calls, list) and len(parsed.tool_calls) > 0
)
assert isinstance(parsed.tool_calls, list)
for tc in parsed.tool_calls:
assert isinstance(tc, ParsedToolCall)
+46 -8
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import pytest
from renderers.base import load_tokenizer
from renderers.base import ToolCallParseStatus, load_tokenizer
from renderers.parsers import (
REASONING_PARSERS,
TOOL_PARSERS,
@@ -40,9 +40,12 @@ def test_qwen3_tool_parser_roundtrip():
completion_text = 'hello\n<tool_call>\n{"name": "search", "arguments": {"q": "rain"}}\n</tool_call>'
token_ids = tok.encode(completion_text, add_special_tokens=False)
content_ids, tool_calls = parser.extract(list(token_ids))
assert tool_calls is not None
assert tool_calls[0]["function"]["name"] == "search"
assert tool_calls[0]["function"]["arguments"] == {"q": "rain"}
assert len(tool_calls) == 1
tc = tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "search"
assert tc.arguments == {"q": "rain"}
assert tc.token_span is not None and tc.token_span[0] < tc.token_span[1]
# content_ids should cover everything up to (but not including) <tool_call>
content_text = tok.decode(content_ids, skip_special_tokens=False)
assert "hello" in content_text
@@ -54,10 +57,44 @@ def test_qwen3_tool_parser_no_tool_call():
parser = get_tool_parser("qwen3", tok)
ids = tok.encode("just plain text response", add_special_tokens=False)
content_ids, tool_calls = parser.extract(list(ids))
assert tool_calls is None
assert tool_calls == []
assert content_ids == list(ids)
def test_qwen3_tool_parser_records_invalid_json():
"""Malformed JSON in a <tool_call> block surfaces as INVALID_JSON, not silently dropped."""
tok = load_tokenizer("Qwen/Qwen3-0.6B")
parser = get_tool_parser("qwen3", tok)
completion = (
'hi\n<tool_call>\n{"name": "f", "arguments": {broken json\n</tool_call>'
)
ids = tok.encode(completion, add_special_tokens=False)
_, tool_calls = parser.extract(list(ids))
assert len(tool_calls) == 1
assert tool_calls[0].status == ToolCallParseStatus.INVALID_JSON
assert tool_calls[0].raw # raw block text preserved
def test_qwen3_tool_parser_parallel_partial_success():
"""Parallel calls: parser keeps the good ones AND records the broken one."""
tok = load_tokenizer("Qwen/Qwen3-0.6B")
parser = get_tool_parser("qwen3", tok)
completion = (
"pre\n"
'<tool_call>\n{"name": "a", "arguments": {}}\n</tool_call>\n'
"<tool_call>\n{broken\n</tool_call>\n"
'<tool_call>\n{"name": "c", "arguments": {"x": 1}}\n</tool_call>'
)
ids = tok.encode(completion, add_special_tokens=False)
_, tool_calls = parser.extract(list(ids))
assert [tc.status for tc in tool_calls] == [
ToolCallParseStatus.OK,
ToolCallParseStatus.INVALID_JSON,
ToolCallParseStatus.OK,
]
assert [tc.name for tc in tool_calls] == ["a", None, "c"]
def test_think_reasoning_parser_extracts_block():
tok = load_tokenizer("Qwen/Qwen3-0.6B")
parser = get_reasoning_parser("think", tok)
@@ -90,8 +127,9 @@ def test_default_renderer_uses_parsers():
parsed = renderer.parse_response(list(ids))
assert parsed.reasoning_content == "think"
assert parsed.content.startswith("ok")
assert parsed.tool_calls is not None
assert parsed.tool_calls[0]["function"]["name"] == "f"
assert len(parsed.tool_calls) == 1
assert parsed.tool_calls[0].name == "f"
assert parsed.tool_calls[0].status == ToolCallParseStatus.OK
def test_default_renderer_without_parsers_is_backward_compatible():
@@ -106,4 +144,4 @@ def test_default_renderer_without_parsers_is_backward_compatible():
parsed = renderer.parse_response(list(ids))
assert parsed.reasoning_content == "r"
assert parsed.content == "a"
assert parsed.tool_calls is None
assert parsed.tool_calls == []
+1
View File
@@ -42,6 +42,7 @@ NO_OP_MODELS = {
"Qwen/Qwen3-VL-4B-Instruct",
"Qwen/Qwen3-VL-8B-Instruct",
"Qwen/Qwen3-VL-30B-A3B-Instruct",
"poolside/Laguna-XS.2",
}
+10 -15
View File
@@ -43,6 +43,7 @@ _ROUNDTRIP_MODELS = [
("moonshotai/Kimi-K2.6", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
("poolside/Laguna-XS.2", "auto"),
("openai/gpt-oss-20b", "gpt-oss"),
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
]
@@ -158,8 +159,8 @@ def test_roundtrip_reasoning_and_content(rt_model, rt_tokenizer, rt_renderer):
def _maybe_skip_tool_calls(renderer_name: str) -> None:
"""DefaultRenderer without a tool_parser configured always returns
tool_calls=None. That's a documented limitation, not a bug — skip."""
"""DefaultRenderer without a tool_parser configured always returns an
empty tool_calls list. That's a documented limitation, not a bug — skip."""
if renderer_name == "default":
pytest.skip(
"DefaultRenderer requires an explicit tool_parser to parse tool "
@@ -194,11 +195,9 @@ def test_roundtrip_single_tool_call(
assert parsed.tool_calls, f"{rt_model}: tool_calls lost, got {parsed.tool_calls!r}"
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc["function"]["name"] == "get_weather", (
f"{rt_model}: name mangled, got {tc!r}"
)
assert _normalize_args(tc["function"]["arguments"]) == {"city": "Tokyo"}, (
f"{rt_model}: args mangled, got {tc['function']['arguments']!r}"
assert tc.name == "get_weather", f"{rt_model}: name mangled, got {tc!r}"
assert _normalize_args(tc.arguments) == {"city": "Tokyo"}, (
f"{rt_model}: args mangled, got {tc.arguments!r}"
)
@@ -235,19 +234,15 @@ def test_roundtrip_multiple_tool_calls(
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
assert parsed.tool_calls is not None and len(parsed.tool_calls) == 2, (
assert len(parsed.tool_calls) == 2, (
f"{rt_model}: expected 2 tool_calls, got {parsed.tool_calls!r}"
)
names = [tc["function"]["name"] for tc in parsed.tool_calls]
names = [tc.name for tc in parsed.tool_calls]
assert names == ["get_weather", "get_time"], (
f"{rt_model}: names/order wrong, got {names}"
)
assert _normalize_args(parsed.tool_calls[0]["function"]["arguments"]) == {
"city": "Tokyo"
}
assert _normalize_args(parsed.tool_calls[1]["function"]["arguments"]) == {
"zone": "JST"
}
assert _normalize_args(parsed.tool_calls[0].arguments) == {"city": "Tokyo"}
assert _normalize_args(parsed.tool_calls[1].arguments) == {"zone": "JST"}
# ── byte-exact re-render invariant ─────────────────────────────────────
+119
View File
@@ -0,0 +1,119 @@
"""Per-token ``RenderedTokens.sampled_mask`` invariants.
``sampled_mask[k]`` answers "would the model have produced
``token_ids[k]`` at inference?" — distinct from ``message_indices``,
which only attributes a token to a source message. SFT loss masks
should AND both signals so the trainer only sees tokens the model
would actually sample.
These tests parametrise across every renderer in ``conftest.RENDERER_MODELS``
and verify the contract for hand-coded renderers. ``DefaultRenderer``
leaves ``sampled_mask`` empty by design (the Jinja template is opaque,
so the renderer cannot know the prompt / completion split) and is
exempt from the populated-length check.
"""
from __future__ import annotations
def test_sampled_mask_length_or_empty(model_name, renderer):
"""``sampled_mask`` is either empty (opt-out) or matches token_ids
length exactly. No partial fills."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
n_tokens = len(rendered.token_ids)
n_mask = len(rendered.sampled_mask)
assert n_mask == 0 or n_mask == n_tokens, (
f"{model_name}: sampled_mask length {n_mask} must be 0 or match "
f"token_ids length {n_tokens}"
)
def test_sampled_mask_excludes_user_and_system(model_name, renderer):
"""Every token attributed to a user / system / tool message must be
is_sampled=False — the model never samples conversation history.
Skips renderers that don't populate sampled_mask (DefaultRenderer)."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return # renderer opted out
bad = []
for k, (msg_idx, is_sampled) in enumerate(
zip(rendered.message_indices, rendered.sampled_mask)
):
if msg_idx < 0:
continue
role = msgs[msg_idx].get("role")
if role in ("user", "system", "tool") and is_sampled:
bad.append((k, role, msg_idx))
assert not bad, (
f"{model_name}: non-assistant tokens marked is_sampled=True "
f"(k, role, msg_idx): {bad[:8]}"
)
def test_sampled_mask_excludes_generation_prompt(model_name, renderer):
"""All generation-prompt tokens (msg_idx=-1 when add_generation_prompt=True)
must be is_sampled=False — they are template-injected scaffolding the
model continues from, not samples."""
msgs = [{"role": "user", "content": "Hi"}]
rendered = renderer.render(msgs, add_generation_prompt=True)
if not rendered.sampled_mask:
return
bad = [
k
for k, (msg_idx, is_sampled) in enumerate(
zip(rendered.message_indices, rendered.sampled_mask)
)
if msg_idx == -1 and is_sampled
]
assert not bad, (
f"{model_name}: generation-prompt tokens marked is_sampled=True "
f"at positions {bad[:8]}"
)
def test_sampled_mask_assistant_role_tag_excluded(model_name, renderer):
"""The leading ``<|im_start|>{role}\\n`` (or equivalent role-tag run)
on an assistant message must be is_sampled=False — the chat template
emits it as part of the generation prompt at inference, so the model
never samples it. Asserts that the *first* token attributed to an
assistant message is is_sampled=False; the last token (turn-close
signal) should be is_sampled=True."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello world!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return
assistant_positions = [
k for k, idx in enumerate(rendered.message_indices) if idx == 1
]
assert assistant_positions, (
f"{model_name}: no tokens attributed to assistant message"
)
first_k = assistant_positions[0]
assert not rendered.sampled_mask[first_k], (
f"{model_name}: first assistant-attributed token at k={first_k} "
f"should be is_sampled=False (role-tag scaffolding), but was True"
)
# At least one assistant-attributed token must be is_sampled=True
# (the content + turn close — otherwise the loss mask is empty).
any_sampled = any(rendered.sampled_mask[k] for k in assistant_positions)
assert any_sampled, (
f"{model_name}: no assistant tokens marked is_sampled=True — the "
f"resulting SFT loss mask would be empty"
)
+325
View File
@@ -0,0 +1,325 @@
"""Tests for per-message / per-role token-count and span helpers.
These methods on :class:`RenderedTokens` derive from the existing
``message_indices`` / ``sampled_mask`` / ``message_roles`` signals —
they're analytics helpers, not new attribution. The contract these
tests pin:
- ``sum(tokens_per_message()) + scaffold_count == len(token_ids)`` — the
helper accounts for every token exactly once, with ``-1``-attributed
scaffolding outside the per-message bucket.
- ``sampled_only=True`` excludes the role-tag opener
(``<|im_start|>role\\n``) the template injects around an assistant
message. The assistant message's sampled count must be strictly less
than its total count.
- ``sampled_only=True`` is zero for tool / user / system roles — the
model never samples conversation history.
- ``message_token_spans`` returns contiguous ``(start, end)`` slices
per message that ``zip``s against ``message_roles``. Slicing
``token_ids[start:end]`` recovers the message's tokens.
Renderers that opt out of ``sampled_mask`` (DefaultRenderer — the
Jinja template is opaque) are exempt from the ``sampled_only``
assertions and return all zeros from the helper under that flag.
"""
from __future__ import annotations
from renderers.base import RenderedTokens
def test_tokens_per_message_sum_equals_attributed(model_name, renderer):
"""``sum(tokens_per_message()) + scaffold_count == len(token_ids)``.
Every token lands in exactly one of (a) a caller-relative message
bucket, or (b) the ``-1`` scaffolding bucket. No double-counts, no
drops.
"""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs, add_generation_prompt=True)
counts = rendered.tokens_per_message()
scaffold = sum(1 for idx in rendered.message_indices if idx == -1)
assert sum(counts) + scaffold == len(rendered.token_ids), (
f"{model_name}: tokens_per_message sum {sum(counts)} + scaffold "
f"{scaffold} != token count {len(rendered.token_ids)}"
)
# message_roles populated, length matches caller input.
assert len(rendered.message_roles) == len(msgs), (
f"{model_name}: message_roles length {len(rendered.message_roles)} "
f"!= len(msgs) {len(msgs)}"
)
assert rendered.message_roles == ["system", "user", "assistant"], (
f"{model_name}: message_roles {rendered.message_roles} != input roles"
)
# Every caller message must have a positive count.
bad = [i for i, n in enumerate(counts) if n == 0]
assert not bad, f"{model_name}: messages with zero attributed tokens: {bad}"
def test_tokens_per_message_sampled_lt_total_for_assistant(model_name, renderer):
"""The assistant message's ``sampled_only=True`` count must be
strictly less than its full count.
The template wraps an assistant turn with at least one role-tag
token (``<|im_start|>assistant\\n`` or equivalent) that the model
doesn't sample at inference. Skips renderers that opt out of
``sampled_mask`` (DefaultRenderer).
"""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello world!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return
total = rendered.tokens_per_message()
sampled = rendered.tokens_per_message(sampled_only=True)
assistant_idx = 1
assert sampled[assistant_idx] < total[assistant_idx], (
f"{model_name}: assistant sampled count {sampled[assistant_idx]} "
f"not strictly less than total {total[assistant_idx]} — role-tag "
f"opener should have been excluded"
)
assert sampled[assistant_idx] > 0, (
f"{model_name}: assistant sampled count is zero — content tokens "
f"should be is_sampled=True"
)
def test_tokens_per_message_sampled_zero_for_history_roles(model_name, renderer):
"""``sampled_only=True`` counts are zero for user / system / tool —
the model never samples conversation history."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return
sampled = rendered.tokens_per_message(sampled_only=True)
assert sampled[0] == 0, (
f"{model_name}: system message sampled count {sampled[0]} != 0"
)
assert sampled[1] == 0, (
f"{model_name}: user message sampled count {sampled[1]} != 0"
)
def test_tokens_per_message_truncates_to_n_messages(model_name, renderer):
"""Passing explicit ``n_messages`` smaller than the populated count
silently drops tail messages — the helper doesn't raise."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
truncated = rendered.tokens_per_message(1)
assert len(truncated) == 1
assert truncated[0] > 0
def test_tokens_per_message_clamps_oversized_n_messages(model_name, renderer):
"""Passing ``n_messages`` larger than ``len(message_roles)`` is
clamped — the helper never reports more messages than the renderer
attributed, so callers can't read trailing-zero phantoms."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
clamped = rendered.tokens_per_message(99)
assert len(clamped) == len(rendered.message_roles)
assert clamped == rendered.tokens_per_message()
def test_tokens_per_message_bridge_attributes_new_messages(model_name, renderer):
"""``bridge_to_next_turn`` returns ``RenderedTokens`` with proper
per-token attribution AND populated ``message_roles`` for
``new_messages``. ``sampled_mask`` is uniformly ``False``.
DefaultRenderer's ``bridge_to_next_turn`` returns ``None``
unconditionally, so we skip when bridge is unsupported.
"""
prior = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered_prior = renderer.render(prior, add_generation_prompt=False)
new_messages = [
{"role": "user", "content": "Tell me a longer story please"},
]
bridge = renderer.bridge_to_next_turn(
previous_prompt_ids=rendered_prior.token_ids,
previous_completion_ids=[],
new_messages=new_messages,
)
if bridge is None:
return
assert len(bridge.message_indices) == len(bridge.token_ids), (
f"{model_name}: bridge message_indices length mismatch"
)
assert len(bridge.sampled_mask) == len(bridge.token_ids), (
f"{model_name}: bridge sampled_mask length mismatch"
)
assert bridge.message_roles == ["user"], (
f"{model_name}: bridge message_roles {bridge.message_roles} != ['user']"
)
assert not any(bridge.sampled_mask), (
f"{model_name}: bridge emitted a token marked is_sampled=True"
)
counts = bridge.tokens_per_message()
assert counts == [counts[0]] and counts[0] > 0, (
f"{model_name}: bridge attributed {counts} tokens; expected one "
f"positive entry for the new user message"
)
def test_tokens_by_role_includes_every_input_role(model_name, renderer):
"""``tokens_by_role`` returns a key for every role that appears in
``message_roles``. Counts sum to the same value as
``tokens_per_message``.
"""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
by_role = rendered.tokens_by_role()
assert set(by_role) == {"system", "user", "assistant"}, (
f"{model_name}: tokens_by_role keys {set(by_role)} != expected roles"
)
assert sum(by_role.values()) == sum(rendered.tokens_per_message()), (
f"{model_name}: tokens_by_role sum disagrees with tokens_per_message sum"
)
def test_tokens_by_role_sampled_only_assistant_only(model_name, renderer):
"""Under ``sampled_only=True``, only ``assistant`` has a positive
count — every other role's tokens were template-injected."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
if not rendered.sampled_mask:
return
by_role = rendered.tokens_by_role(sampled_only=True)
assert by_role["assistant"] > 0
assert by_role["system"] == 0
assert by_role["user"] == 0
def test_message_token_spans_recover_token_ranges(model_name, renderer):
"""``message_token_spans()`` returns ``(start, end)`` such that
``token_ids[start:end]`` contains exactly the tokens attributed to
that message and ``token_ids[end-1]`` is still in that message
(i.e. the span is the inclusive token range of the message).
Also: spans cover every non-scaffolding token; the spans are
ordered by message index; concatenating
``token_ids[start:end]`` for every non-None span plus the
``-1``-attributed scaffolding tokens equals the original
``token_ids``.
"""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs, add_generation_prompt=True)
spans = rendered.message_token_spans()
assert len(spans) == len(msgs)
# Each span's tokens match the message_indices attribution.
for i, span in enumerate(spans):
assert span is not None, f"{model_name}: message {i} has no span"
start, end = span
attributed = [
rendered.message_indices[k]
for k in range(start, end)
if rendered.message_indices[k] == i
]
# At least one token in the span belongs to this message
# (contiguity assumption — see method docstring).
assert attributed, (
f"{model_name}: span {span} for msg {i} contains no msg-i tokens"
)
# Spans are non-decreasing by start.
starts = [s[0] for s in spans if s is not None]
assert starts == sorted(starts), (
f"{model_name}: spans not in message order: {starts}"
)
def test_role_token_spans_groups_by_role(model_name, renderer):
"""``role_token_spans()`` groups :meth:`message_token_spans` by
role. The total tokens captured per role should match
``tokens_by_role()``.
"""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs)
role_spans = rendered.role_token_spans()
by_role = rendered.tokens_by_role()
for role, spans in role_spans.items():
span_total = sum(e - s for s, e in spans)
assert span_total == by_role[role], (
f"{model_name}: role {role!r} span-total {span_total} != "
f"tokens_by_role {by_role[role]}"
)
def test_tokens_per_message_no_messages_helper_works():
"""Pure-data-shape: methods on a manually-constructed RenderedTokens
without any renderer involvement. No fixture needed."""
r = RenderedTokens(
token_ids=[10, 11, 12, 13, 14],
message_indices=[0, 0, 1, 1, -1],
sampled_mask=[False, True, False, False, False],
message_roles=["user", "assistant"],
)
assert r.tokens_per_message() == [2, 2]
assert r.tokens_per_message(sampled_only=True) == [1, 0]
assert r.tokens_by_role() == {"user": 2, "assistant": 2}
assert r.tokens_by_role(sampled_only=True) == {"user": 1, "assistant": 0}
assert r.message_token_spans() == [(0, 2), (2, 4)]
assert r.role_token_spans() == {
"user": [(0, 2)],
"assistant": [(2, 4)],
}
def test_message_token_spans_empty_message():
"""A message that contributed zero tokens (rare but possible for
empty content some templates skip) gets ``None`` as its span."""
r = RenderedTokens(
token_ids=[10, 11, 12],
message_indices=[0, 0, 2],
message_roles=["user", "assistant", "tool"],
)
spans = r.message_token_spans()
assert spans[0] == (0, 2)
assert spans[1] is None # no tokens attributed
assert spans[2] == (2, 3)
+139
View File
@@ -0,0 +1,139 @@
"""Tool-arg string-type preservation across renderers.
XML-style chat templates (Qwen3.5, GLM, MiniMax, Laguna) render tool-call
argument values verbatim inside ``<arg_value>X</arg_value>`` tags with
no quoting, so a value of ``true`` could be either a bool or the string
``"true"``. Without the tool schema, the parser has no signal to choose
between them and defaults to ``json.loads`` — which silently corrupts
string args that look like JSON.
This test passes the tool schema to ``parse_response`` so the parser can
preserve declared-string params verbatim, matching vLLM / SGLang's
reference parsers (e.g. ``vllm/glm45_tool_parser.py``). The hermes-JSON
(Qwen3) and section-JSON (Kimi K2) parsers sidestep the bug because
their wire format quotes strings; both serve as controls.
Originally raised by Robin (Poolside) on PR #21.
"""
from __future__ import annotations
import json
from functools import lru_cache
from typing import Any
import pytest
# (HuggingFace model name, renderer name). Two JSON-shaped controls
# (string types already preserved by the wire format) + four XML-style
# parsers that rely on the schema to preserve them.
_MODELS = [
("Qwen/Qwen3-8B", "auto"), # hermes JSON — control
("moonshotai/Kimi-K2-Instruct", "auto"), # section JSON — control
("Qwen/Qwen3.5-9B", "auto"), # XML
("zai-org/GLM-5", "auto"), # XML
("MiniMaxAI/MiniMax-M2.5", "auto"), # XML
("poolside/Laguna-XS.2", "auto"), # XML
]
@lru_cache(maxsize=None)
def _load(model: str, renderer_name: str):
from renderers import create_renderer
from renderers.base import load_tokenizer
tok = load_tokenizer(model)
return tok, create_renderer(tok, renderer=renderer_name)
def pytest_generate_tests(metafunc):
if "model" in metafunc.fixturenames:
metafunc.parametrize(
"model,renderer_name",
_MODELS,
ids=[m for m, _ in _MODELS],
)
@pytest.fixture
def renderer(model, renderer_name):
return _load(model, renderer_name)[1]
PROMPT = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Call f."},
]
# Each case: a single ``x`` argument whose value is a STRING that
# happens to be valid JSON of another type. With a schema declaring
# ``x: string``, the parser must return the string verbatim.
JSON_LOOKING_STRING_ARGS = [
pytest.param({"x": "true"}, id="string-bool"),
pytest.param({"x": "42"}, id="string-int"),
pytest.param({"x": "null"}, id="string-null"),
pytest.param({"x": "[1,2,3]"}, id="string-array"),
pytest.param({"x": '{"k": 1}'}, id="string-object"),
]
# Tool schema with the single string-typed parameter exercised by every
# case above. Passed to both ``render`` (so the system prompt declares
# the tool) and ``parse_response`` (so the parser preserves the type).
TOOLS = [
{
"type": "function",
"function": {
"name": "f",
"description": "Test tool with one string parameter.",
"parameters": {
"type": "object",
"properties": {"x": {"type": "string"}},
"required": ["x"],
},
},
}
]
def _normalize_args(args: Any) -> Any:
"""Mirror ``test_roundtrip._normalize_args`` — some parsers return a
JSON string, others a dict; compare by value."""
if isinstance(args, str):
try:
return json.loads(args)
except json.JSONDecodeError:
return args
return args
def _extract_assistant_tokens(renderer, prompt, assistant_msg, *, tools=None):
prompt_ids = renderer.render_ids(prompt, tools=tools, add_generation_prompt=False)
full_ids = renderer.render_ids(prompt + [assistant_msg], tools=tools)
return full_ids[len(prompt_ids) :]
@pytest.mark.parametrize("args", JSON_LOOKING_STRING_ARGS)
def test_string_arg_preserves_type(model, renderer_name, renderer, args):
"""Tool-call args of declared type ``str`` must round-trip as ``str``,
not get re-parsed as bool/int/null/list/dict by the parser."""
msg = {
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "functions.f:0",
"function": {"name": "f", "arguments": args},
}
],
}
completion_ids = _extract_assistant_tokens(renderer, PROMPT, msg, tools=TOOLS)
parsed = renderer.parse_response(completion_ids, tools=TOOLS)
assert parsed.tool_calls, f"{model}: parser returned no tool_calls"
got = _normalize_args(parsed.tool_calls[0].arguments)
assert got == args, (
f"{model}: tool-arg type drift — sent {args!r}, parser returned {got!r}"
)
Generated
+4 -5
View File
@@ -9,7 +9,7 @@ resolution-markers = [
]
[options]
exclude-newer = "2026-05-03T21:26:00.600500892Z"
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P7D"
[[package]]
@@ -1333,7 +1333,6 @@ wheels = [
[[package]]
name = "renderers"
version = "0.1.7"
source = { editable = "." }
dependencies = [
{ name = "jinja2" },
@@ -1799,11 +1798,11 @@ wheels = [
[[package]]
name = "urllib3"
version = "2.6.3"
version = "2.7.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c7/24/5f1b3bdffd70275f6661c76461e25f024d5a38a46f04aaca912426a2b1d3/urllib3-2.6.3.tar.gz", hash = "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed", size = 435556, upload-time = "2026-01-07T16:24:43.925Z" }
sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/39/08/aaaad47bc4e9dc8c725e68f9d04865dbcb2052843ff09c97b08904852d84/urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4", size = 131584, upload-time = "2026-01-07T16:24:42.685Z" },
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
]
[[package]]