Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ec28a8543 | ||
|
|
c86c50b72e | ||
|
|
1831bcc50c | ||
|
|
3ae276c446 | ||
|
|
1691f87e90 | ||
|
|
9e11214dd5 | ||
|
|
143ffdee56 | ||
|
|
f9414b1e95 | ||
|
|
ee9703fcc9 | ||
|
|
3177399b79 | ||
|
|
8704f9d502 | ||
|
|
fdc03f2861 | ||
|
|
d547eef54c | ||
|
|
25ba413d46 | ||
|
|
17d0584f87 | ||
|
|
87084dcb8c | ||
|
|
2eabcf4274 | ||
|
|
973581f5e0 | ||
|
|
e2639e32b8 | ||
|
|
01aeb004b8 | ||
|
|
562db77eff | ||
|
|
40620409ed | ||
|
|
f99428a35b | ||
|
|
2c2aa00d42 | ||
|
|
3ebfe7b67e | ||
|
|
073389004f |
@@ -0,0 +1,104 @@
|
||||
name: Publish Dev
|
||||
|
||||
# Tag every commit on main as ``renderers-v<next>.dev<N>`` and publish the
|
||||
# wheel to PyPI as a pre-release. ``<next>`` is the latest release tag with
|
||||
# its patch bumped; ``<N>`` is the number of commits since that release so
|
||||
# each main commit maps to a unique PEP 440 dev version.
|
||||
#
|
||||
# Building from the freshly-created tag means hatch-vcs resolves the version
|
||||
# cleanly (no ``+gHASH`` local segment), which PyPI requires.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: publish-dev-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
tag:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
outputs:
|
||||
tag: ${{ steps.compute.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Compute next dev tag
|
||||
id: compute
|
||||
run: |
|
||||
set -euo pipefail
|
||||
LATEST_RELEASE=$(git tag --list 'renderers-v*' --sort=-v:refname \
|
||||
| grep -Ev '(dev|rc|a[0-9]|b[0-9])' \
|
||||
| head -1)
|
||||
if [ -z "$LATEST_RELEASE" ]; then
|
||||
echo "No release tag matching 'renderers-v<MAJOR.MINOR.PATCH>' found" >&2
|
||||
exit 1
|
||||
fi
|
||||
BASE=${LATEST_RELEASE#renderers-v}
|
||||
MAJOR=$(echo "$BASE" | cut -d. -f1)
|
||||
MINOR=$(echo "$BASE" | cut -d. -f2)
|
||||
PATCH=$(echo "$BASE" | cut -d. -f3)
|
||||
NEXT="${MAJOR}.${MINOR}.$((PATCH + 1))"
|
||||
N=$(git rev-list --count "${LATEST_RELEASE}..HEAD")
|
||||
TAG="renderers-v${NEXT}.dev${N}"
|
||||
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||
echo "Computed tag: ${TAG} (base=${LATEST_RELEASE}, commits=${N})"
|
||||
|
||||
- name: Create and push tag
|
||||
env:
|
||||
TAG: ${{ steps.compute.outputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
|
||||
echo "Tag ${TAG} already exists on origin — nothing to do" >&2
|
||||
exit 0
|
||||
fi
|
||||
git config user.name 'github-actions[bot]'
|
||||
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
|
||||
git tag -a "$TAG" -m "Automated dev release ${TAG}"
|
||||
git push origin "$TAG"
|
||||
|
||||
build:
|
||||
needs: tag
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: refs/tags/${{ needs.tag.outputs.tag }}
|
||||
|
||||
- uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Build renderers
|
||||
run: uv build
|
||||
|
||||
- name: Upload dist artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dist-dev
|
||||
path: dist/
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
publish:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
environment: pypi-prod
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Download dist artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: dist-dev
|
||||
path: dist/
|
||||
|
||||
- name: Publish to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
|
||||
@@ -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
|
||||
|
||||
@@ -31,3 +31,6 @@ coverage.xml
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
|
||||
# agent harness state
|
||||
.claude/
|
||||
|
||||
@@ -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.
|
||||
@@ -17,7 +17,7 @@ from transformers import AutoTokenizer
|
||||
from renderers import create_renderer
|
||||
|
||||
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
|
||||
r = create_renderer(tok, renderer="auto") # → Qwen3Renderer
|
||||
r = create_renderer(tok) # → Qwen3Renderer (auto-resolved)
|
||||
|
||||
prompt_ids = r.render_ids(
|
||||
[{"role": "user", "content": "hi"}],
|
||||
@@ -71,17 +71,17 @@ Each hand-coded bridge:
|
||||
### Picking a renderer
|
||||
|
||||
```python
|
||||
r = create_renderer(tok, renderer="auto")
|
||||
r = create_renderer(tok) # AutoRendererConfig is the implicit default
|
||||
```
|
||||
|
||||
Auto-detect matches `tokenizer.name_or_path` against `MODEL_RENDERER_MAP` by **exact match**. Prefix matching is intentionally off — same architecture can ship different chat templates (base vs instruct, fine-tune renames). Fine-tunes must pass `renderer=<name>` explicitly; unknown names fall back to `DefaultRenderer`.
|
||||
Auto-detect matches `tokenizer.name_or_path` against `MODEL_RENDERER_MAP` by **exact match**. Prefix matching is intentionally off — same architecture can ship different chat templates (base vs instruct, fine-tune renames). Fine-tunes must pass an explicit typed config (e.g. `Qwen3RendererConfig()`); unknown names fall back to `DefaultRenderer`.
|
||||
|
||||
### Pools
|
||||
|
||||
```python
|
||||
from renderers import create_renderer_pool
|
||||
|
||||
pool = create_renderer_pool("Qwen/Qwen3-8B", renderer="auto", size=16)
|
||||
pool = create_renderer_pool("Qwen/Qwen3-8B", size=16)
|
||||
with pool.checkout() as r:
|
||||
ids = r.render_ids(messages)
|
||||
```
|
||||
@@ -108,25 +108,50 @@ Empirical delta on Qwen3.5-35B-A3B + mini-swe-agent-plus, step 0:
|
||||
|
||||
Each break fragments a rollout into multiple training samples — every fragment re-encodes its prefix, inflating compute roughly linearly with the number of breaks.
|
||||
|
||||
## Compaction overrides
|
||||
## Typed renderer configs
|
||||
|
||||
`create_renderer` and `create_renderer_pool` accept two constructor-only flags:
|
||||
Each renderer accepts a typed pydantic config that pins its template-control kwargs at construction. `create_renderer` and `create_renderer_pool` take one positional `config` argument:
|
||||
|
||||
```python
|
||||
preserve_all_thinking: bool = False
|
||||
preserve_thinking_between_tool_calls: bool = False
|
||||
from renderers import (
|
||||
create_renderer,
|
||||
AutoRendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
GLM5RendererConfig,
|
||||
DefaultRendererConfig,
|
||||
)
|
||||
|
||||
# Auto-resolve renderer from the tokenizer's model name. Carries the
|
||||
# shared preserve_* flags; template kwargs require an explicit choice.
|
||||
renderer = create_renderer(tokenizer)
|
||||
renderer = create_renderer(tokenizer, AutoRendererConfig(preserve_all_thinking=True))
|
||||
|
||||
# Explicit choice — the typed config exposes exactly the fields that
|
||||
# renderer's chat template honours.
|
||||
renderer = create_renderer(tokenizer, Qwen3RendererConfig(enable_thinking=False))
|
||||
renderer = create_renderer(tokenizer, GLM5RendererConfig(clear_thinking=False))
|
||||
|
||||
# Default renderer (apply_chat_template fallback) — extra fields are
|
||||
# captured via pydantic ``extra="allow"`` and forwarded to the Jinja
|
||||
# template; tool / reasoning parsers are typed.
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
DefaultRendererConfig(tool_parser="qwen3", reasoning_parser="think"),
|
||||
)
|
||||
```
|
||||
|
||||
Defaults preserve byte-identity with the model's chat template. Flipping a flag at construction restores `reasoning_content` the template would otherwise drop:
|
||||
Discriminated union: every per-renderer config is a variant of `RendererConfig`, dispatched on the `name` field. Bogus combinations (e.g. `add_vision_id` under `name="qwen3"`) error at construction with a `pydantic.ValidationError`. Downstream pydantic configs (prime-rl orchestrator, verifiers `ClientConfig`) hold a single field typed as `RendererConfig` and inherit the same strict-per-variant validation.
|
||||
|
||||
- `preserve_all_thinking=True` — every past assistant's reasoning is kept.
|
||||
- `preserve_thinking_between_tool_calls=True` — reasoning is kept on assistants in the in-flight tool cycle (no-op for current renderers; reserved for future templates that drop it).
|
||||
Two shared behaviour flags live on every variant via `_BaseRendererConfig`:
|
||||
|
||||
The canonical use case is **compaction**. Injecting a `user` turn like *"summarize the work so far"* puts every prior assistant in a "past cycle", so template-default rules drop their `reasoning_content` before the summarizer sees it. Build the renderer with `preserve_all_thinking=True` to keep reasoning visible end-to-end on those flows. Both flags only ever *add* tokens vs the template default.
|
||||
- `preserve_all_thinking=True` — every past assistant's `reasoning_content` is kept, even when the chat template would drop it.
|
||||
- `preserve_thinking_between_tool_calls=True` — reasoning is kept on assistants in the in-flight tool cycle (post-last-user A-T-…-A block when it contains a tool response). A new user turn closes the block and drops its thinking.
|
||||
|
||||
These OR-compose with template-level toggles (e.g. GLM-5 `clear_thinking`, Nemotron-3 `truncate_history_thinking`): either flag saying "keep" wins. preserve_* can only ever *extend* retention — never override a template kwarg into a "drop" decision. The canonical use case is **compaction**: injecting a `user` turn like *"summarize the work so far"* puts every prior assistant in a past cycle, and `preserve_all_thinking=True` keeps reasoning visible end-to-end.
|
||||
|
||||
## `DefaultRenderer`
|
||||
|
||||
Fallback for unsupported models. Wraps `apply_chat_template` and accepts `tool_parser` / `reasoning_parser` kwargs (vLLM convention). `bridge_to_next_turn` returns `None` because the template's close is unknown, so multi-turn rollouts fall back to full re-render. Implementing a hand-coded renderer is a few hundred lines of Python (`render_ids` + `parse_response` + `bridge_to_next_turn`) and is the only path that closes the failure modes above by construction.
|
||||
Fallback for unsupported models. Wraps `apply_chat_template` and accepts `tool_parser` / `reasoning_parser` (vLLM convention) plus arbitrary Jinja kwargs via `DefaultRendererConfig`'s `extra="allow"`. `bridge_to_next_turn` returns `None` because the template's close is unknown, so multi-turn rollouts fall back to full re-render. Implementing a hand-coded renderer is a few hundred lines of Python (`render_ids` + `parse_response` + `bridge_to_next_turn`) and is the only path that closes the failure modes above by construction.
|
||||
|
||||
## Roadmap
|
||||
|
||||
@@ -141,3 +166,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).
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
# Renderer config
|
||||
|
||||
`renderers.RendererConfig` is the typed input to `create_renderer` and
|
||||
`create_renderer_pool`. It pins the renderer choice and its template-control
|
||||
kwargs at construction.
|
||||
|
||||
```python
|
||||
from renderers import create_renderer, Qwen35RendererConfig
|
||||
|
||||
r = create_renderer(tokenizer, Qwen35RendererConfig(enable_thinking=False))
|
||||
```
|
||||
|
||||
`RendererConfig` is a pydantic discriminated union (one variant per renderer,
|
||||
dispatched on the `name` field). Selecting a variant exposes exactly the
|
||||
fields that renderer's chat template honours; anything else raises a
|
||||
`pydantic.ValidationError` at construction.
|
||||
|
||||
## Per-renderer configs
|
||||
|
||||
Each hand-coded renderer has a typed config class with the template kwargs
|
||||
its Jinja chat template reads. For example:
|
||||
|
||||
| Renderer | Config class | Template fields |
|
||||
|----------------|--------------------------|----------------------------------------------------------------|
|
||||
| Qwen3 | `Qwen3RendererConfig` | `enable_thinking` |
|
||||
| Qwen3.5 / 3.6 | `Qwen35RendererConfig` | `enable_thinking`, `add_vision_id` |
|
||||
| Qwen3-VL | `Qwen3VLRendererConfig` | `add_vision_id` |
|
||||
| GLM-5 / 5.1 | `GLM5RendererConfig` | `enable_thinking`, `clear_thinking` |
|
||||
| GLM-4.5 | `GLM45RendererConfig` | `enable_thinking` |
|
||||
| Nemotron-3 | `Nemotron3RendererConfig`| `enable_thinking`, `truncate_history_thinking` |
|
||||
| Kimi K2.5 | `KimiK25RendererConfig` | `thinking` |
|
||||
| MiniMax-M2 | `MiniMaxM2RendererConfig`| `model_identity` |
|
||||
| Laguna-XS.2 | `LagunaXS2RendererConfig`| `enable_thinking`, `render_assistant_messages_raw` |
|
||||
| gpt-oss | `GptOssRendererConfig` | `reasoning_effort`, `conversation_start_date` |
|
||||
|
||||
Field names mirror the upstream Jinja variable names. Passing
|
||||
`Qwen3RendererConfig(add_vision_id=True)` raises — Qwen3 is text-only, so
|
||||
the field doesn't exist on its config. Use
|
||||
`type(config).template_field_names()` to introspect the fields that mirror
|
||||
chat-template kwargs (parity is verified against `apply_chat_template` in
|
||||
`tests/test_renderer_config_parity.py`).
|
||||
|
||||
Configs are frozen. To override a field, construct a new instance or call
|
||||
`config.model_copy(update={...})`.
|
||||
|
||||
## Auto-resolution
|
||||
|
||||
`create_renderer(tokenizer)` (no config) resolves the renderer from
|
||||
`tokenizer.name_or_path` via `MODEL_RENDERER_MAP`:
|
||||
|
||||
```python
|
||||
r = create_renderer(tokenizer) # AutoRendererConfig() is the default
|
||||
r = create_renderer(tokenizer, AutoRendererConfig(preserve_all_thinking=True))
|
||||
```
|
||||
|
||||
`AutoRendererConfig` carries only the shared `preserve_*` flags. Template
|
||||
kwargs depend on the renderer, so overriding them requires naming the
|
||||
renderer explicitly:
|
||||
|
||||
```python
|
||||
r = create_renderer(tokenizer, GLM5RendererConfig(clear_thinking=False))
|
||||
```
|
||||
|
||||
Auto-resolution fails loudly for VLMs that miss the exact-match lookup —
|
||||
`DefaultRenderer` only knows `apply_chat_template` + text tokens, so silently
|
||||
falling back for a VLM would produce token streams the trainer can't
|
||||
reconstruct. Text-only fine-tunes without a registered renderer fall back to
|
||||
`DefaultRenderer` and log the choice at INFO.
|
||||
|
||||
## `preserve_*` flags
|
||||
|
||||
Every variant carries two renderer-agnostic flags on `_BaseRendererConfig`:
|
||||
|
||||
- `preserve_all_thinking: bool = False` — re-emit `reasoning_content` on
|
||||
every past assistant turn, even when the chat template would drop it.
|
||||
- `preserve_thinking_between_tool_calls: bool = False` — re-emit
|
||||
`reasoning_content` only inside the in-flight tool cycle (the contiguous
|
||||
A-T-…-A block after the most recent `user` message, when it contains at
|
||||
least one `tool` response). A new user turn closes the block and drops
|
||||
its thinking.
|
||||
|
||||
These OR-compose with template-level toggles. GLM-5's `clear_thinking` and
|
||||
Nemotron-3's `truncate_history_thinking` already gate past thinking; the
|
||||
`preserve_*` flags add to that:
|
||||
|
||||
| `clear_thinking` | `preserve_all_thinking` | past thinking? |
|
||||
|------------------|-------------------------|----------------|
|
||||
| `True` (default — drop) | `False` (default) | dropped |
|
||||
| `True` | `True` | kept |
|
||||
| `False` (keep) | `False` | kept |
|
||||
| `False` | `True` | kept |
|
||||
|
||||
`preserve_*` can only extend retention, never force a drop. The canonical
|
||||
use case is **compaction**: injecting a `user` turn like *"summarize the work
|
||||
so far"* puts every prior assistant in a past cycle, and
|
||||
`preserve_all_thinking=True` keeps reasoning visible end-to-end.
|
||||
|
||||
## `DefaultRendererConfig` accepts arbitrary Jinja kwargs
|
||||
|
||||
`DefaultRenderer` wraps `tokenizer.apply_chat_template` for any model that
|
||||
doesn't have a hand-coded renderer. Its config sets `extra="allow"`:
|
||||
|
||||
```python
|
||||
from renderers import create_renderer, DefaultRendererConfig
|
||||
|
||||
r = create_renderer(
|
||||
tokenizer,
|
||||
DefaultRendererConfig(
|
||||
tool_parser="qwen3", # registered in renderers.parsers
|
||||
reasoning_parser="think",
|
||||
enable_thinking=False, # forwarded to apply_chat_template
|
||||
custom_jinja_kwarg=True, # ditto
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
`tool_parser` and `reasoning_parser` are typed because they configure
|
||||
`DefaultRenderer`'s own parsing pipeline. Every other field lands in
|
||||
`model_extra` and `DefaultRenderer._apply` forwards `model_extra` verbatim
|
||||
to `apply_chat_template`.
|
||||
|
||||
## Downstream integration
|
||||
|
||||
Downstream pydantic configs (`prime-rl` orchestrator, `verifiers`
|
||||
`ClientConfig`) hold a single field typed as `RendererConfig`:
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
class ClientConfig(BaseModel):
|
||||
renderer: RendererConfig = Field(default_factory=AutoRendererConfig)
|
||||
```
|
||||
|
||||
In TOML / YAML, the discriminator routes deserialization:
|
||||
|
||||
```toml
|
||||
[client.renderer]
|
||||
name = "qwen3.5"
|
||||
enable_thinking = false
|
||||
add_vision_id = true
|
||||
preserve_all_thinking = true
|
||||
```
|
||||
|
||||
Pydantic dispatches on `name = "qwen3.5"` to `Qwen35RendererConfig`. Bogus
|
||||
combinations (e.g. `add_vision_id` under `name = "qwen3"`) raise at
|
||||
config-load with a clear message naming the offending field and the variant
|
||||
that rejected it.
|
||||
|
||||
To construct a config from a renderer name string (e.g. from a CLI flag):
|
||||
|
||||
```python
|
||||
from renderers import config_from_name
|
||||
|
||||
cfg = config_from_name("glm-5") # → GLM5RendererConfig() with defaults
|
||||
cfg = config_from_name("auto") # → None, the implicit "auto" form
|
||||
```
|
||||
|
||||
## Renaming a renderer is a breaking change
|
||||
|
||||
The discriminator key is the renderer name string. Renaming `"qwen3.5"` to
|
||||
something else would break any downstream config that references it by
|
||||
name. Add new renderers; don't rename existing ones.
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
@@ -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,17 @@ 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). The patch is bracketed
|
||||
# around ``from_pretrained``, so subsequent ``AutoTokenizer`` calls
|
||||
# outside the renderers package stay vanilla.
|
||||
"fastokens>=0.2.0",
|
||||
# ``BaseRendererConfig`` inherits from ``pydantic_config.BaseConfig`` so
|
||||
# the typed-config surface stays uniform with prime-rl / verifiers config
|
||||
# bases. Transitively brings pydantic, which ``renderers.configs`` also
|
||||
# imports directly.
|
||||
"prime-pydantic-config>=0.3.0.dev83",
|
||||
]
|
||||
|
||||
[tool.hatch.version]
|
||||
@@ -60,6 +73,12 @@ dev = [
|
||||
|
||||
[tool.uv]
|
||||
exclude-newer = "7 days"
|
||||
# fastokens 0.2.0 was published on 2026-05-17 and contains the
|
||||
# ``unpatch_transformers`` fix (crusoecloud/fastokens#32) needed for
|
||||
# MiniMax-M2's slow→fast tokenizer conversion path. Exempting it from
|
||||
# the project-wide 7-day cutoff lets the lockfile pick it up immediately
|
||||
# while the rest of the dependency graph stays gated.
|
||||
exclude-newer-package = { fastokens = false, "prime-pydantic-config" = false }
|
||||
|
||||
[tool.ty.environment]
|
||||
python-version = "3.13"
|
||||
|
||||
+98
-16
@@ -15,6 +15,7 @@ from renderers.base import (
|
||||
MultiModalData,
|
||||
MultimodalRenderer,
|
||||
ParsedResponse,
|
||||
ParsedToolCall,
|
||||
PlaceholderRange,
|
||||
RenderedConversation,
|
||||
RenderedTokens,
|
||||
@@ -24,8 +25,10 @@ from renderers.base import (
|
||||
ThinkingPart,
|
||||
ToolCall,
|
||||
ToolCallFunction,
|
||||
ToolCallParseStatus,
|
||||
ToolSpec,
|
||||
VideoPart,
|
||||
attribute_text_segments,
|
||||
build_training_sample,
|
||||
build_trajectory_step,
|
||||
create_renderer,
|
||||
@@ -34,56 +37,135 @@ from renderers.base import (
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.deepseek_v3 import DeepSeekV3Renderer
|
||||
from renderers.default import DefaultRenderer
|
||||
from renderers.glm5 import GLM5Renderer
|
||||
from renderers.glm45 import GLM45Renderer
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.kimi_k2 import KimiK2Renderer
|
||||
from renderers.kimi_k25 import KimiK25Renderer
|
||||
from renderers.minimax_m2 import MiniMaxM2Renderer
|
||||
from renderers.nemotron3 import Nemotron3Renderer
|
||||
from renderers.qwen3 import Qwen3Renderer
|
||||
from renderers.qwen3_vl import Qwen3VLRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from renderers.qwen36 import Qwen36Renderer
|
||||
from renderers.client import OverlongPromptError
|
||||
from renderers.configs import (
|
||||
AutoRendererConfig,
|
||||
BaseRendererConfig,
|
||||
config_from_name,
|
||||
DefaultRendererConfig,
|
||||
DeepSeekV3RendererConfig,
|
||||
GLM45RendererConfig,
|
||||
GLM51RendererConfig,
|
||||
GLM5RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
KimiK25RendererConfig,
|
||||
KimiK2RendererConfig,
|
||||
LagunaXS2RendererConfig,
|
||||
MiniMaxM2RendererConfig,
|
||||
Nemotron3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
Qwen36RendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
Qwen3VLRendererConfig,
|
||||
RendererConfig,
|
||||
)
|
||||
|
||||
# Concrete renderer classes are lazy-loaded so that consumers needing
|
||||
# only the config layer (``RendererConfig`` discriminated union) don't
|
||||
# pay the ``transformers`` import cost. Each renderer module does
|
||||
# ``from transformers.tokenization_utils import PreTrainedTokenizer``
|
||||
# at module level, so eager imports here would drag ``transformers``
|
||||
# into every downstream ``import renderers``. ``__getattr__`` (PEP 562)
|
||||
# resolves the names on first attribute access, so ``from renderers
|
||||
# import DefaultRenderer`` and ``renderers.DefaultRenderer`` both work
|
||||
# transparently. ``create_renderer`` doesn't depend on these eager
|
||||
# imports — ``renderers.base._populate_registry`` lazy-imports the
|
||||
# concrete classes itself when a renderer is instantiated.
|
||||
_LAZY_RENDERERS: dict[str, str] = {
|
||||
"DeepSeekV3Renderer": "renderers.deepseek_v3",
|
||||
"DefaultRenderer": "renderers.default",
|
||||
"GLM45Renderer": "renderers.glm45",
|
||||
"GLM51Renderer": "renderers.glm5",
|
||||
"GLM5Renderer": "renderers.glm5",
|
||||
"GptOssRenderer": "renderers.gpt_oss",
|
||||
"KimiK25Renderer": "renderers.kimi_k25",
|
||||
"KimiK2Renderer": "renderers.kimi_k2",
|
||||
"LagunaXS2Renderer": "renderers.laguna_xs2",
|
||||
"MiniMaxM2Renderer": "renderers.minimax_m2",
|
||||
"Nemotron3Renderer": "renderers.nemotron3",
|
||||
"Qwen35Renderer": "renderers.qwen35",
|
||||
"Qwen36Renderer": "renderers.qwen36",
|
||||
"Qwen3Renderer": "renderers.qwen3",
|
||||
"Qwen3VLRenderer": "renderers.qwen3_vl",
|
||||
}
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
if name in _LAZY_RENDERERS:
|
||||
import importlib
|
||||
|
||||
module = importlib.import_module(_LAZY_RENDERERS[name])
|
||||
value = getattr(module, name)
|
||||
globals()[name] = value # cache for subsequent lookups
|
||||
return value
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
|
||||
|
||||
def __dir__() -> list[str]:
|
||||
return sorted(set(globals().keys()) | set(_LAZY_RENDERERS))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AutoRendererConfig",
|
||||
"BaseRendererConfig",
|
||||
"Content",
|
||||
"ContentPart",
|
||||
"DeepSeekV3Renderer",
|
||||
"DeepSeekV3RendererConfig",
|
||||
"DefaultRenderer",
|
||||
"DefaultRendererConfig",
|
||||
"GLM45Renderer",
|
||||
"GLM45RendererConfig",
|
||||
"GLM51Renderer",
|
||||
"GLM51RendererConfig",
|
||||
"GLM5Renderer",
|
||||
"GLM5RendererConfig",
|
||||
"GptOssRenderer",
|
||||
"GptOssRendererConfig",
|
||||
"ImagePart",
|
||||
"KimiK2Renderer",
|
||||
"KimiK25Renderer",
|
||||
"KimiK25RendererConfig",
|
||||
"KimiK2Renderer",
|
||||
"KimiK2RendererConfig",
|
||||
"LagunaXS2Renderer",
|
||||
"LagunaXS2RendererConfig",
|
||||
"MULTIMODAL_MODELS",
|
||||
"Message",
|
||||
"MiniMaxM2Renderer",
|
||||
"MiniMaxM2RendererConfig",
|
||||
"MultiModalData",
|
||||
"MultimodalRenderer",
|
||||
"Nemotron3Renderer",
|
||||
"Nemotron3RendererConfig",
|
||||
"OverlongPromptError",
|
||||
"ParsedResponse",
|
||||
"ParsedToolCall",
|
||||
"PlaceholderRange",
|
||||
"Qwen3Renderer",
|
||||
"Qwen3VLRenderer",
|
||||
"Qwen35Renderer",
|
||||
"Qwen35RendererConfig",
|
||||
"Qwen36Renderer",
|
||||
"Qwen36RendererConfig",
|
||||
"Qwen3Renderer",
|
||||
"Qwen3RendererConfig",
|
||||
"Qwen3VLRenderer",
|
||||
"Qwen3VLRendererConfig",
|
||||
"RenderedConversation",
|
||||
"RenderedTokens",
|
||||
"Renderer",
|
||||
"RendererConfig",
|
||||
"RendererPool",
|
||||
"TextPart",
|
||||
"ThinkingPart",
|
||||
"ToolCall",
|
||||
"ToolCallFunction",
|
||||
"ToolCallParseStatus",
|
||||
"ToolSpec",
|
||||
"VideoPart",
|
||||
"__version__",
|
||||
"attribute_text_segments",
|
||||
"build_training_sample",
|
||||
"build_trajectory_step",
|
||||
"config_from_name",
|
||||
"create_renderer",
|
||||
"create_renderer_pool",
|
||||
"is_multimodal",
|
||||
|
||||
+804
-117
File diff suppressed because it is too large
Load Diff
+185
-74
@@ -12,16 +12,99 @@ achieve real parallelism.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
from openai import AsyncOpenAI, BadRequestError
|
||||
import httpx
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from renderers.base import Message, MultiModalData, Renderer, RendererPool, ToolSpec
|
||||
from renderers.base import (
|
||||
Message,
|
||||
MultiModalData,
|
||||
RenderedTokens,
|
||||
Renderer,
|
||||
RendererPool,
|
||||
ToolCallParseStatus,
|
||||
ToolSpec,
|
||||
)
|
||||
|
||||
_request_logger = logging.getLogger("renderers.client")
|
||||
ROUTED_EXPERTS_DATA_PREFIX = b'"routed_experts":{"data":"'
|
||||
|
||||
|
||||
class OverlongPromptError(Exception):
|
||||
"""The rendered prompt exceeds the engine's context window.
|
||||
|
||||
Raised by :func:`generate` when the rendered token sequence is strictly
|
||||
longer than the resolved cap — either an explicit ``max_prompt_len`` the
|
||||
caller passed in, or the engine's ``max_model_len`` discovered via
|
||||
``GET /v1/models``. Caught client-side before the engine ever sees the
|
||||
request, so callers route the failure to a deterministic policy (skip /
|
||||
truncate / count) instead of round-tripping through an engine 4xx.
|
||||
|
||||
Named after the corresponding ``verifiers.errors.OverlongPromptError``;
|
||||
the two are distinct classes (different package hierarchies) but the
|
||||
concept is the same and downstream clients translate one to the other.
|
||||
"""
|
||||
|
||||
def __init__(self, *, prompt_len: int, max_prompt_len: int) -> None:
|
||||
self.prompt_len = prompt_len
|
||||
self.max_prompt_len = max_prompt_len
|
||||
super().__init__(
|
||||
f"Prompt length ({prompt_len}) exceeds maximum "
|
||||
f"context length ({max_prompt_len})."
|
||||
)
|
||||
|
||||
|
||||
# Per-process cache of resolved engine context-length caps, keyed by
|
||||
# ``(base_url, model)``. ``None`` is the "we asked the engine and it didn't
|
||||
# tell us" sentinel — distinct from "key missing" (haven't asked yet). The
|
||||
# lock serializes the first lookup per key; cache hits avoid the lock.
|
||||
_max_prompt_len_cache: dict[tuple[str, str], int | None] = {}
|
||||
_max_prompt_len_lock = asyncio.Lock()
|
||||
|
||||
|
||||
async def _resolve_max_prompt_len(client: AsyncOpenAI, model: str) -> int | None:
|
||||
"""Discover ``max_model_len`` from the engine via ``GET /v1/models``.
|
||||
|
||||
OpenAI-API-compatible engines expose model metadata at this endpoint;
|
||||
vLLM extends its ``ModelCard`` with a ``max_model_len`` field. Engines
|
||||
that don't (SGLang as of this writing, third-party gateways, etc.) get
|
||||
a cached ``None`` and the pre-flight overflow check silently disables —
|
||||
callers fall back to whatever reactive handling they have for engine
|
||||
4xx, which the verifiers ``@handle_openai_overlong_prompt`` decorator
|
||||
already supplies for the prime-rl path.
|
||||
|
||||
Any exception during lookup (network error, non-JSON body, attribute
|
||||
miss on a mock client in tests) is treated as "unknown cap": cached
|
||||
``None`` so we don't retry on every call.
|
||||
"""
|
||||
key = (str(getattr(client, "base_url", "")), model)
|
||||
if key in _max_prompt_len_cache:
|
||||
return _max_prompt_len_cache[key]
|
||||
async with _max_prompt_len_lock:
|
||||
if key in _max_prompt_len_cache:
|
||||
return _max_prompt_len_cache[key]
|
||||
try:
|
||||
payload = await client.get("/models", cast_to=cast(Any, dict[str, Any]))
|
||||
except Exception as exc:
|
||||
_request_logger.debug("max_prompt_len lookup failed: %s", exc)
|
||||
_max_prompt_len_cache[key] = None
|
||||
return None
|
||||
value: int | None = None
|
||||
for card in payload.get("data") or []:
|
||||
if not isinstance(card, Mapping):
|
||||
continue
|
||||
if card.get("id") != model:
|
||||
continue
|
||||
raw = card.get("max_model_len")
|
||||
if isinstance(raw, int) and raw > 0:
|
||||
value = raw
|
||||
break
|
||||
_max_prompt_len_cache[key] = value
|
||||
return value
|
||||
|
||||
|
||||
async def _maybe_offload(renderer: Renderer | RendererPool, fn):
|
||||
@@ -38,6 +121,26 @@ async def _maybe_offload(renderer: Renderer | RendererPool, fn):
|
||||
return fn()
|
||||
|
||||
|
||||
def strip_routed_experts_data(raw: bytes) -> tuple[bytes, memoryview | None]:
|
||||
data_start = raw.find(ROUTED_EXPERTS_DATA_PREFIX)
|
||||
if data_start < 0:
|
||||
return raw, None
|
||||
|
||||
data_start += len(ROUTED_EXPERTS_DATA_PREFIX)
|
||||
data_end = raw.index(b'"', data_start)
|
||||
routed_data = memoryview(raw)[data_start:data_end]
|
||||
stripped = raw[:data_start] + raw[data_end:]
|
||||
return stripped, routed_data
|
||||
|
||||
|
||||
def parse_generate_response(raw: bytes) -> dict[str, Any]:
|
||||
stripped, routed_data = strip_routed_experts_data(raw)
|
||||
payload: dict[str, Any] = json.loads(stripped)
|
||||
if routed_data is not None:
|
||||
payload["choices"][0]["routed_experts"]["data"] = routed_data
|
||||
return payload
|
||||
|
||||
|
||||
async def generate(
|
||||
*,
|
||||
client: AsyncOpenAI,
|
||||
@@ -46,11 +149,13 @@ async def generate(
|
||||
model: str,
|
||||
prompt_ids: list[int] | None = None,
|
||||
multi_modal_data: MultiModalData | None = None,
|
||||
prompt_attribution: RenderedTokens | None = None,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
sampling_params: dict[str, Any] | None = None,
|
||||
cache_salt: str | None = None,
|
||||
priority: int | None = None,
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
max_prompt_len: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Tokenize messages, call vLLM /inference/v1/generate, parse the response.
|
||||
|
||||
@@ -59,7 +164,11 @@ async def generate(
|
||||
renderer) and ``logprobs=1`` (we always emit completion_logprobs). Pass
|
||||
``prompt_ids`` to skip rendering and use a prebuilt token sequence —
|
||||
pair it with ``multi_modal_data`` when the prebuilt prompt has image /
|
||||
video placeholders that need engine-side mm payload.
|
||||
video placeholders that need engine-side mm payload, and with
|
||||
``prompt_attribution`` (a :class:`RenderedTokens` whose ``token_ids``
|
||||
match the passed-in ``prompt_ids``) to carry the renderer's per-token
|
||||
attribution (``is_content`` / ``sampled_mask`` / ``message_indices`` /
|
||||
``message_roles``) into the result without re-rendering.
|
||||
|
||||
For multimodal renderers (e.g. ``Qwen3VLRenderer``), the call goes
|
||||
through ``renderer.render(...)`` to recover the ``multi_modal_data``
|
||||
@@ -67,9 +176,31 @@ async def generate(
|
||||
mm_placeholders, kwargs_data) before POSTing. The serializer imports
|
||||
``vllm.*`` lazily so text-only consumers never pay for the import.
|
||||
|
||||
``max_prompt_len`` controls the pre-flight overflow check. When the
|
||||
rendered prompt is strictly longer than the cap, the request is never
|
||||
sent and ``OverlongPromptError`` is raised. If ``max_prompt_len`` is
|
||||
``None`` (the default), the cap is auto-discovered once per
|
||||
``(base_url, model)`` via ``GET /v1/models`` (vLLM's
|
||||
``ModelCard.max_model_len`` extension); engines that don't expose it
|
||||
cache a ``None`` cap and the pre-flight silently disables. Engine 4xx
|
||||
that still slip through propagate raw — converting them into a domain
|
||||
error is the calling client's job (its error shape is engine-specific).
|
||||
|
||||
Returns a dict with: request_id, prompt_ids, completion_ids,
|
||||
completion_logprobs, content, reasoning_content, tool_calls,
|
||||
finish_reason, routed_experts.
|
||||
finish_reason, routed_experts, multi_modal_data, prompt_attribution.
|
||||
|
||||
``prompt_attribution`` is the renderer's :class:`RenderedTokens` for
|
||||
the prompt — either the one this call computed via
|
||||
``renderer.render(...)`` or the one the caller threaded in alongside
|
||||
``prompt_ids``. Carries ``token_ids``, ``message_indices``,
|
||||
``sampled_mask``, ``is_content``, ``message_roles``, and
|
||||
``multi_modal_data``, so downstream consumers (verifiers
|
||||
``RendererClient`` → prime-rl) can build per-token loss masks
|
||||
(``content_mask_for_roles({"tool"})`` for SFT-on-tool-body,
|
||||
``sampled_mask`` for RL trainable spans) without a second render
|
||||
pass. ``None`` when the caller passed pre-built ``prompt_ids``
|
||||
without attribution.
|
||||
"""
|
||||
if tools and not getattr(renderer, "supports_tools", True):
|
||||
raise ValueError(
|
||||
@@ -79,15 +210,33 @@ async def generate(
|
||||
|
||||
def _prepare():
|
||||
if prompt_ids is not None:
|
||||
return list(prompt_ids), renderer.get_stop_token_ids(), multi_modal_data
|
||||
# Caller-supplied prompt; if they also gave us pre-computed
|
||||
# attribution (e.g. the bridge path in verifiers), thread it
|
||||
# through unchanged.
|
||||
return (
|
||||
list(prompt_ids),
|
||||
renderer.get_stop_token_ids(),
|
||||
multi_modal_data,
|
||||
prompt_attribution,
|
||||
)
|
||||
rendered = renderer.render(messages, tools=tools, add_generation_prompt=True)
|
||||
return (
|
||||
rendered.token_ids,
|
||||
renderer.get_stop_token_ids(),
|
||||
rendered.multi_modal_data,
|
||||
rendered,
|
||||
)
|
||||
|
||||
prompt_ids, stop_token_ids, mm_data = await _maybe_offload(renderer, _prepare)
|
||||
prompt_ids, stop_token_ids, mm_data, prompt_attr = await _maybe_offload(
|
||||
renderer, _prepare
|
||||
)
|
||||
|
||||
if max_prompt_len is None:
|
||||
max_prompt_len = await _resolve_max_prompt_len(client, model)
|
||||
if max_prompt_len is not None and len(prompt_ids) > max_prompt_len:
|
||||
raise OverlongPromptError(
|
||||
prompt_len=len(prompt_ids), max_prompt_len=max_prompt_len
|
||||
)
|
||||
|
||||
sp: dict[str, Any] = dict(sampling_params or {})
|
||||
sp["stop_token_ids"] = stop_token_ids
|
||||
@@ -123,27 +272,19 @@ async def generate(
|
||||
sp.get("max_tokens"),
|
||||
)
|
||||
post_kwargs: dict[str, Any] = {
|
||||
"cast_to": cast(Any, dict[str, Any]),
|
||||
"cast_to": httpx.Response,
|
||||
"body": body,
|
||||
}
|
||||
if extra_headers:
|
||||
post_kwargs["options"] = cast(Any, {"headers": extra_headers})
|
||||
try:
|
||||
data = await client.post(endpoint, **post_kwargs)
|
||||
except BadRequestError as exc:
|
||||
_log_overlong_prompt_diagnostic(
|
||||
prompt_ids=prompt_ids,
|
||||
messages=messages,
|
||||
max_tokens=sp.get("max_tokens"),
|
||||
exc=exc,
|
||||
)
|
||||
raise
|
||||
raw_response = await client.post(endpoint, **post_kwargs)
|
||||
data = parse_generate_response(raw_response.content)
|
||||
|
||||
choice = (data.get("choices") or [{}])[0]
|
||||
completion_ids = choice.get("token_ids") or []
|
||||
|
||||
parsed = await _maybe_offload(
|
||||
renderer, lambda: renderer.parse_response(completion_ids)
|
||||
renderer, lambda: renderer.parse_response(completion_ids, tools=tools)
|
||||
)
|
||||
|
||||
# ChatCompletionLogProbs flatten: {"content": [{"logprob": ...}, ...]}
|
||||
@@ -151,22 +292,21 @@ async def generate(
|
||||
content_lp = raw_logprobs.get("content") if isinstance(raw_logprobs, dict) else None
|
||||
completion_logprobs = [float(c.get("logprob") or 0.0) for c in content_lp or []]
|
||||
|
||||
routed_experts = None
|
||||
raw_re = choice.get("routed_experts")
|
||||
if isinstance(raw_re, dict) and "data" in raw_re and "shape" in raw_re:
|
||||
routed_experts = (
|
||||
np.frombuffer(base64.b85decode(raw_re["data"]), dtype=np.int32)
|
||||
.reshape(raw_re["shape"])
|
||||
.tolist()
|
||||
)
|
||||
routed_experts = choice.get("routed_experts")
|
||||
|
||||
# /inference/v1/generate returns finish_reason in {"stop","length",...} —
|
||||
# never "tool_calls" (a chat-completions concept). Promote stop→tool_calls
|
||||
# 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 {
|
||||
@@ -183,6 +323,14 @@ async def generate(
|
||||
# callers can persist it on the trajectory step for downstream
|
||||
# multi-turn bridging and training-sample construction.
|
||||
"multi_modal_data": mm_data,
|
||||
# The renderer's per-token attribution for the prompt — either
|
||||
# the RenderedTokens computed here via renderer.render(...) or
|
||||
# the one threaded in by the caller alongside prompt_ids (the
|
||||
# bridge path). Lets downstream consumers (verifiers
|
||||
# RendererClient → prime-rl) build SFT-on-tool-body and other
|
||||
# selective loss masks without a second render pass. ``None``
|
||||
# when the caller passed prompt_ids without attribution.
|
||||
"prompt_attribution": prompt_attr,
|
||||
}
|
||||
|
||||
|
||||
@@ -212,6 +360,7 @@ def _build_mm_features(
|
||||
to change. Don't pre-build the abstraction with one engine in tree.
|
||||
"""
|
||||
from renderers.qwen3_vl import Qwen3VLRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
|
||||
# Type dispatch only needs the renderer class. Pools expose
|
||||
# ``renderer_cls`` as a snapshot attribute, so we don't have to check
|
||||
@@ -220,7 +369,10 @@ def _build_mm_features(
|
||||
renderer.renderer_cls if isinstance(renderer, RendererPool) else type(renderer)
|
||||
)
|
||||
|
||||
if issubclass(renderer_cls, Qwen3VLRenderer):
|
||||
# Qwen3-VL and Qwen3.5 both ship ``pixel_values`` + ``image_grid_thw``
|
||||
# via the shared Qwen2-VL field factory. ``spatial_merge_size=2`` is
|
||||
# the family default and matches every Qwen-VL processor in tree.
|
||||
if issubclass(renderer_cls, (Qwen3VLRenderer, Qwen35Renderer)):
|
||||
return _build_qwen_vl_features(mm_data, spatial_merge_size=2)
|
||||
|
||||
raise NotImplementedError(
|
||||
@@ -292,44 +444,3 @@ def _build_qwen_vl_features(
|
||||
out["kwargs_data"] = None
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def _log_overlong_prompt_diagnostic(
|
||||
*,
|
||||
prompt_ids: list[int],
|
||||
messages: list[Message],
|
||||
max_tokens: int | None,
|
||||
exc: BadRequestError,
|
||||
) -> None:
|
||||
"""Log a structured snapshot when vLLM rejects with 4xx — usually overlong.
|
||||
|
||||
Captures total prompt length, per-message role + character count, and
|
||||
the first chunk of the response body.
|
||||
"""
|
||||
body_text = ""
|
||||
response = getattr(exc, "response", None)
|
||||
if response is not None:
|
||||
body_text = (response.text or "")[:500].replace("\n", " ")
|
||||
msg_summary = []
|
||||
for i, m in enumerate(messages):
|
||||
role = m.get("role", "?")
|
||||
content = m.get("content")
|
||||
if isinstance(content, str):
|
||||
content_len = len(content)
|
||||
elif isinstance(content, list):
|
||||
content_len = sum(
|
||||
len(p.get("text", "")) if isinstance(p, dict) else 0 for p in content
|
||||
)
|
||||
else:
|
||||
content_len = 0
|
||||
tool_calls = m.get("tool_calls")
|
||||
tc_count = len(tool_calls) if tool_calls else 0
|
||||
msg_summary.append(f"[{i}]{role}(c={content_len},tc={tc_count})")
|
||||
_request_logger.warning(
|
||||
"vllm 4xx prompt_len=%d messages=%d max_tokens=%s per_msg=%s response_body=%s",
|
||||
len(prompt_ids),
|
||||
len(messages),
|
||||
max_tokens,
|
||||
" ".join(msg_summary),
|
||||
body_text,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
"""Typed renderer configs — one pydantic model per renderer, unified by a
|
||||
discriminated union (``RendererConfig``).
|
||||
|
||||
Each renderer accepts its own typed config; bad combinations (e.g.
|
||||
``add_vision_id`` under ``name="qwen3"``) fail at config-load time with a
|
||||
pydantic ``ValidationError`` rather than at runtime via an allowlist
|
||||
check. The shared ``preserve_*`` flags live on ``BaseRendererConfig``
|
||||
and OR-compose with template-level toggles (e.g. GLM-5
|
||||
``clear_thinking``) inside each renderer — they extend retention, never
|
||||
override the template into a drop.
|
||||
|
||||
``AutoRendererConfig`` is a placeholder variant: ``create_renderer``
|
||||
resolves it via ``MODEL_RENDERER_MAP`` and constructs the matching
|
||||
typed config with the auto config's ``preserve_*`` fields carried over.
|
||||
|
||||
``DefaultRendererConfig`` uses ``extra="allow"`` to accept arbitrary
|
||||
Jinja kwargs as ``model_extra`` — ``DefaultRenderer`` doesn't know which
|
||||
keys its tokenizer's template will honour, so it can't enumerate them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated, ClassVar, Literal, Union
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
|
||||
class BaseRendererConfig(BaseConfig):
|
||||
"""Shared fields and config for every renderer config variant.
|
||||
|
||||
Inherits from ``pydantic_config.BaseConfig`` so the typed-config
|
||||
surface stays uniform with prime-rl / verifiers config bases. The
|
||||
BaseConfig contract includes ``extra="forbid"`` (preserved here);
|
||||
this class adds ``frozen=True`` so configs are hashable value
|
||||
objects.
|
||||
|
||||
``preserve_all_thinking`` and ``preserve_thinking_between_tool_calls``
|
||||
are renderer-internal behaviour flags — they don't map to any Jinja
|
||||
chat-template kwarg. They OR-compose with template-level toggles on
|
||||
renderers that expose one (GLM-5 ``clear_thinking``, Nemotron-3
|
||||
``truncate_history_thinking``): either flag saying "keep this
|
||||
thinking" wins. preserve_* can only ever extend retention; setting
|
||||
``preserve_all_thinking=True`` always keeps past thinking, regardless
|
||||
of the template kwarg. See ``renderers.base.should_preserve_past_thinking``.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
preserve_all_thinking: bool = False
|
||||
"""Restore ``reasoning_content`` on every past assistant turn, even
|
||||
when the chat template would drop it. Strict superset of
|
||||
``preserve_thinking_between_tool_calls``."""
|
||||
|
||||
preserve_thinking_between_tool_calls: bool = False
|
||||
"""Restore ``reasoning_content`` only inside the in-flight tool cycle:
|
||||
the contiguous A-T-...-A block after the most recent ``user`` turn,
|
||||
and only if it contains at least one ``tool`` response. A new user
|
||||
turn closes the block and drops its thinking (template default)."""
|
||||
|
||||
# Fields that are renderer-internal — not forwarded to (or mirrored
|
||||
# by) ``apply_chat_template``. Override in subclasses that hold
|
||||
# non-template config (e.g. ``image_cache_max``, GptOss's
|
||||
# ``use_system_prompt`` / ``knowledge_cutoff`` / ``model_identity``,
|
||||
# or fields that exist as renderer conventions without a Jinja
|
||||
# analogue like DeepSeek V3 / Kimi K2 ``enable_thinking``).
|
||||
#
|
||||
# Used by parity tests to compute the field subset that, when
|
||||
# changed, must produce token streams matching
|
||||
# ``apply_chat_template`` — see :meth:`template_field_names`. The
|
||||
# renderer is the only end-to-end consumer of these fields, so this
|
||||
# is a renderer-side bookkeeping concern rather than a public API.
|
||||
_internal_fields: ClassVar[frozenset[str]] = frozenset()
|
||||
|
||||
@classmethod
|
||||
def template_field_names(cls) -> frozenset[str]:
|
||||
"""Subset of fields that mirror Jinja chat-template kwargs.
|
||||
|
||||
Default: every non-base field except ``name`` and any field
|
||||
listed in ``_internal_fields``. Used by the parity test matrix
|
||||
(``tests/test_renderer_config_parity.py``) to discover the
|
||||
cells that must agree with ``apply_chat_template``.
|
||||
"""
|
||||
base = frozenset(BaseRendererConfig.model_fields)
|
||||
return frozenset(cls.model_fields) - base - {"name"} - cls._internal_fields
|
||||
|
||||
|
||||
class AutoRendererConfig(BaseRendererConfig):
|
||||
"""Resolve the renderer from ``tokenizer.name_or_path`` at construction
|
||||
time via ``MODEL_RENDERER_MAP``. Carries only the shared ``preserve_*``
|
||||
fields; template kwargs require an explicit renderer choice so that
|
||||
template-dependent behaviour stays visible at the call site."""
|
||||
|
||||
name: Literal["auto"] = "auto"
|
||||
|
||||
|
||||
class DefaultRendererConfig(BaseRendererConfig):
|
||||
"""Config for ``DefaultRenderer`` — the fallback wrapping
|
||||
``tokenizer.apply_chat_template``. Accepts arbitrary extra fields
|
||||
via ``extra="allow"`` because the underlying Jinja template's kwargs
|
||||
are unknown to us. ``DefaultRenderer`` forwards ``model_extra`` to
|
||||
``apply_chat_template`` verbatim.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True, extra="allow")
|
||||
|
||||
name: Literal["default"] = "default"
|
||||
|
||||
tool_parser: str | None = None
|
||||
"""Name of a tool parser registered in ``renderers.parsers`` (e.g.
|
||||
``"qwen3"``, ``"glm"``). Consumed only by ``DefaultRenderer``."""
|
||||
|
||||
reasoning_parser: str | None = None
|
||||
"""Name of a reasoning parser registered in ``renderers.parsers``
|
||||
(e.g. ``"think"``). Consumed only by ``DefaultRenderer``."""
|
||||
|
||||
# tool_parser / reasoning_parser are renderer-internal — they configure
|
||||
# DefaultRenderer's parsing pipeline, not the underlying Jinja
|
||||
# template. Jinja kwargs live in ``model_extra`` (extra="allow").
|
||||
_internal_fields = frozenset({"tool_parser", "reasoning_parser"})
|
||||
|
||||
|
||||
class Qwen3RendererConfig(BaseRendererConfig):
|
||||
"""Qwen3 (text-only) renderer config."""
|
||||
|
||||
name: Literal["qwen3"] = "qwen3"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""When ``True``, the generation prompt includes ``<think>`` so the
|
||||
model continues into a thinking block. Mirrors the chat template's
|
||||
``enable_thinking`` kwarg."""
|
||||
|
||||
|
||||
class Qwen35RendererConfig(BaseRendererConfig):
|
||||
"""Qwen3.5 renderer config."""
|
||||
|
||||
name: Literal["qwen3.5"] = "qwen3.5"
|
||||
|
||||
enable_thinking: bool | None = None
|
||||
"""When ``True``, the generation prompt includes ``<think>``. ``None``
|
||||
auto-detects from the tokenizer's chat-template default — Instruct
|
||||
checkpoints default off, Thinking checkpoints default on. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
add_vision_id: bool = False
|
||||
"""When ``True``, prefix each ``<|vision_start|>`` placeholder with
|
||||
``"Picture N: "`` / ``"Video N: "`` where N is a 1-indexed counter
|
||||
running across the entire conversation. Mirrors the chat template's
|
||||
``add_vision_id`` toggle."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""FIFO bound on the per-renderer image processor cache. Renderer-
|
||||
internal — not a Jinja chat-template kwarg."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
|
||||
class Qwen36RendererConfig(BaseRendererConfig):
|
||||
"""Qwen3.6 renderer config. Inherits Qwen3.5's template surface."""
|
||||
|
||||
name: Literal["qwen3.6"] = "qwen3.6"
|
||||
|
||||
enable_thinking: bool | None = None
|
||||
"""See :class:`Qwen35RendererConfig.enable_thinking`."""
|
||||
|
||||
add_vision_id: bool = False
|
||||
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
|
||||
class Qwen3VLRendererConfig(BaseRendererConfig):
|
||||
"""Qwen3-VL renderer config."""
|
||||
|
||||
name: Literal["qwen3-vl"] = "qwen3-vl"
|
||||
|
||||
add_vision_id: bool = False
|
||||
"""See :class:`Qwen35RendererConfig.add_vision_id`."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
|
||||
class GLM5RendererConfig(BaseRendererConfig):
|
||||
"""GLM-5 renderer config."""
|
||||
|
||||
name: Literal["glm-5"] = "glm-5"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
clear_thinking: bool = True
|
||||
"""When ``False``, the renderer keeps ``<think>{reasoning}</think>``
|
||||
on past-cycle assistant turns instead of dropping them. Mirrors the
|
||||
chat template's ``clear_thinking`` toggle. OR-composes with
|
||||
``preserve_all_thinking`` / ``preserve_thinking_between_tool_calls``
|
||||
— see :class:`BaseRendererConfig` for the contract."""
|
||||
|
||||
|
||||
class GLM51RendererConfig(BaseRendererConfig):
|
||||
"""GLM-5.1 renderer config — same template surface as GLM-5, distinct
|
||||
discriminator so the registry can route to ``GLM51Renderer``."""
|
||||
|
||||
name: Literal["glm-5.1"] = "glm-5.1"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""See :class:`GLM5RendererConfig.enable_thinking`."""
|
||||
|
||||
clear_thinking: bool = True
|
||||
"""See :class:`GLM5RendererConfig.clear_thinking`."""
|
||||
|
||||
|
||||
class GLM45RendererConfig(BaseRendererConfig):
|
||||
"""GLM-4.5 Air renderer config."""
|
||||
|
||||
name: Literal["glm-4.5"] = "glm-4.5"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
|
||||
class GptOssRendererConfig(BaseRendererConfig):
|
||||
"""OpenAI gpt-oss (harmony) renderer config.
|
||||
|
||||
Several fields here are renderer-internal: ``use_system_prompt``,
|
||||
``knowledge_cutoff``, and ``model_identity`` control how the renderer
|
||||
builds the harmony ``SystemContent`` preamble and don't have direct
|
||||
Jinja-kwarg analogues. They're typed config rather than Jinja kwargs
|
||||
because users still want to set them — the distinction only matters
|
||||
for downstream tooling that synthesises a Jinja-kwargs view (none
|
||||
today, since vLLM is invoked via the token-in endpoint).
|
||||
"""
|
||||
|
||||
name: Literal["gpt-oss"] = "gpt-oss"
|
||||
|
||||
reasoning_effort: Literal["low", "medium", "high"] = "medium"
|
||||
"""Harmony reasoning-effort tag. Mirrors the ``apply_chat_template``
|
||||
``reasoning_effort`` kwarg."""
|
||||
|
||||
conversation_start_date: str | None = None
|
||||
"""ISO date string for the harmony preamble. ``None`` defers to
|
||||
today's date at render time."""
|
||||
|
||||
use_system_prompt: bool = True
|
||||
"""Prepend the canonical harmony ``SystemContent`` preamble. Matches
|
||||
HF's ``apply_chat_template`` behaviour."""
|
||||
|
||||
knowledge_cutoff: str | None = None
|
||||
"""Override the model's knowledge-cutoff string in the preamble.
|
||||
``None`` uses harmony's built-in default."""
|
||||
|
||||
model_identity: str | None = None
|
||||
"""Override the model-identity line in the preamble. ``None`` uses
|
||||
harmony's built-in default."""
|
||||
|
||||
_internal_fields = frozenset(
|
||||
{"use_system_prompt", "knowledge_cutoff", "model_identity"}
|
||||
)
|
||||
|
||||
|
||||
class KimiK2RendererConfig(BaseRendererConfig):
|
||||
"""Kimi K2 renderer config.
|
||||
|
||||
``enable_thinking`` is renderer-internal here — Kimi K2's chat
|
||||
template doesn't reference any thinking variable, so it's a no-op
|
||||
against ``apply_chat_template`` parity. The field is kept for
|
||||
protocol uniformity with the rest of the renderer family.
|
||||
"""
|
||||
|
||||
name: Literal["kimi-k2"] = "kimi-k2"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""No-op for Kimi K2 (template doesn't gate on it). Stored for
|
||||
introspection / cross-renderer uniformity."""
|
||||
|
||||
_internal_fields = frozenset({"enable_thinking"})
|
||||
|
||||
|
||||
class KimiK25RendererConfig(BaseRendererConfig):
|
||||
"""Kimi K2.5 renderer config."""
|
||||
|
||||
name: Literal["kimi-k2.5"] = "kimi-k2.5"
|
||||
|
||||
thinking: bool = True
|
||||
"""When ``True``, the generation prompt prefills ``<think>``; when
|
||||
``False`` it prefills ``<think></think>``. The kwarg is named
|
||||
``thinking`` (not ``enable_thinking``) to match the upstream chat
|
||||
template's native variable name."""
|
||||
|
||||
image_cache_max: int = 256
|
||||
"""See :class:`Qwen35RendererConfig.image_cache_max`."""
|
||||
|
||||
_internal_fields = frozenset({"image_cache_max"})
|
||||
|
||||
|
||||
class LagunaXS2RendererConfig(BaseRendererConfig):
|
||||
"""Laguna XS.2 renderer config."""
|
||||
|
||||
name: Literal["laguna-xs.2"] = "laguna-xs.2"
|
||||
|
||||
enable_thinking: bool = False
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg. Default ``False``
|
||||
matches the upstream Jinja default for Laguna XS.2."""
|
||||
|
||||
render_assistant_messages_raw: bool = False
|
||||
"""When ``True``, assistant messages render as a passthrough: the
|
||||
content bytes are emitted verbatim (no reasoning extraction, no
|
||||
tool-call XML synthesis), and the ``<think>``/``</think>`` prefix
|
||||
and ``</assistant>`` suffix are only added when missing. Mirrors the
|
||||
chat template's ``render_assistant_messages_raw`` gate."""
|
||||
|
||||
|
||||
class MiniMaxM2RendererConfig(BaseRendererConfig):
|
||||
"""MiniMax M2 / M2.5 renderer config."""
|
||||
|
||||
name: Literal["minimax-m2"] = "minimax-m2"
|
||||
|
||||
model_identity: str = "You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax."
|
||||
"""Fallback persona used when no system message is supplied. Mirrors
|
||||
the chat template's ``model_identity`` Jinja variable."""
|
||||
|
||||
|
||||
class Nemotron3RendererConfig(BaseRendererConfig):
|
||||
"""Nemotron 3 renderer config."""
|
||||
|
||||
name: Literal["nemotron-3"] = "nemotron-3"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""When ``True``, the generation prompt includes ``<think>``. Mirrors
|
||||
the chat template's ``enable_thinking`` kwarg."""
|
||||
|
||||
truncate_history_thinking: bool = True
|
||||
"""When ``False``, keep ``<think>{reasoning}</think>`` on past-cycle
|
||||
assistant turns instead of dropping them. Mirrors the chat
|
||||
template's ``truncate_history_thinking`` toggle. OR-composes with
|
||||
``preserve_all_thinking`` / ``preserve_thinking_between_tool_calls``
|
||||
— see :class:`BaseRendererConfig` for the contract."""
|
||||
|
||||
|
||||
class DeepSeekV3RendererConfig(BaseRendererConfig):
|
||||
"""DeepSeek V3 renderer config.
|
||||
|
||||
``enable_thinking`` is renderer-internal here — DeepSeek-V3's chat
|
||||
template does not reference any thinking variable, so passing it to
|
||||
``apply_chat_template`` upstream is a no-op. The renderer uses it
|
||||
to control the ``<think>`` prefill at the generation prompt (R1
|
||||
distill convention).
|
||||
"""
|
||||
|
||||
name: Literal["deepseek-v3"] = "deepseek-v3"
|
||||
|
||||
enable_thinking: bool = True
|
||||
"""Renderer convention for the R1-distill family: when ``True``,
|
||||
prefill ``<think>`` at the generation prompt. The DeepSeek-V3 Jinja
|
||||
template ignores this kwarg upstream; it's not a chat-template
|
||||
kwarg in the strict sense."""
|
||||
|
||||
_internal_fields = frozenset({"enable_thinking"})
|
||||
|
||||
|
||||
RendererConfig = Annotated[
|
||||
Union[
|
||||
AutoRendererConfig,
|
||||
DefaultRendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
Qwen36RendererConfig,
|
||||
Qwen3VLRendererConfig,
|
||||
GLM5RendererConfig,
|
||||
GLM51RendererConfig,
|
||||
GLM45RendererConfig,
|
||||
GptOssRendererConfig,
|
||||
KimiK2RendererConfig,
|
||||
KimiK25RendererConfig,
|
||||
LagunaXS2RendererConfig,
|
||||
MiniMaxM2RendererConfig,
|
||||
Nemotron3RendererConfig,
|
||||
DeepSeekV3RendererConfig,
|
||||
],
|
||||
Field(discriminator="name"),
|
||||
]
|
||||
"""Discriminated union over every renderer config variant.
|
||||
|
||||
Downstream pydantic configs (prime-rl orchestrator, verifiers
|
||||
``ClientConfig``) can hold a single field typed as ``RendererConfig``;
|
||||
deserialization dispatches on ``name`` and exposes strictly the kwargs
|
||||
that renderer supports. Bogus combinations (e.g. ``add_vision_id`` under
|
||||
``name="qwen3"``) raise ``ValidationError`` at config-load time.
|
||||
"""
|
||||
|
||||
|
||||
# Map discriminator → config class. Used by ``create_renderer`` when
|
||||
# resolving ``AutoRendererConfig`` against ``MODEL_RENDERER_MAP``: the
|
||||
# resolved renderer name picks the corresponding typed config, and the
|
||||
# auto config's ``preserve_*`` fields are carried over.
|
||||
_CONFIG_BY_NAME: dict[str, type[BaseRendererConfig]] = {
|
||||
"auto": AutoRendererConfig,
|
||||
"default": DefaultRendererConfig,
|
||||
"qwen3": Qwen3RendererConfig,
|
||||
"qwen3.5": Qwen35RendererConfig,
|
||||
"qwen3.6": Qwen36RendererConfig,
|
||||
"qwen3-vl": Qwen3VLRendererConfig,
|
||||
"glm-5": GLM5RendererConfig,
|
||||
"glm-5.1": GLM51RendererConfig,
|
||||
"glm-4.5": GLM45RendererConfig,
|
||||
"gpt-oss": GptOssRendererConfig,
|
||||
"kimi-k2": KimiK2RendererConfig,
|
||||
"kimi-k2.5": KimiK25RendererConfig,
|
||||
"laguna-xs.2": LagunaXS2RendererConfig,
|
||||
"minimax-m2": MiniMaxM2RendererConfig,
|
||||
"nemotron-3": Nemotron3RendererConfig,
|
||||
"deepseek-v3": DeepSeekV3RendererConfig,
|
||||
}
|
||||
|
||||
|
||||
def _config_class_for(name: str) -> type[BaseRendererConfig]:
|
||||
cls = _CONFIG_BY_NAME.get(name)
|
||||
if cls is None:
|
||||
raise ValueError(
|
||||
f"No renderer config registered for name={name!r}. "
|
||||
f"Known: {sorted(_CONFIG_BY_NAME)}"
|
||||
)
|
||||
return cls
|
||||
|
||||
|
||||
def config_from_name(name: str) -> BaseRendererConfig | None:
|
||||
"""Construct a default-valued config for the given renderer name.
|
||||
|
||||
Convenience for callers that hold a renderer name as a string and
|
||||
want the matching typed config. ``"auto"`` returns ``None`` —
|
||||
:func:`renderers.create_renderer` interprets that as "run auto
|
||||
resolution against ``MODEL_RENDERER_MAP``", which is what callers
|
||||
expect from a bare-string name.
|
||||
"""
|
||||
if name == "auto":
|
||||
return None
|
||||
return _config_class_for(name)()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AutoRendererConfig",
|
||||
"BaseRendererConfig",
|
||||
"DefaultRendererConfig",
|
||||
"DeepSeekV3RendererConfig",
|
||||
"GLM45RendererConfig",
|
||||
"GLM51RendererConfig",
|
||||
"GLM5RendererConfig",
|
||||
"GptOssRendererConfig",
|
||||
"KimiK25RendererConfig",
|
||||
"KimiK2RendererConfig",
|
||||
"LagunaXS2RendererConfig",
|
||||
"MiniMaxM2RendererConfig",
|
||||
"Nemotron3RendererConfig",
|
||||
"Qwen35RendererConfig",
|
||||
"Qwen36RendererConfig",
|
||||
"Qwen3RendererConfig",
|
||||
"Qwen3VLRendererConfig",
|
||||
"RendererConfig",
|
||||
"config_from_name",
|
||||
]
|
||||
+172
-52
@@ -21,9 +21,11 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import DeepSeekV3RendererConfig
|
||||
from renderers.parsing import parse_deepseek_v3
|
||||
|
||||
# Fullwidth vertical bar used in DeepSeek special token names.
|
||||
@@ -38,25 +40,25 @@ def _ds_token(name: str) -> str:
|
||||
|
||||
|
||||
class DeepSeekV3Renderer:
|
||||
"""Deterministic message → token renderer for DeepSeek V3 models."""
|
||||
"""Deterministic message → token renderer for DeepSeek V3 models.
|
||||
|
||||
DeepSeek-V3's chat template does not consult any thinking-related
|
||||
variable; the ``enable_thinking`` field on the typed config controls
|
||||
the renderer's ``<think>\\n`` prefill at the generation prompt
|
||||
(R1-distill convention) and is intentionally not forwarded to
|
||||
``apply_chat_template`` upstream — that would be a no-op. The
|
||||
template also always emits ``<think>{reasoning}</think>`` when
|
||||
``reasoning_content`` is provided, so ``preserve_*`` flags are
|
||||
no-ops here too; stored for protocol uniformity.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: DeepSeekV3RendererConfig | None = None,
|
||||
):
|
||||
# DeepSeek-V3's chat template always emits ``<think>{reasoning}</think>``
|
||||
# when ``reasoning_content`` is provided — no drop, so the override
|
||||
# flags are no-ops. Stored for introspection / Protocol parity only.
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or DeepSeekV3RendererConfig()
|
||||
|
||||
# ── BOS / EOS ────────────────────────────────────────────────
|
||||
self._bos = self._get_special_token(f"begin{_US}of{_US}sentence")
|
||||
@@ -113,20 +115,48 @@ class DeepSeekV3Renderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
emit_ids(self._encode(text), msg_idx)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── 1. BOS token ─────────────────────────────────────────────
|
||||
emit_special(self._bos, -1)
|
||||
emit_special(self._bos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Collect system messages at the start ───────────────────
|
||||
# All leading system messages are concatenated with "\n\n" and emitted
|
||||
@@ -148,7 +178,8 @@ class DeepSeekV3Renderer:
|
||||
|
||||
if sys_parts:
|
||||
# Attribute the concatenated system text to the first system message (index 0).
|
||||
emit_text("\n\n".join(sys_parts), 0)
|
||||
# The system content is the caller's body — mark is_content=True.
|
||||
emit_text("\n\n".join(sys_parts), 0, is_sampled=False, is_content=True)
|
||||
|
||||
# ── 3. Render non-system messages ─────────────────────────────
|
||||
num_messages = len(messages)
|
||||
@@ -163,8 +194,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, is_content=False)
|
||||
emit_text(str(content), i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "user":
|
||||
content = msg.get("content") or ""
|
||||
@@ -177,8 +208,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, is_content=False)
|
||||
emit_text(str(content), i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "assistant":
|
||||
self._render_assistant(
|
||||
@@ -187,6 +218,7 @@ class DeepSeekV3Renderer:
|
||||
messages,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
@@ -195,6 +227,7 @@ class DeepSeekV3Renderer:
|
||||
i,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
# ── 4. Generation prompt ──────────────────────────────────────
|
||||
@@ -202,11 +235,19 @@ 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)
|
||||
if self._enable_thinking:
|
||||
emit_text("<think>\n", -1)
|
||||
emit_special(
|
||||
self._assistant_token, -1, is_sampled=False, is_content=False
|
||||
)
|
||||
if self.config.enable_thinking:
|
||||
emit_text("<think>\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(token_ids=tokens, message_indices=indices)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
@@ -221,7 +262,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 +307,40 @@ class DeepSeekV3Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask.
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
@@ -279,11 +353,11 @@ class DeepSeekV3Renderer:
|
||||
|
||||
if role == "user":
|
||||
emit_special(self._user_token, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
elif role == "system":
|
||||
# Post-initial system messages render as user turns.
|
||||
emit_special(self._user_token, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
elif role == "tool":
|
||||
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
|
||||
next_is_tool = (
|
||||
@@ -293,7 +367,7 @@ class DeepSeekV3Renderer:
|
||||
if not prev_is_tool:
|
||||
emit_special(self._tool_outputs_begin, i)
|
||||
emit_special(self._tool_output_begin, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
emit_special(self._tool_output_end, i)
|
||||
if not next_is_tool:
|
||||
emit_special(self._tool_outputs_end, i)
|
||||
@@ -306,10 +380,17 @@ class DeepSeekV3Renderer:
|
||||
last_role = new_messages[-1].get("role") if new_messages else None
|
||||
if last_role != "tool":
|
||||
emit_special(self._assistant_token, -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.enable_thinking:
|
||||
emit_text("<think>\n", -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Assistant rendering
|
||||
@@ -323,6 +404,7 @@ class DeepSeekV3Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Determine whether this message follows a tool output sequence.
|
||||
# The HF template emits <|tool▁outputs▁end|> before the assistant content
|
||||
@@ -349,17 +431,29 @@ 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|>``). On assistant
|
||||
# the invariant ``is_content == sampled_mask`` holds.
|
||||
if not prev_is_tool:
|
||||
emit_special(self._assistant_token, msg_idx)
|
||||
emit_special(
|
||||
self._assistant_token, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
if not tool_calls:
|
||||
emit_text(content, msg_idx)
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
# Emit any pre-tool-call content first.
|
||||
emit_text(content, msg_idx)
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool call section.
|
||||
emit_special(self._tool_calls_begin, msg_idx)
|
||||
emit_special(
|
||||
self._tool_calls_begin, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
@@ -371,14 +465,28 @@ class DeepSeekV3Renderer:
|
||||
)
|
||||
# Format: <|tool▁call▁begin|>function<|tool▁sep|>{name}\n```json\n{args}\n```<|tool▁call▁end|>
|
||||
# tool_sep is a special token; type ("function") and name+args are plain text.
|
||||
emit_special(self._tool_call_begin, msg_idx)
|
||||
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, is_content=True
|
||||
)
|
||||
emit_text("function", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._tool_sep, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
f"{name}\n```json\n{args_str}\n```",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(
|
||||
self._tool_calls_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
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, is_content=True)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Tool (tool-response) rendering
|
||||
@@ -391,7 +499,13 @@ class DeepSeekV3Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# body bytes get ``is_content=True``; the surrounding section
|
||||
# specials are scaffold.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
@@ -402,11 +516,17 @@ class DeepSeekV3Renderer:
|
||||
content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._tool_outputs_begin, msg_idx)
|
||||
emit_special(
|
||||
self._tool_outputs_begin, msg_idx, is_sampled=False, is_content=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, is_content=False
|
||||
)
|
||||
emit_text(str(content), msg_idx, is_sampled=False, is_content=True)
|
||||
emit_special(self._tool_output_end, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if not next_is_tool:
|
||||
emit_special(self._tool_outputs_end, msg_idx)
|
||||
emit_special(
|
||||
self._tool_outputs_end, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
+26
-23
@@ -19,9 +19,8 @@ from renderers.base import (
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
)
|
||||
from renderers.configs import DefaultRendererConfig
|
||||
from renderers.parsers import (
|
||||
ReasoningParser,
|
||||
ToolParser,
|
||||
get_reasoning_parser,
|
||||
get_tool_parser,
|
||||
)
|
||||
@@ -82,36 +81,30 @@ def _decode_tool_call_arguments(messages: list) -> list:
|
||||
class DefaultRenderer:
|
||||
"""Fallback renderer using tokenizer.apply_chat_template().
|
||||
|
||||
Works with any model. Pass ``tool_parser`` and/or ``reasoning_parser``
|
||||
(by name, resolved against the registries in ``renderers.parsers``) to
|
||||
enable structured output extraction.
|
||||
Works with any model. The config can carry ``tool_parser`` and/or
|
||||
``reasoning_parser`` (resolved against ``renderers.parsers``) to
|
||||
enable structured output extraction, plus arbitrary additional Jinja
|
||||
template kwargs captured as ``model_extra`` (``extra="allow"`` on
|
||||
:class:`renderers.DefaultRendererConfig`).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
tool_parser: str | ToolParser | None = None,
|
||||
reasoning_parser: str | ReasoningParser | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
**chat_template_kwargs,
|
||||
config: DefaultRendererConfig | None = None,
|
||||
):
|
||||
if preserve_all_thinking or preserve_thinking_between_tool_calls:
|
||||
cfg = config or DefaultRendererConfig()
|
||||
if cfg.preserve_all_thinking or cfg.preserve_thinking_between_tool_calls:
|
||||
raise NotImplementedError(
|
||||
"DefaultRenderer falls back to apply_chat_template and can't "
|
||||
"selectively re-emit dropped reasoning_content. Configure a "
|
||||
"model-specific renderer if you need preserve_*_thinking."
|
||||
)
|
||||
self._tokenizer = tokenizer
|
||||
self._chat_template_kwargs = chat_template_kwargs
|
||||
self._tool_parser = _resolve_parser(tool_parser, tokenizer, get_tool_parser)
|
||||
self.config = cfg
|
||||
self._tool_parser = _resolve_parser(cfg.tool_parser, tokenizer, get_tool_parser)
|
||||
self._reasoning_parser = _resolve_parser(
|
||||
reasoning_parser, tokenizer, get_reasoning_parser
|
||||
)
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
cfg.reasoning_parser, tokenizer, get_reasoning_parser
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -143,10 +136,15 @@ class DefaultRenderer:
|
||||
token_ids = full_ids
|
||||
message_indices.extend([-1] * len(gen_tokens))
|
||||
|
||||
return RenderedTokens(token_ids=token_ids, message_indices=message_indices)
|
||||
message_roles = [m.get("role") or "" for m in messages]
|
||||
return RenderedTokens(
|
||||
token_ids=token_ids,
|
||||
message_indices=message_indices,
|
||||
message_roles=message_roles,
|
||||
)
|
||||
|
||||
def _apply(self, messages, *, tools=None, add_generation_prompt=False) -> list[int]:
|
||||
kwargs = dict(self._chat_template_kwargs)
|
||||
kwargs = dict(self.config.model_extra or {})
|
||||
kwargs["add_generation_prompt"] = add_generation_prompt
|
||||
kwargs["tokenize"] = True
|
||||
if tools is not None:
|
||||
@@ -167,14 +165,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).
|
||||
|
||||
+237
-68
@@ -20,9 +20,11 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
)
|
||||
from renderers.configs import GLM45RendererConfig
|
||||
from renderers.parsing import parse_glm
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
@@ -52,17 +54,10 @@ class GLM45Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: GLM45RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or GLM45RendererConfig()
|
||||
|
||||
self._gmask = self._token_id("[gMASK]")
|
||||
self._sop = self._token_id("<sop>")
|
||||
@@ -127,28 +122,59 @@ class GLM45Renderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated segments as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment.
|
||||
|
||||
Lets call sites express "this wrap + this body, joined the
|
||||
same way as the chat template, but attributed separately"
|
||||
without splitting the encode call (which could shift BPE
|
||||
merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── Prefix ──────────────────────────────────────────────────
|
||||
emit_special(self._gmask, -1)
|
||||
emit_special(self._sop, -1)
|
||||
emit_special(self._gmask, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._sop, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Tools in system prompt ──────────────────────────────────
|
||||
# The tools-header block is all scaffold by design — the tools
|
||||
# dict is recoverable from the ``tools`` argument; don't
|
||||
# re-attribute the embedded JSON specs as message body.
|
||||
if tools:
|
||||
emit_special(self._system, -1)
|
||||
emit_special(self._system, -1, is_sampled=False, is_content=False)
|
||||
tool_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
|
||||
tool_text += _TOOLS_FOOTER
|
||||
emit_text(tool_text, -1)
|
||||
emit_text(tool_text, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Compute last_user_index ─────────────────────────────────
|
||||
last_ui = self._last_user_index(messages)
|
||||
@@ -159,22 +185,29 @@ 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, is_content=False)
|
||||
# ``\n`` is the scaffold separator after the role tag;
|
||||
# the body proper is the caller-provided content.
|
||||
emit_text_segments(
|
||||
[("\n", False), (content, True)], i, is_sampled=False
|
||||
)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._user, i)
|
||||
user_text = "\n" + content
|
||||
if not self._enable_thinking and not content.endswith("/nothink"):
|
||||
user_text += "/nothink"
|
||||
emit_text(user_text, i)
|
||||
emit_special(self._user, i, is_sampled=False, is_content=False)
|
||||
# ``\n`` is scaffold; ``content`` is body; the optional
|
||||
# ``/nothink`` suffix is scaffold the renderer injects
|
||||
# when ``enable_thinking=False``.
|
||||
user_segments: list[tuple[str, bool]] = [("\n", False), (content, True)]
|
||||
if not self.config.enable_thinking and not content.endswith("/nothink"):
|
||||
user_segments.append(("/nothink", False))
|
||||
emit_text_segments(user_segments, i, is_sampled=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
@@ -184,22 +217,34 @@ class GLM45Renderer:
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
messages, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
# ── Generation prompt ───────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1)
|
||||
if not self._enable_thinking:
|
||||
emit_text("\n", -1)
|
||||
emit_special(self._think, -1)
|
||||
emit_special(self._think_end, -1)
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
if not self.config.enable_thinking:
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(token_ids=tokens, message_indices=indices)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
@@ -214,7 +259,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 +277,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 +311,56 @@ class GLM45Renderer:
|
||||
last_prev = previous_ids[-1]
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
@@ -273,31 +368,48 @@ class GLM45Renderer:
|
||||
if role == "user":
|
||||
if not (i == 0 and last_prev == self._user):
|
||||
emit_special(self._user, i)
|
||||
user_text = "\n" + content
|
||||
if not self._enable_thinking and not content.endswith("/nothink"):
|
||||
user_text += "/nothink"
|
||||
emit_text(user_text, i)
|
||||
user_segments: list[tuple[str, bool]] = [
|
||||
("\n", False),
|
||||
(content, True),
|
||||
]
|
||||
if not self.config.enable_thinking and not content.endswith("/nothink"):
|
||||
user_segments.append(("/nothink", False))
|
||||
emit_text_segments(user_segments, i)
|
||||
elif role == "system":
|
||||
emit_special(self._system, i)
|
||||
emit_text("\n" + content, i)
|
||||
emit_text_segments([("\n", False), (content, True)], i)
|
||||
elif role == "tool":
|
||||
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
|
||||
if i == 0 and last_prev == self._observation:
|
||||
pass
|
||||
elif not prev_is_tool:
|
||||
emit_special(self._observation, i)
|
||||
emit_text("\n<tool_response>\n" + content + "\n</tool_response>", i)
|
||||
emit_text_segments(
|
||||
[
|
||||
("\n<tool_response>\n", False),
|
||||
(content, True),
|
||||
("\n</tool_response>", False),
|
||||
],
|
||||
i,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
# Generation prompt.
|
||||
emit_special(self._assistant, -1)
|
||||
if not self._enable_thinking:
|
||||
if not self.config.enable_thinking:
|
||||
emit_text("\n", -1)
|
||||
emit_special(self._think, -1)
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -309,6 +421,7 @@ class GLM45Renderer:
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
):
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
@@ -322,24 +435,45 @@ 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.
|
||||
#
|
||||
# Invariant on assistant tokens: ``is_content == sampled_mask``.
|
||||
# Every scaffold token here gets ``is_sampled=False/is_content=False``;
|
||||
# every model-sampled emit gets both True.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if (msg_idx > last_user_index or preserve_thinking) and reasoning_content:
|
||||
emit_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, is_content=True)
|
||||
emit_text(
|
||||
reasoning_content.strip(), msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_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, is_content=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool calls — keep content + \n contiguous to preserve BPE merges
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
if content.strip() and tool_calls:
|
||||
emit_text("\n" + content.strip() + "\n", msg_idx)
|
||||
emit_text(
|
||||
"\n" + content.strip() + "\n", msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
elif content.strip():
|
||||
emit_text("\n" + content.strip(), msg_idx)
|
||||
emit_text("\n" + content.strip(), msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
@@ -347,9 +481,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, is_content=True)
|
||||
emit_special(self._tool_call_tok, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(name + "\n", msg_idx, is_sampled=True, is_content=True)
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
# per-argument rendering below still works.
|
||||
if isinstance(arguments, str):
|
||||
@@ -359,18 +493,33 @@ 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, is_content=True
|
||||
)
|
||||
emit_text(arg_name, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._arg_key_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._arg_value, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
if isinstance(arg_value, str):
|
||||
emit_text(arg_value, msg_idx)
|
||||
emit_text(arg_value, msg_idx, is_sampled=True, is_content=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,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._arg_value_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end_tok, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -380,10 +529,30 @@ class GLM45Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. The body bytes
|
||||
# get ``is_content=True``; the ``\n<tool_response>\n`` /
|
||||
# ``\n</tool_response>`` wraps and the ``<|observation|>`` role
|
||||
# tag are scaffold so the SFT mask for tool body never trains
|
||||
# the model to emit them. Single BPE pass over the joined text
|
||||
# preserves boundary merges (the tool body's leading/trailing
|
||||
# chars can merge with the wrap's ``\n``s if the tokenizer would
|
||||
# do so; we route through ``emit_text_segments`` so the
|
||||
# attribution is offset-driven and tokenizer-agnostic).
|
||||
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, is_content=False)
|
||||
|
||||
emit_text("\n<tool_response>\n" + content + "\n</tool_response>", msg_idx)
|
||||
emit_text_segments(
|
||||
[
|
||||
("\n<tool_response>\n", False),
|
||||
(content, True),
|
||||
("\n</tool_response>", False),
|
||||
],
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
)
|
||||
|
||||
+236
-63
@@ -21,9 +21,11 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
)
|
||||
from renderers.configs import GLM5RendererConfig, GLM51RendererConfig
|
||||
from renderers.parsing import parse_glm
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
@@ -53,20 +55,18 @@ class GLM5Renderer:
|
||||
# GLM51Renderer; GLM-5 proper keeps this off.
|
||||
empty_think_on_last_assistant: bool = False
|
||||
|
||||
# GLM-5.1 uses the same template surface and binds the same kwargs.
|
||||
# Subclassed in ``GLM51Renderer`` so the registry can dispatch on the
|
||||
# ``glm-5.1`` discriminator while sharing this implementation.
|
||||
_config_cls: type = GLM5RendererConfig
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: GLM5RendererConfig | GLM51RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or type(self)._config_cls()
|
||||
|
||||
self._gmask = self._token_id("[gMASK]")
|
||||
self._sop = self._token_id("<sop>")
|
||||
@@ -142,28 +142,62 @@ class GLM5Renderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated segments as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment.
|
||||
|
||||
Lets call sites express "this wrap + this body, joined the
|
||||
same way as the chat template, but attributed separately"
|
||||
without splitting the encode call (which could shift BPE
|
||||
merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── Prefix ──────────────────────────────────────────────────
|
||||
emit_special(self._gmask, -1)
|
||||
emit_special(self._sop, -1)
|
||||
# ``[gMASK]<sop>`` is unconditional template scaffolding at the
|
||||
# very start of the stream — the model never samples these and
|
||||
# they are not part of any message body.
|
||||
emit_special(self._gmask, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._sop, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Tools in system prompt ──────────────────────────────────
|
||||
# The tools-header block is all scaffold by design — the tools
|
||||
# dict is recoverable from the ``tools`` argument; don't
|
||||
# re-attribute the embedded JSON specs as message body.
|
||||
if tools:
|
||||
emit_special(self._system, -1)
|
||||
emit_special(self._system, -1, is_sampled=False, is_content=False)
|
||||
tool_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tool_text += self._format_tool_spec(tool) + "\n"
|
||||
tool_text += _TOOLS_FOOTER
|
||||
emit_text(tool_text, -1)
|
||||
emit_text(tool_text, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Compute last_user_index ─────────────────────────────────
|
||||
last_ui = self._last_user_index(messages)
|
||||
@@ -174,19 +208,19 @@ 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, is_content=False)
|
||||
emit_text(content, i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._user, i)
|
||||
emit_text(content, i)
|
||||
emit_special(self._user, i, is_sampled=False, is_content=False)
|
||||
emit_text(content, i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
@@ -196,22 +230,37 @@ class GLM5Renderer:
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
messages, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
# ── Generation prompt ───────────────────────────────────────
|
||||
# Gen prompt tokens are what the chat template prepends before
|
||||
# sampling starts — the model continues from these, never emits
|
||||
# them. Always is_sampled=False / is_content=False.
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._think_end, -1)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(token_ids=tokens, message_indices=indices)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
@@ -226,7 +275,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 +293,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 +331,56 @@ class GLM5Renderer:
|
||||
last_prev = previous_ids[-1]
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
@@ -290,10 +389,10 @@ class GLM5Renderer:
|
||||
# Dedup: model already emitted <|user|> as its stop token.
|
||||
if not (i == 0 and last_prev == self._user):
|
||||
emit_special(self._user, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
elif role == "system":
|
||||
emit_special(self._system, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
elif role == "tool":
|
||||
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
|
||||
if i == 0 and last_prev == self._observation:
|
||||
@@ -302,19 +401,26 @@ class GLM5Renderer:
|
||||
elif not prev_is_tool:
|
||||
emit_special(self._observation, i)
|
||||
emit_special(self._tool_response_tok, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
emit_special(self._tool_response_end_tok, i)
|
||||
else:
|
||||
return None
|
||||
|
||||
# Generation prompt — match the gen-prompt branch of ``render()``.
|
||||
emit_special(self._assistant, -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
else:
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -326,6 +432,7 @@ class GLM5Renderer:
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
):
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
@@ -339,42 +446,81 @@ 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.
|
||||
#
|
||||
# Invariant on assistant tokens: ``is_content == sampled_mask``.
|
||||
# Every scaffold token here gets ``is_sampled=False/is_content=False``;
|
||||
# every model-sampled emit gets both True.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Chat-template default: keep ``<think>`` only on the in-flight cycle
|
||||
# (post-last-user). Past-cycle assistants drop their reasoning.
|
||||
# ``preserve_thinking`` is the override output of
|
||||
# ``should_preserve_past_thinking`` — it adds historical assistants
|
||||
# back when the renderer was constructed with
|
||||
# ``preserve_all_thinking=True``.
|
||||
# ``preserve_all_thinking=True``. ``clear_thinking=False`` mirrors
|
||||
# the template's per-call ``clear_thinking is defined and not
|
||||
# clear_thinking`` gate: a chat_template_kwarg surface for the
|
||||
# same behaviour, gated explicitly by the caller per render.
|
||||
include_thinking = (
|
||||
msg_idx > last_user_index or preserve_thinking
|
||||
msg_idx > last_user_index
|
||||
or preserve_thinking
|
||||
or not self.config.clear_thinking
|
||||
) and reasoning_content
|
||||
|
||||
if include_thinking:
|
||||
emit_special(self._think, msg_idx)
|
||||
emit_text(reasoning_content.strip(), msg_idx)
|
||||
emit_special(self._think_end, msg_idx)
|
||||
elif self.empty_think_on_last_assistant and msg_idx > last_user_index:
|
||||
# ``<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, is_content=False)
|
||||
emit_text(
|
||||
reasoning_content.strip(), msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
elif (
|
||||
self.empty_think_on_last_assistant
|
||||
and msg_idx > last_user_index
|
||||
and self.config.enable_thinking
|
||||
):
|
||||
# GLM-5.1: wrap the last assistant with an empty <think></think>
|
||||
# even without reasoning, matching the Jinja template.
|
||||
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.
|
||||
#
|
||||
# When ``enable_thinking=False`` the GLM-5.1 template skips
|
||||
# the opening ``<think>`` for the most-recent assistant too
|
||||
# — it emits only the lone ``</think>`` separator (and the
|
||||
# gen prompt likewise switches to ``</think>``). Fall
|
||||
# through to the else branch below so we match.
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
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, is_content=False)
|
||||
|
||||
if content.strip():
|
||||
emit_text(content.strip(), msg_idx)
|
||||
emit_text(content.strip(), msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool calls (directly after content, no newlines)
|
||||
# Tool calls (directly after content, no newlines). All of these
|
||||
# are the model's sampled output — both is_sampled and is_content
|
||||
# are True across the entire tool-call span.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
|
||||
emit_special(self._tool_call_tok, msg_idx)
|
||||
emit_text(name, msg_idx)
|
||||
emit_special(self._tool_call_tok, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(name, msg_idx, is_sampled=True, is_content=True)
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
# per-argument rendering below still works.
|
||||
if isinstance(arguments, str):
|
||||
@@ -384,16 +530,31 @@ 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, is_content=True
|
||||
)
|
||||
emit_text(arg_name, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._arg_key_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(
|
||||
self._arg_value, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
if isinstance(arg_value, str):
|
||||
emit_text(arg_value, msg_idx)
|
||||
emit_text(arg_value, msg_idx, is_sampled=True, is_content=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,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._arg_value_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(
|
||||
self._tool_call_end_tok, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -403,15 +564,26 @@ class GLM5Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. The tool body
|
||||
# bytes get ``is_content=True``; the ``<|observation|>`` /
|
||||
# ``<tool_response>`` wraps are scaffold so the SFT mask for
|
||||
# tool body never trains the model to emit them.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._observation, msg_idx)
|
||||
emit_special(self._observation, msg_idx, is_sampled=False, is_content=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, is_content=False
|
||||
)
|
||||
emit_text(content, msg_idx, is_sampled=False, is_content=True)
|
||||
emit_special(
|
||||
self._tool_response_end_tok, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
|
||||
class GLM51Renderer(GLM5Renderer):
|
||||
@@ -429,6 +601,7 @@ class GLM51Renderer(GLM5Renderer):
|
||||
"""
|
||||
|
||||
empty_think_on_last_assistant = True
|
||||
_config_cls = GLM51RendererConfig
|
||||
|
||||
@staticmethod
|
||||
def _format_tool_spec(tool: ToolSpec) -> str:
|
||||
|
||||
+278
-52
@@ -60,6 +60,7 @@ from renderers.base import (
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import GptOssRendererConfig
|
||||
from renderers.parsing import parse_gpt_oss
|
||||
|
||||
|
||||
@@ -121,44 +122,27 @@ class GptOssRenderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
use_system_prompt: bool = True,
|
||||
reasoning_effort: str | None = "medium",
|
||||
conversation_start_date: str | None = None,
|
||||
knowledge_cutoff: str | None = None,
|
||||
model_identity: str | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: GptOssRendererConfig | None = None,
|
||||
):
|
||||
"""Initialise the renderer.
|
||||
|
||||
Args:
|
||||
tokenizer: HuggingFace tokenizer.
|
||||
use_system_prompt: When True (default), prepend the canonical
|
||||
harmony SystemContent preamble. Matches HF's
|
||||
apply_chat_template behaviour.
|
||||
reasoning_effort: ``"low" | "medium" | "high"``. Default
|
||||
``"medium"`` (matches apply_chat_template).
|
||||
conversation_start_date: Optional ISO date for the preamble.
|
||||
Defaults to today's date in YYYY-MM-DD form.
|
||||
knowledge_cutoff: Optional knowledge cutoff string. Harmony's
|
||||
default is built into ``SystemContent.new()``.
|
||||
model_identity: Optional override for the model identity line.
|
||||
config: Typed renderer config (see
|
||||
:class:`renderers.GptOssRendererConfig`).
|
||||
"""
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or GptOssRendererConfig()
|
||||
self._enc: HarmonyEncoding = load_harmony_encoding(
|
||||
HarmonyEncodingName.HARMONY_GPT_OSS
|
||||
)
|
||||
self._use_system_prompt = use_system_prompt
|
||||
self._reasoning_effort = _reasoning_effort(reasoning_effort)
|
||||
self._conversation_start_date = (
|
||||
conversation_start_date or datetime.now().strftime("%Y-%m-%d")
|
||||
)
|
||||
self._knowledge_cutoff = knowledge_cutoff
|
||||
self._model_identity = model_identity
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
# Materialised harmony-enum form of reasoning_effort.
|
||||
self._reasoning_effort_enum = _reasoning_effort(self.config.reasoning_effort)
|
||||
# ``conversation_start_date=None`` defers to today's date —
|
||||
# materialise once at construction so renders within the same
|
||||
# instance use a stable date.
|
||||
self._conversation_start_date_resolved = (
|
||||
self.config.conversation_start_date or datetime.now().strftime("%Y-%m-%d")
|
||||
)
|
||||
|
||||
# Cache special-token IDs for the bridge / generation-prompt path.
|
||||
@@ -184,6 +168,90 @@ class GptOssRenderer:
|
||||
return []
|
||||
return self._tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
def _prefix_content_mask(
|
||||
self,
|
||||
prefix_tokens: list[int],
|
||||
first_system_idx: int | None,
|
||||
messages: list[Message],
|
||||
tools: list[ToolSpec] | None,
|
||||
) -> list[bool]:
|
||||
"""Per-token is_content mask over the rendered system+developer prefix.
|
||||
|
||||
Harmony's prefix is one opaque block. The caller's system content
|
||||
lands inside the developer message as ``# Instructions\\n\\n{content}``.
|
||||
To attribute body bytes back, we render the same prefix with empty
|
||||
instructions and diff: the unique-to-with-instructions span is the
|
||||
body region. Falls back to all-False (whole prefix scaffold) if
|
||||
the caller didn't supply a system message — there's no body to
|
||||
attribute in that case.
|
||||
"""
|
||||
n = len(prefix_tokens)
|
||||
mask = [False] * n
|
||||
if first_system_idx is None:
|
||||
return mask
|
||||
instructions = _content_text(messages[first_system_idx].get("content"))
|
||||
if not instructions:
|
||||
return mask
|
||||
|
||||
# Build the same prefix with empty instructions.
|
||||
empty_prefix_msgs: list[HarmonyMessage] = []
|
||||
if self.config.use_system_prompt:
|
||||
sys_content = SystemContent.new().with_reasoning_effort(
|
||||
self._reasoning_effort_enum
|
||||
)
|
||||
sys_content = sys_content.with_conversation_start_date(
|
||||
self._conversation_start_date_resolved
|
||||
)
|
||||
if self.config.knowledge_cutoff is not None:
|
||||
sys_content = sys_content.with_knowledge_cutoff(
|
||||
self.config.knowledge_cutoff
|
||||
)
|
||||
if self.config.model_identity is not None:
|
||||
sys_content = sys_content.with_model_identity(
|
||||
self.config.model_identity
|
||||
)
|
||||
empty_prefix_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
|
||||
)
|
||||
dev = DeveloperContent.new()
|
||||
if tools:
|
||||
dev = dev.with_function_tools([_tool_to_description(t) for t in tools])
|
||||
empty_prefix_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev)
|
||||
)
|
||||
try:
|
||||
empty_tokens = self._enc.render_conversation(
|
||||
Conversation.from_messages(empty_prefix_msgs)
|
||||
)
|
||||
except Exception:
|
||||
return mask
|
||||
|
||||
# Longest common prefix.
|
||||
i_start = 0
|
||||
n_empty = len(empty_tokens)
|
||||
while (
|
||||
i_start < min(n, n_empty)
|
||||
and prefix_tokens[i_start] == empty_tokens[i_start]
|
||||
):
|
||||
i_start += 1
|
||||
# Longest common suffix.
|
||||
j_full = n
|
||||
j_empty = n_empty
|
||||
while (
|
||||
j_full > i_start
|
||||
and j_empty > i_start
|
||||
and prefix_tokens[j_full - 1] == empty_tokens[j_empty - 1]
|
||||
):
|
||||
j_full -= 1
|
||||
j_empty -= 1
|
||||
# Tokens [i_start:j_full] in prefix_tokens are unique to the
|
||||
# with-instructions render — that's the body span (includes the
|
||||
# ``# Instructions\n\n`` scaffolding header, which the substring
|
||||
# match in the body-decode test ignores).
|
||||
for k in range(i_start, j_full):
|
||||
mask[k] = True
|
||||
return mask
|
||||
|
||||
# ── public interface ─────────────────────────────────────────────────────
|
||||
|
||||
def render(
|
||||
@@ -198,10 +266,84 @@ class GptOssRenderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit(ids: list[int], msg_idx: int) -> None:
|
||||
def emit(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_harmony_message(
|
||||
hm_ids: list[int], msg_idx: int, *, is_assistant: bool
|
||||
) -> 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``.
|
||||
|
||||
``is_content`` further splits the body: the trailing
|
||||
terminator (``<|end|>`` / ``<|return|>`` / ``<|call|>``) is
|
||||
scaffold on non-assistant turns; on assistant turns it's the
|
||||
model's stop signal, so ``is_content=True`` mirrors
|
||||
``sampled_mask`` as the invariant on assistant requires.
|
||||
The body bytes between ``<|message|>`` and the terminator
|
||||
are body (``is_content=True``) on every role — that's the
|
||||
caller-provided content (or, for assistant, the model's
|
||||
sampled emission). The header (``<|start|>`` ... ``<|message|>``)
|
||||
— including any ``functions.{name}`` recipient text on tool
|
||||
results, which comes from a prior assistant's tool_calls
|
||||
rather than this tool message's own content — is scaffold.
|
||||
"""
|
||||
try:
|
||||
msg_marker = hm_ids.index(self._message)
|
||||
except ValueError:
|
||||
# Defensive: a harmony message without <|message|> is
|
||||
# malformed. Treat the whole thing as scaffolding.
|
||||
emit(hm_ids, msg_idx, is_sampled=False, is_content=False)
|
||||
return
|
||||
header = hm_ids[: msg_marker + 1]
|
||||
body = hm_ids[msg_marker + 1 :]
|
||||
emit(header, msg_idx, is_sampled=False, is_content=False)
|
||||
# Split body into content + terminator. The terminator (if
|
||||
# present) is the last token of the body and is one of the
|
||||
# three harmony stop tokens.
|
||||
terminator_ids = {self._end, self._return, self._call}
|
||||
if body and body[-1] in terminator_ids:
|
||||
body_content = body[:-1]
|
||||
terminator = body[-1:]
|
||||
else:
|
||||
body_content = body
|
||||
terminator = []
|
||||
emit(
|
||||
body_content,
|
||||
msg_idx,
|
||||
is_sampled=is_assistant,
|
||||
is_content=True,
|
||||
)
|
||||
if terminator:
|
||||
emit(
|
||||
terminator,
|
||||
msg_idx,
|
||||
is_sampled=is_assistant,
|
||||
is_content=is_assistant,
|
||||
)
|
||||
|
||||
# ── Build harmony prefix (system + developer) ───────────────────
|
||||
# When tools are present, harmony's conversation-level renderer
|
||||
@@ -215,17 +357,21 @@ class GptOssRenderer:
|
||||
None,
|
||||
)
|
||||
prefix_msgs: list[HarmonyMessage] = []
|
||||
if self._use_system_prompt:
|
||||
if self.config.use_system_prompt:
|
||||
sys_content = SystemContent.new().with_reasoning_effort(
|
||||
self._reasoning_effort
|
||||
self._reasoning_effort_enum
|
||||
)
|
||||
sys_content = sys_content.with_conversation_start_date(
|
||||
self._conversation_start_date
|
||||
self._conversation_start_date_resolved
|
||||
)
|
||||
if self._knowledge_cutoff is not None:
|
||||
sys_content = sys_content.with_knowledge_cutoff(self._knowledge_cutoff)
|
||||
if self._model_identity is not None:
|
||||
sys_content = sys_content.with_model_identity(self._model_identity)
|
||||
if self.config.knowledge_cutoff is not None:
|
||||
sys_content = sys_content.with_knowledge_cutoff(
|
||||
self.config.knowledge_cutoff
|
||||
)
|
||||
if self.config.model_identity is not None:
|
||||
sys_content = sys_content.with_model_identity(
|
||||
self.config.model_identity
|
||||
)
|
||||
prefix_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
|
||||
)
|
||||
@@ -248,32 +394,52 @@ 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)
|
||||
# Compute the body-token span inside the prefix by diffing
|
||||
# against the same render with empty developer instructions.
|
||||
# Tokens unique to the with-instructions render are the body
|
||||
# span (``# Instructions\n\n{caller_system_content}``). Marking
|
||||
# those is_content=True so the caller's system text is
|
||||
# recoverable from ``content_token_spans_by_role()["system"]``.
|
||||
# The scaffolding ``# Instructions\n\n`` prefix bleeds into
|
||||
# the body run; consumers reading the body do a substring
|
||||
# check rather than expecting an exact match.
|
||||
prefix_content_mask = self._prefix_content_mask(
|
||||
prefix_tokens, first_system_idx, messages, tools
|
||||
)
|
||||
for tid, is_content in zip(prefix_tokens, prefix_content_mask):
|
||||
tokens.append(tid)
|
||||
indices.append(prefix_origin)
|
||||
sampled.append(False)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── Iterate the rest of the messages ────────────────────────────
|
||||
last_idx = len(messages) - 1
|
||||
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,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
)
|
||||
for hm in self._to_harmony_messages(
|
||||
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 +451,21 @@ 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, is_content=False)
|
||||
emit(self._encode("assistant"), -1, is_sampled=False, is_content=False)
|
||||
emit([self._channel], -1, is_sampled=False, is_content=False)
|
||||
emit(self._encode("analysis"), -1, is_sampled=False, is_content=False)
|
||||
emit([self._message], -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(token_ids=tokens, message_indices=indices)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
@@ -307,7 +480,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 +531,70 @@ class GptOssRenderer:
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False``). The harmony encoder
|
||||
# renders each ``new_messages[i]`` as a single block, so every
|
||||
# token in that block carries index ``i``; the trailing
|
||||
# generation prompt uses ``-1``. ``is_content`` follows the same
|
||||
# rules as :meth:`render`'s ``emit_harmony_message``: header is
|
||||
# scaffold, body bytes are body, terminator scaffold (the bridge
|
||||
# never carries assistant turns, so terminators are always
|
||||
# scaffold on the non-assistant roles the bridge accepts).
|
||||
terminator_ids = {self._end, self._return, self._call}
|
||||
ext: list[int] = []
|
||||
for msg in new_messages:
|
||||
ext_indices: list[int] = []
|
||||
ext_content: list[bool] = []
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
if role not in ("tool", "user", "system", "developer"):
|
||||
return None
|
||||
for hm in self._to_harmony_messages(msg):
|
||||
ext.extend(self._enc.render(hm))
|
||||
ids = self._enc.render(hm)
|
||||
try:
|
||||
msg_marker = ids.index(self._message)
|
||||
except ValueError:
|
||||
# Defensive: treat as scaffolding.
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([i] * len(ids))
|
||||
ext_content.extend([False] * len(ids))
|
||||
continue
|
||||
header = ids[: msg_marker + 1]
|
||||
body = ids[msg_marker + 1 :]
|
||||
ext.extend(header)
|
||||
ext_indices.extend([i] * len(header))
|
||||
ext_content.extend([False] * len(header))
|
||||
if body and body[-1] in terminator_ids:
|
||||
body_content = body[:-1]
|
||||
terminator = body[-1:]
|
||||
else:
|
||||
body_content = body
|
||||
terminator = []
|
||||
ext.extend(body_content)
|
||||
ext_indices.extend([i] * len(body_content))
|
||||
ext_content.extend([True] * len(body_content))
|
||||
if terminator:
|
||||
ext.extend(terminator)
|
||||
ext_indices.extend([i] * len(terminator))
|
||||
ext_content.extend([False] * len(terminator))
|
||||
|
||||
# Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
|
||||
gen_before = len(ext)
|
||||
ext.append(self._start)
|
||||
ext.extend(self._encode("assistant"))
|
||||
ext.append(self._channel)
|
||||
ext.extend(self._encode("analysis"))
|
||||
ext.append(self._message)
|
||||
ext_indices.extend([-1] * (len(ext) - gen_before))
|
||||
ext_content.extend([False] * (len(ext) - gen_before))
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
# ── message conversion ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
+213
-71
@@ -26,31 +26,29 @@ from renderers.base import (
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import KimiK2RendererConfig
|
||||
from renderers.parsing import parse_kimi_k2
|
||||
|
||||
_DEFAULT_SYSTEM = "You are Kimi, an AI assistant created by Moonshot AI."
|
||||
|
||||
|
||||
class KimiK2Renderer:
|
||||
"""Deterministic message → token renderer for Kimi K2 models."""
|
||||
"""Deterministic message → token renderer for Kimi K2 models.
|
||||
|
||||
Kimi K2's chat template doesn't read any thinking-related variable —
|
||||
``content`` renders verbatim with no reasoning branch. The
|
||||
``enable_thinking`` / ``preserve_*`` fields on the config are stored
|
||||
for protocol uniformity with the rest of the renderer family but
|
||||
have no effect on the byte-level output.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: KimiK2RendererConfig | None = None,
|
||||
):
|
||||
# Kimi-K2's chat template doesn't read ``reasoning_content`` for
|
||||
# past assistant turns, so the override flags are no-ops. Stored
|
||||
# for introspection / Protocol parity only.
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or KimiK2RendererConfig()
|
||||
|
||||
self._im_user = self._token_id("<|im_user|>")
|
||||
self._im_assistant = self._token_id("<|im_assistant|>")
|
||||
@@ -118,6 +116,11 @@ class KimiK2Renderer:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
# Preserve the caller's list — ``message_roles`` and per-token
|
||||
# attribution refer to this frame (not the post-normalisation
|
||||
# list that includes auto-injected system / tool_declare).
|
||||
caller_messages = list(messages)
|
||||
|
||||
# Inject tools as tool_declare message + ensure system message.
|
||||
# The Jinja template emits the tools list directly (no
|
||||
# ``{"type":"function","function":...}`` wrapper) using
|
||||
@@ -165,17 +168,34 @@ class KimiK2Renderer:
|
||||
|
||||
token_ids: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
token_ids.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
token_ids.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
emit_ids(self._encode(text), msg_idx)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
# Compute last non-tool-call assistant index to determine thinking preservation
|
||||
last_plain_assistant_idx = -1
|
||||
@@ -203,31 +223,40 @@ class KimiK2Renderer:
|
||||
content = "".join(parts)
|
||||
|
||||
oi = orig_idx(i)
|
||||
# Auto-injected system / tool_declare messages have ``oi == -1``.
|
||||
# Their text isn't from the caller's input, so we treat the
|
||||
# whole emission as scaffold (``is_content=False`` everywhere).
|
||||
# The test contract is that ``msg_idx == -1`` runs are
|
||||
# template-only and ``is_content=False``.
|
||||
body_is_content = oi >= 0
|
||||
|
||||
if role == "system":
|
||||
emit_special(self._im_system, oi)
|
||||
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, is_content=False)
|
||||
emit_text("system", oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
|
||||
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
# Jinja emits a literal newline only after the auto-injected
|
||||
# system's <|im_end|> (see _ensure_system_message's contract).
|
||||
if i == auto_system_idx:
|
||||
emit_text("\n", oi)
|
||||
emit_text("\n", oi, is_sampled=False, is_content=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)
|
||||
# The tool_declare body is the tools JSON — recoverable
|
||||
# from the caller's ``tools`` argument, so we treat it as
|
||||
# scaffold (consistent with Qwen3's tools-header block).
|
||||
emit_special(self._im_system, oi, is_sampled=False, is_content=False)
|
||||
emit_text("tool_declare", oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
|
||||
emit_text(content, oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._im_user, oi)
|
||||
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, is_content=False)
|
||||
emit_text("user", oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
|
||||
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
# Kimi strips reasoning from historical assistant turns and
|
||||
@@ -247,24 +276,36 @@ class KimiK2Renderer:
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
msg, oi, content, emit_special=emit_special, emit_text=emit_text
|
||||
msg,
|
||||
oi,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
|
||||
else:
|
||||
# Unknown role: use system-style formatting
|
||||
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, is_content=False)
|
||||
emit_text(role, oi, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, oi, is_sampled=False, is_content=False)
|
||||
emit_text(content, oi, is_sampled=False, is_content=body_is_content)
|
||||
emit_special(self._im_end, oi, is_sampled=False, is_content=False)
|
||||
|
||||
# Generation prompt
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_assistant, -1)
|
||||
emit_text("assistant", -1)
|
||||
emit_special(self._im_middle, -1)
|
||||
emit_special(self._im_assistant, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(token_ids=token_ids, message_indices=indices)
|
||||
return RenderedTokens(
|
||||
token_ids=token_ids,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in caller_messages],
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
@@ -279,7 +320,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 +365,42 @@ class KimiK2Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
@@ -347,17 +423,21 @@ class KimiK2Renderer:
|
||||
emit_special(self._im_user, i)
|
||||
emit_text("user", i)
|
||||
emit_special(self._im_middle, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
emit_special(self._im_end, i)
|
||||
elif role == "system":
|
||||
emit_special(self._im_system, i)
|
||||
emit_text("system", i)
|
||||
emit_special(self._im_middle, i)
|
||||
emit_text(content, i)
|
||||
emit_text(content, i, is_content=True)
|
||||
emit_special(self._im_end, i)
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
msg, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
@@ -367,7 +447,14 @@ class KimiK2Renderer:
|
||||
emit_text("assistant", -1)
|
||||
emit_special(self._im_middle, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -379,22 +466,36 @@ 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. ``is_content``
|
||||
# is also False here — the role tag isn't part of any message's
|
||||
# body, on any role.
|
||||
emit_special(self._im_assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Kimi K2's Jinja template has no reasoning-content support: the
|
||||
# assistant turn renders its ``content`` verbatim, including any
|
||||
# inline ``<think>...</think>`` tags. The separate
|
||||
# ``reasoning_content`` field is dropped (the template never reads
|
||||
# it). ``is_last_turn`` is unused here for the same reason.
|
||||
# On assistant tokens, ``is_content == sampled_mask`` by construction
|
||||
# — every sampled token is body, every scaffold token isn't.
|
||||
_ = is_last_turn
|
||||
emit_text(content, msg_idx)
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool calls
|
||||
# Tool calls — model-sampled markup carrying caller / model body.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
if tool_calls:
|
||||
emit_special(self._tool_calls_section_begin, msg_idx)
|
||||
emit_special(
|
||||
self._tool_calls_section_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
arguments = func.get("arguments", {})
|
||||
@@ -408,14 +509,37 @@ class KimiK2Renderer:
|
||||
# caller to provide an id in ``functions.{name}:{idx}`` form
|
||||
# (that's where the Kimi parser recovers the function name).
|
||||
tc_id = tc.get("id") or ""
|
||||
emit_special(self._tool_call_begin, msg_idx)
|
||||
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,
|
||||
is_content=True,
|
||||
)
|
||||
emit_text(tc_id, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_argument_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_text(args_str, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_calls_section_end,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
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 (and the
|
||||
# assistant's body).
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -426,12 +550,30 @@ 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. The ``content``
|
||||
# field's body bytes get ``is_content=True``; everything else —
|
||||
# the ``<|im_system|>name<|im_middle|>`` wrap, the ``## Return of
|
||||
# …\n`` header (template-synthesised, not part of the body) —
|
||||
# is scaffold so the SFT mask for tool body never trains the
|
||||
# model to emit them.
|
||||
#
|
||||
# We keep the original kimi_k2 emit boundaries — the header and
|
||||
# the content are encoded separately, which preserves the
|
||||
# template's byte-identity since the original code also emitted
|
||||
# them as separate ``encode`` calls.
|
||||
name = msg.get("name") or "tool"
|
||||
tool_call_id = msg.get("tool_call_id") or ""
|
||||
|
||||
emit_special(self._im_system, msg_idx)
|
||||
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, is_content=False)
|
||||
emit_text(name, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text(
|
||||
f"## Return of {tool_call_id}\n",
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
emit_text(content, msg_idx, is_sampled=False, is_content=True)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+401
-128
@@ -31,13 +31,17 @@ 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.configs import KimiK25RendererConfig
|
||||
from renderers.parsing import parse_kimi_k2_section
|
||||
from renderers.qwen3_vl import (
|
||||
_image_hash,
|
||||
_is_image_part,
|
||||
@@ -210,7 +214,9 @@ class _EnumType(_BaseType):
|
||||
self.enum = schema["enum"]
|
||||
|
||||
def to_typescript_style(self, indent: str = "") -> str:
|
||||
return " | ".join(f'"{e}"' if isinstance(e, str) else str(e) for e in self.enum)
|
||||
return " | ".join(
|
||||
f'"{e}"' if isinstance(e, str) else json.dumps(e) for e in self.enum
|
||||
)
|
||||
|
||||
|
||||
class _AnyOfType(_BaseType):
|
||||
@@ -280,11 +286,7 @@ class _TypedParam:
|
||||
def to_typescript_style(self, indent: str = "") -> str:
|
||||
comments = self.type_.format_docstring(indent)
|
||||
if self.default is not None:
|
||||
default_repr = (
|
||||
json.dumps(self.default, ensure_ascii=False)
|
||||
if not isinstance(self.default, (int, float, bool))
|
||||
else repr(self.default)
|
||||
)
|
||||
default_repr = json.dumps(self.default, ensure_ascii=False)
|
||||
comments += f"{indent}// Default: {default_repr}\n"
|
||||
opt = "?" if self.optional else ""
|
||||
return (
|
||||
@@ -420,12 +422,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 +451,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 +532,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 +547,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,
|
||||
@@ -508,8 +563,13 @@ class KimiK25Renderer:
|
||||
"""Deterministic message → token renderer for Kimi K2.5 models.
|
||||
|
||||
Renders to the same ``<|im_*|>`` format as Kimi K2 but adds:
|
||||
- Generation prompt prefills ``<think>`` (enable_thinking=True, default) or
|
||||
``<think></think>`` (enable_thinking=False) to control thinking mode.
|
||||
- Generation prompt prefills ``<think>`` (thinking=True, default) or
|
||||
``<think></think>`` (thinking=False) to control thinking mode. The
|
||||
template's native kwarg name is ``thinking`` (not the more common
|
||||
``enable_thinking``); we mirror it on
|
||||
:class:`renderers.KimiK25RendererConfig` so
|
||||
``KimiK25RendererConfig(thinking=False)`` produces the same tokens
|
||||
as ``apply_chat_template(..., thinking=False)``.
|
||||
- Image content rendering via ``<|media_begin|>image<|media_content|>...<|media_end|>``.
|
||||
- TypeScript-style tool declarations instead of JSON.
|
||||
|
||||
@@ -519,20 +579,13 @@ class KimiK25Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: KimiK25RendererConfig | None = None,
|
||||
*,
|
||||
processor: Any = None,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
image_cache_max: int = 256,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or KimiK25RendererConfig()
|
||||
|
||||
# Core structural tokens — all must be single special tokens in the vocab
|
||||
self._im_user = self._token_id("<|im_user|>")
|
||||
@@ -573,7 +626,6 @@ class KimiK25Renderer:
|
||||
# for Kimi (we emit a single placeholder regardless), but kept for
|
||||
# consistency / debugging.
|
||||
self._image_cache: dict[str, tuple[Any, int]] = {}
|
||||
self._image_cache_max = image_cache_max
|
||||
|
||||
@property
|
||||
def mm_token_type_id_map(self) -> dict[int, int]:
|
||||
@@ -625,7 +677,7 @@ class KimiK25Renderer:
|
||||
# Patch count via the processor's own calculator (matches the
|
||||
# model's per-patch attention count); kept for debugging.
|
||||
num_patches = int(img_proc.media_tokens_calculator(media_item))
|
||||
if len(self._image_cache) >= self._image_cache_max:
|
||||
if len(self._image_cache) >= self.config.image_cache_max:
|
||||
self._image_cache.pop(next(iter(self._image_cache)))
|
||||
self._image_cache[h] = (out, num_patches)
|
||||
return pil, out, num_patches, h
|
||||
@@ -692,22 +744,45 @@ class KimiK25Renderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
mm_hashes: dict[str, list[str]] = {}
|
||||
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
mm_items: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
emit_ids(self._encode(text), msg_idx)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
def emit_image(part: dict[str, Any], msg_idx: int) -> None:
|
||||
def emit_image(
|
||||
part: dict[str, Any],
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_sampled: bool,
|
||||
is_content: bool,
|
||||
) -> None:
|
||||
"""Emit Kimi K2.5's image wrap and accumulate ``mm_data``.
|
||||
|
||||
Template-equivalent expansion per image:
|
||||
@@ -720,15 +795,32 @@ class KimiK25Renderer:
|
||||
Kimi's chat template after every image — kept here verbatim
|
||||
for byte-parity, regardless of what follows (more images,
|
||||
text, or the ``<|im_end|>`` close).
|
||||
|
||||
``is_content`` attribution: ``<|media_pad|>`` represents
|
||||
caller-provided image data — body. The wrap tokens
|
||||
(``<|media_begin|>``, the literal ``"image"`` prose,
|
||||
``<|media_content|>``, ``<|media_end|>``, the trailing
|
||||
``\\n``) are template-injected scaffold.
|
||||
"""
|
||||
_, out, _num_patches, h = self._process_image(part)
|
||||
emit_special(self._media_begin, msg_idx)
|
||||
emit_text("image", msg_idx)
|
||||
emit_special(self._media_content, msg_idx)
|
||||
emit_special(
|
||||
self._media_begin, msg_idx, is_sampled=is_sampled, is_content=False
|
||||
)
|
||||
emit_text("image", msg_idx, is_sampled=is_sampled, is_content=False)
|
||||
emit_special(
|
||||
self._media_content, msg_idx, is_sampled=is_sampled, is_content=False
|
||||
)
|
||||
offset = len(tokens)
|
||||
emit_special(self._media_pad, msg_idx)
|
||||
emit_special(self._media_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
emit_special(
|
||||
self._media_pad,
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
emit_special(
|
||||
self._media_end, msg_idx, is_sampled=is_sampled, is_content=False
|
||||
)
|
||||
emit_text("\n", msg_idx, is_sampled=is_sampled, is_content=False)
|
||||
mm_hashes.setdefault("image", []).append(h)
|
||||
mm_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=1)
|
||||
@@ -748,28 +840,34 @@ class KimiK25Renderer:
|
||||
# K2.5/K2.6's tokenizer auto-computes ``tools_ts_str`` and threads
|
||||
# it into apply_chat_template, so the template's TS branch always
|
||||
# fires when tools are present. Match that with our own TS encoder.
|
||||
# The tools-TS body is recoverable from the ``tools`` argument, so
|
||||
# we attribute the entire tool_declare emission as scaffold —
|
||||
# consistent with Qwen3's tools-header treatment.
|
||||
if tools:
|
||||
tools_ts = _encode_tools_typescript(tools)
|
||||
emit_special(self._im_system, -1)
|
||||
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, is_content=False)
|
||||
emit_text("tool_declare", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
|
||||
emit_text(tools_ts, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Iterate messages ─────────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
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, is_content=False)
|
||||
elif role == "assistant":
|
||||
emit_special(self._im_assistant, i)
|
||||
emit_special(self._im_assistant, i, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._im_system, i)
|
||||
emit_special(self._im_system, i, is_sampled=False, is_content=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, is_content=False)
|
||||
emit_special(self._im_middle, i, is_sampled=False, is_content=False)
|
||||
|
||||
# Body
|
||||
if role == "assistant":
|
||||
@@ -777,8 +875,8 @@ class KimiK25Renderer:
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant_body(
|
||||
msg,
|
||||
@@ -788,6 +886,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 (and the assistant's body). Kimi K2.5 has no
|
||||
# inter-turn ``\n`` separator (unlike Qwen3), so the
|
||||
# turn-close token is the last sampled token.
|
||||
emit_special(self._im_end, i, is_sampled=True, is_content=True)
|
||||
continue
|
||||
elif role == "tool":
|
||||
self._render_tool_body(
|
||||
msg,
|
||||
@@ -795,9 +900,13 @@ 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. The body is caller-provided, so
|
||||
# ``is_content=True`` over the content emit.
|
||||
self._emit_content(
|
||||
msg.get("content"),
|
||||
i,
|
||||
@@ -805,21 +914,23 @@ class KimiK25Renderer:
|
||||
emit_text,
|
||||
emit_ids,
|
||||
emit_image=emit_image,
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
emit_special(self._im_end, i)
|
||||
emit_special(self._im_end, i, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Generation prompt ────────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_assistant, -1)
|
||||
emit_text("assistant", -1)
|
||||
emit_special(self._im_middle, -1)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._im_assistant, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._im_middle, -1, is_sampled=False, is_content=False)
|
||||
if self.config.thinking:
|
||||
# Prefill open <think> tag to trigger thinking mode
|
||||
emit_text("<think>", -1)
|
||||
emit_text("<think>", -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
# Empty <think></think> to disable thinking
|
||||
emit_text("<think></think>", -1)
|
||||
emit_text("<think></think>", -1, is_sampled=False, is_content=False)
|
||||
|
||||
mm_data: MultiModalData | None = None
|
||||
if mm_hashes or mm_placeholders or mm_items:
|
||||
@@ -832,6 +943,9 @@ class KimiK25Renderer:
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -848,22 +962,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 +1035,77 @@ class KimiK25Renderer:
|
||||
return None
|
||||
|
||||
# Seed combined-token list with prior turn so placeholder offsets
|
||||
# are absolute in the bridged sequence.
|
||||
# are absolute in the bridged sequence. Parallel
|
||||
# ``indices``/``sampled``/``content_mask`` are seeded with
|
||||
# ``-1``/``False``/``False`` for the prior portion — the bridge
|
||||
# has no attribution info for ``previous_ids``. Bridge-added
|
||||
# tokens get proper ``msg_idx`` (relative to ``new_messages``)
|
||||
# and uniformly ``False`` ``sampled``: nothing the bridge emits
|
||||
# was model-sampled. ``is_content`` follows the same rules as in
|
||||
# :meth:`render` so consumers can walk the trajectory and read
|
||||
# each step's own body mask.
|
||||
tokens: list[int] = list(previous_ids)
|
||||
indices: list[int] = [-1] * len(previous_ids)
|
||||
sampled: list[bool] = [False] * len(previous_ids)
|
||||
content_mask: list[bool] = [False] * len(previous_ids)
|
||||
new_hashes: dict[str, list[str]] = {}
|
||||
new_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
new_items: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, _msg_idx: int = -1) -> 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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_image(part: dict[str, Any], _msg_idx: int = -1) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_image(
|
||||
part: dict[str, Any],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
_, out, _num_patches, h = self._process_image(part)
|
||||
emit_special(self._media_begin)
|
||||
emit_text("image")
|
||||
emit_special(self._media_content)
|
||||
emit_special(self._media_begin, msg_idx)
|
||||
emit_text("image", msg_idx)
|
||||
emit_special(self._media_content, msg_idx)
|
||||
offset = len(tokens)
|
||||
emit_special(self._media_pad)
|
||||
emit_special(self._media_end)
|
||||
emit_text("\n")
|
||||
# ``<|media_pad|>`` stands in for caller-provided image data —
|
||||
# mark it as body when the surrounding content is body.
|
||||
emit_special(self._media_pad, msg_idx, is_content=is_content)
|
||||
emit_special(self._media_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
new_hashes.setdefault("image", []).append(h)
|
||||
new_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=1)
|
||||
@@ -956,6 +1139,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 +1149,8 @@ class KimiK25Renderer:
|
||||
emit_text,
|
||||
emit_ids,
|
||||
emit_image=emit_image,
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
emit_special(self._im_end, i)
|
||||
@@ -973,7 +1159,7 @@ class KimiK25Renderer:
|
||||
emit_special(self._im_assistant, -1)
|
||||
emit_text("assistant", -1)
|
||||
emit_special(self._im_middle, -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.thinking:
|
||||
emit_text("<think>", -1)
|
||||
else:
|
||||
emit_text("<think></think>", -1)
|
||||
@@ -1001,8 +1187,15 @@ class KimiK25Renderer:
|
||||
for modality, vals in new_items.items():
|
||||
merged_items.setdefault(modality, []).extend(vals)
|
||||
|
||||
bridge_roles = [m.get("role") or "" for m in new_messages]
|
||||
if not (merged_hashes or merged_placeholders or merged_items):
|
||||
return RenderedTokens(token_ids=tokens)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
)
|
||||
|
||||
mm_data = MultiModalData(
|
||||
mm_hashes=merged_hashes,
|
||||
@@ -1011,7 +1204,10 @@ class KimiK25Renderer:
|
||||
)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=[-1] * len(tokens),
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -1028,6 +1224,8 @@ class KimiK25Renderer:
|
||||
emit_ids,
|
||||
*,
|
||||
emit_image=None,
|
||||
is_sampled: bool,
|
||||
is_content: bool = True,
|
||||
) -> None:
|
||||
"""Emit message content, handling strings, multipart lists, and (when
|
||||
``emit_image`` is supplied) image parts.
|
||||
@@ -1042,11 +1240,15 @@ class KimiK25Renderer:
|
||||
``bridge_to_next_turn``), so consecutive images naturally
|
||||
produce the template's ``...<|media_end|>\\n<|media_begin|>...``
|
||||
pattern without an inter-image separator here.
|
||||
|
||||
``is_content`` propagates to text emits and to the
|
||||
``<|media_pad|>`` body token of each image; the surrounding
|
||||
media wrap tokens are always scaffold (handled by ``emit_image``).
|
||||
"""
|
||||
if content is None:
|
||||
return
|
||||
if isinstance(content, str):
|
||||
emit_text(content, msg_idx)
|
||||
emit_text(content, msg_idx, is_sampled=is_sampled, is_content=is_content)
|
||||
return
|
||||
if isinstance(content, list):
|
||||
for part in content:
|
||||
@@ -1059,19 +1261,31 @@ 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, is_content=is_content
|
||||
)
|
||||
continue
|
||||
if is_video:
|
||||
raise NotImplementedError(
|
||||
"Video parts are not yet supported by KimiK25Renderer."
|
||||
)
|
||||
if ptype == "text":
|
||||
emit_text(part.get("text", ""), msg_idx)
|
||||
emit_text(
|
||||
part.get("text", ""),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
elif ptype == "thinking":
|
||||
# Thinking parts in non-assistant roles are rendered as text
|
||||
thinking = part.get("thinking", "")
|
||||
if thinking:
|
||||
emit_text(f"<think>{thinking}</think>", msg_idx)
|
||||
emit_text(
|
||||
f"<think>{thinking}</think>",
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
# Other part types are silently skipped
|
||||
|
||||
def _render_assistant_body(
|
||||
@@ -1129,17 +1343,31 @@ 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). On assistant tokens ``is_content == sampled_mask`` by
|
||||
# construction.
|
||||
if is_suffix or (preserve_thinking and reasoning_content):
|
||||
emit_text(f"<think>{reasoning_content}</think>", msg_idx)
|
||||
emit_text(
|
||||
f"<think>{reasoning_content}</think>",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
else:
|
||||
emit_text("<think></think>", msg_idx)
|
||||
emit_text(text_content, msg_idx)
|
||||
emit_text("<think></think>", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(text_content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
if tool_calls:
|
||||
emit_special(self._tool_calls_section_begin, msg_idx)
|
||||
emit_special(
|
||||
self._tool_calls_section_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
arguments = func.get("arguments", {})
|
||||
@@ -1153,12 +1381,32 @@ class KimiK25Renderer:
|
||||
# ``functions.{name}:{idx}`` form (Kimi's parser recovers
|
||||
# the function name from that field).
|
||||
tool_id = tc.get("id") or ""
|
||||
emit_special(self._tool_call_begin, msg_idx)
|
||||
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,
|
||||
is_content=True,
|
||||
)
|
||||
emit_text(tool_id, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_argument_begin,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_text(args_str, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_calls_section_end,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
def _render_tool_body(
|
||||
self,
|
||||
@@ -1168,6 +1416,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 +1424,36 @@ 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. The ``## Return
|
||||
# of …\n`` header is template-synthesised scaffold; the
|
||||
# ``content`` body bytes get ``is_content=True``.
|
||||
tool_call_id = msg.get("tool_call_id") or ""
|
||||
emit_text(f"## Return of {tool_call_id}\n", msg_idx)
|
||||
emit_text(
|
||||
f"## Return of {tool_call_id}\n",
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
content = msg.get("content")
|
||||
if content is not None:
|
||||
self._emit_content(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,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
def _normalize_response_tokens(self, response: list[int]) -> list[int]:
|
||||
"""Restore the synthetic ``<think>`` prefill if the sampler stripped it.
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
"""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,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
)
|
||||
from renderers.configs import LagunaXS2RendererConfig
|
||||
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,
|
||||
config: LagunaXS2RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self.config = config or LagunaXS2RendererConfig()
|
||||
|
||||
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] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
emit_special(self._eos, -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── System header (absorbs messages[0] if it's a system message) ──
|
||||
system_content = _DEFAULT_SYSTEM_MESSAGE
|
||||
system_msg_idx = -1
|
||||
caller_has_system = bool(messages and messages[0].get("role") == "system")
|
||||
if caller_has_system:
|
||||
system_content = self._visible_text(messages[0].get("content"))
|
||||
system_msg_idx = 0
|
||||
|
||||
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,
|
||||
is_content=False,
|
||||
)
|
||||
if has_sys_content:
|
||||
# If the caller provided system content, it's body bytes;
|
||||
# otherwise this is the default system prompt (scaffold).
|
||||
sys_is_content = caller_has_system
|
||||
emit_text(
|
||||
system_content.rstrip(),
|
||||
system_msg_idx,
|
||||
is_sampled=False,
|
||||
is_content=sys_is_content,
|
||||
)
|
||||
if tools:
|
||||
tool_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
|
||||
tool_text += (
|
||||
_TOOLS_FOOTER_THINKING
|
||||
if self.config.enable_thinking
|
||||
else _TOOLS_FOOTER_NO_THINKING
|
||||
)
|
||||
emit_text(tool_text, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n</system>\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Per-message loop ──────────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
match msg["role"]:
|
||||
case "system":
|
||||
# Already consumed in the header block.
|
||||
if i == 0:
|
||||
continue
|
||||
# Body = caller's content; the ``<system>...</system>``
|
||||
# wrap and surrounding ``\n``s are scaffold.
|
||||
sys_segs: list[tuple[str, bool]] = [("<system>\n", False)]
|
||||
if content:
|
||||
sys_segs.append((content, True))
|
||||
sys_segs.append(("\n</system>\n", False))
|
||||
emit_text_segments(sys_segs, i, is_sampled=False)
|
||||
case "user":
|
||||
user_segs: list[tuple[str, bool]] = [("<user>\n", False)]
|
||||
if content:
|
||||
user_segs.append((content, True))
|
||||
user_segs.append(("\n</user>\n", False))
|
||||
emit_text_segments(user_segs, i, is_sampled=False)
|
||||
case "assistant":
|
||||
self._render_assistant(
|
||||
msg,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
case "tool":
|
||||
tool_segs: list[tuple[str, bool]] = [("<tool_response>\n", False)]
|
||||
if content:
|
||||
tool_segs.append((content, True))
|
||||
tool_segs.append(("\n</tool_response>\n", False))
|
||||
emit_text_segments(tool_segs, i, is_sampled=False)
|
||||
|
||||
# ── Generation prompt ─────────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
)
|
||||
|
||||
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] = []
|
||||
ext_content: 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). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask.
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
if role == "user":
|
||||
segs: list[tuple[str, bool]] = [("<user>\n", False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
segs.append(("\n</user>\n", False))
|
||||
emit_text_segments(segs, i)
|
||||
elif role == "system":
|
||||
segs = [("<system>\n", False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
segs.append(("\n</system>\n", False))
|
||||
emit_text_segments(segs, i)
|
||||
elif role == "tool":
|
||||
segs = [("<tool_response>\n", False)]
|
||||
if content:
|
||||
segs.append((content, True))
|
||||
segs.append(("\n</tool_response>\n", False))
|
||||
emit_text_segments(segs, i)
|
||||
else:
|
||||
return None
|
||||
|
||||
emit_special(self._assistant, -1)
|
||||
emit_text("\n", -1)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
else:
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
msg: Message,
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
if self.config.render_assistant_messages_raw:
|
||||
self._render_assistant_raw(
|
||||
msg_idx,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
)
|
||||
return
|
||||
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
reasoning_content = msg["reasoning_content"]
|
||||
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. ``is_content`` is also
|
||||
# False on the role tag. On assistant the invariant
|
||||
# ``is_content == sampled_mask`` holds.
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if reasoning_content:
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n" + reasoning_content.strip() + "\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Combined newline-after-</think> with optional content. Bundling
|
||||
# preserves BPE merges across the boundary.
|
||||
post_think_text = "\n"
|
||||
if content.strip():
|
||||
post_think_text += content.strip() + "\n"
|
||||
emit_text(post_think_text, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
inner = name + "\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, is_content=True)
|
||||
emit_special(self._tool_call_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# ``</assistant>`` is the model's stop signal (alongside
|
||||
# ``〈|EOS|〉``) — it samples this to end its turn, so it's part of
|
||||
# the sampled stream. The trailing ``\n`` is template-appended
|
||||
# between turns and never sampled.
|
||||
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
def _render_assistant_raw(
|
||||
self,
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
) -> None:
|
||||
"""Passthrough assistant rendering matching the Jinja template's
|
||||
``render_assistant_messages_raw`` branch.
|
||||
|
||||
Three pieces, each conditional on the content's own bytes:
|
||||
|
||||
- Open the assistant turn (``<assistant>\\n``) — always.
|
||||
- Prepend the gen-prompt prefix (``<think>`` if
|
||||
``enable_thinking``, else ``</think>``) only when ``content``
|
||||
doesn't already start with it. This lets callers ship content
|
||||
that already includes the prefix (e.g. raw rollouts) without
|
||||
duplicating it.
|
||||
- Emit ``content`` verbatim. ``</think>`` and ``</assistant>``
|
||||
land inside the content as added-vocab specials via the
|
||||
tokenizer's default ``split_special_tokens=False`` behaviour,
|
||||
matching what ``apply_chat_template`` does when it tokenises
|
||||
the rendered string.
|
||||
- Append ``\\n</assistant>`` only when ``content`` doesn't end
|
||||
with ``</assistant>`` (or ``</assistant>\\n``), then always
|
||||
emit the inter-turn ``\\n``.
|
||||
|
||||
Tool calls are deliberately ignored in raw mode — the template
|
||||
also ignores ``message.tool_calls`` here. Callers shipping raw
|
||||
content are expected to embed any tool-call payload in the
|
||||
content string themselves.
|
||||
"""
|
||||
emit_special(self._assistant, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if self.config.enable_thinking:
|
||||
if not content.startswith("<think>"):
|
||||
emit_special(self._think, msg_idx, is_sampled=False, is_content=False)
|
||||
else:
|
||||
if not content.startswith("</think>"):
|
||||
emit_special(
|
||||
self._think_end, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
if not (content.endswith("</assistant>\n") or content.endswith("</assistant>")):
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._assistant_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
+305
-68
@@ -21,16 +21,14 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import MiniMaxM2RendererConfig
|
||||
from renderers.parsing import parse_minimax
|
||||
|
||||
_DEFAULT_SYSTEM = (
|
||||
"You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax."
|
||||
)
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
"\n\n# Tools\n"
|
||||
"You may call one or more tools to assist with the user query.\n"
|
||||
@@ -58,17 +56,10 @@ class MiniMaxM2Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
default_system: str = _DEFAULT_SYSTEM,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: MiniMaxM2RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._default_system = default_system
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or MiniMaxM2RendererConfig()
|
||||
|
||||
self._bos = self._token_id("]~!b[")
|
||||
self._role = self._token_id("]~b]")
|
||||
@@ -118,15 +109,70 @@ class MiniMaxM2Renderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_token_overlap_body(
|
||||
full_text: str,
|
||||
body_start: int,
|
||||
body_end: int,
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_sampled: bool,
|
||||
) -> None:
|
||||
"""Tokenize ``full_text`` and mark tokens that overlap the body
|
||||
char span as ``is_content=True``.
|
||||
|
||||
Differs from :func:`attribute_text_segments` only in the
|
||||
boundary-token rule: a token straddling scaffold→body gets
|
||||
``True`` if any of its bytes are body bytes (overlap rule),
|
||||
rather than being attributed to whichever segment its first
|
||||
char belongs to. The body's first byte is preserved even when
|
||||
BPE merges it with the wrap's trailing byte (``>The`` →
|
||||
single token).
|
||||
"""
|
||||
from renderers.base import _get_offset_tokenizer
|
||||
|
||||
offset_tok = _get_offset_tokenizer(self._tokenizer)
|
||||
encoding = offset_tok(
|
||||
full_text, add_special_tokens=False, return_offsets_mapping=True
|
||||
)
|
||||
for tok_id, (start, end) in zip(
|
||||
encoding["input_ids"], encoding["offset_mapping"]
|
||||
):
|
||||
overlaps = start < body_end and end > body_start
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(overlaps)
|
||||
|
||||
# ── Extract system message ──────────────────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
@@ -134,27 +180,38 @@ class MiniMaxM2Renderer:
|
||||
conversation: list[Message] = messages[1:] if first_is_system else messages
|
||||
|
||||
# ── System block (always present) ───────────────────────────
|
||||
emit_special(self._bos, sys_idx)
|
||||
emit_special(self._role, sys_idx)
|
||||
emit_special(self._bos, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_special(self._role, sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
sys_content = (
|
||||
self._visible_text(messages[0].get("content")) if first_is_system else ""
|
||||
)
|
||||
system_text = "system\n" + (sys_content or self._default_system)
|
||||
# Body = caller's system content (if any). Default system message
|
||||
# is template-injected scaffold; tools header / per-tool JSON /
|
||||
# footer / instructions are scaffold too (the tools dict is
|
||||
# recoverable from the ``tools`` arg).
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
sys_segments.append((sys_content, True))
|
||||
else:
|
||||
sys_segments.append((self.config.model_identity, False))
|
||||
|
||||
if tools:
|
||||
system_text += _TOOLS_HEADER
|
||||
sys_segments.append((_TOOLS_HEADER, False))
|
||||
for tool in tools:
|
||||
func = tool.get("function", tool)
|
||||
system_text += (
|
||||
"<tool>" + json.dumps(func, ensure_ascii=False) + "</tool>\n"
|
||||
sys_segments.append(
|
||||
(
|
||||
"<tool>" + json.dumps(func, ensure_ascii=False) + "</tool>\n",
|
||||
False,
|
||||
)
|
||||
)
|
||||
system_text += _TOOLS_FOOTER_PREFIX
|
||||
system_text += _TOOLS_INSTRUCTIONS
|
||||
sys_segments.append((_TOOLS_FOOTER_PREFIX, False))
|
||||
sys_segments.append((_TOOLS_INSTRUCTIONS, False))
|
||||
|
||||
emit_text(system_text, sys_idx)
|
||||
emit_special(self._eos, sys_idx)
|
||||
emit_text("\n", sys_idx)
|
||||
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._eos, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ── Compute last_user_index (relative to conversation) ──────
|
||||
last_ui = -1
|
||||
@@ -169,17 +226,21 @@ 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, is_content=False)
|
||||
user_content = self._visible_text(msg.get("content"))
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if user_content:
|
||||
user_segments.append((user_content, True))
|
||||
emit_text_segments(user_segments, orig_idx, is_sampled=False)
|
||||
emit_special(self._eos, orig_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
orig_idx,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
@@ -189,6 +250,7 @@ class MiniMaxM2Renderer:
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
@@ -199,16 +261,24 @@ class MiniMaxM2Renderer:
|
||||
msg,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
emit_token_overlap_body=emit_token_overlap_body,
|
||||
)
|
||||
|
||||
# ── Generation prompt ───────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._role, -1)
|
||||
emit_text("ai\n", -1)
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
emit_special(self._role, -1, is_sampled=False, is_content=False)
|
||||
emit_text("ai\n", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(token_ids=tokens, message_indices=indices)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
@@ -223,7 +293,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 +307,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 +338,77 @@ class MiniMaxM2Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask.
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_token_overlap_body(
|
||||
full_text: str,
|
||||
body_start: int,
|
||||
body_end: int,
|
||||
msg_idx: int,
|
||||
*,
|
||||
is_sampled: bool,
|
||||
) -> None:
|
||||
from renderers.base import _get_offset_tokenizer
|
||||
|
||||
offset_tok = _get_offset_tokenizer(self._tokenizer)
|
||||
encoding = offset_tok(
|
||||
full_text, add_special_tokens=False, return_offsets_mapping=True
|
||||
)
|
||||
for tok_id, (start, end) in zip(
|
||||
encoding["input_ids"], encoding["offset_mapping"]
|
||||
):
|
||||
overlaps = start < body_end and end > body_start
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(overlaps)
|
||||
|
||||
# Trailing ``\n`` after the ``[e~[`` turn close — see ``render()``.
|
||||
emit_text("\n", -1)
|
||||
@@ -277,12 +418,18 @@ class MiniMaxM2Renderer:
|
||||
content = self._visible_text(msg.get("content"))
|
||||
if role == "user":
|
||||
emit_special(self._role, i)
|
||||
emit_text("user\n" + content, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i)
|
||||
emit_special(self._eos, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "system":
|
||||
emit_special(self._role, i)
|
||||
emit_text("system\n" + content, i)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if content:
|
||||
sys_segments.append((content, True))
|
||||
emit_text_segments(sys_segments, i)
|
||||
emit_special(self._eos, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "tool":
|
||||
@@ -293,6 +440,8 @@ class MiniMaxM2Renderer:
|
||||
msg,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
emit_token_overlap_body=emit_token_overlap_body,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
@@ -303,7 +452,14 @@ class MiniMaxM2Renderer:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -315,6 +471,7 @@ class MiniMaxM2Renderer:
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
):
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
@@ -329,26 +486,62 @@ 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. ``is_content`` is also
|
||||
# False here — the role tag isn't part of any message's body.
|
||||
emit_special(self._role, orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build the 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). For assistant messages the invariant
|
||||
# ``is_content == sampled_mask`` holds — every sampled token is
|
||||
# body, every scaffold token isn't.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
emit_thinking = reasoning_content and (
|
||||
conv_idx > last_user_index or preserve_thinking
|
||||
)
|
||||
|
||||
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, is_content=False)
|
||||
emit_special(self._think, orig_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n" + reasoning_content + "\n",
|
||||
orig_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._think_end, orig_idx, is_sampled=True, is_content=True)
|
||||
# \n\n + content must be contiguous for BPE
|
||||
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, is_content=False)
|
||||
else:
|
||||
emit_text("ai\n", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if tool_calls:
|
||||
# \n before <minimax:tool_call> must be contiguous with preceding text
|
||||
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, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_tok, orig_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
invoke_block = "\n"
|
||||
for tc in tool_calls:
|
||||
@@ -380,13 +573,18 @@ 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, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end_tok, orig_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
elif body:
|
||||
emit_text(body, orig_idx, is_sampled=True, is_content=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, is_content=True)
|
||||
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -397,7 +595,15 @@ class MiniMaxM2Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
emit_token_overlap_body=None,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# body bytes get ``is_content=True``; the surrounding ``<response>``
|
||||
# wrap, role tag and separators are scaffold so an SFT mask over
|
||||
# tool body never trains the model to emit those.
|
||||
prev_is_tool = conv_idx > 0 and conversation[conv_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
conv_idx + 1 < len(conversation)
|
||||
@@ -405,8 +611,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, is_content=False)
|
||||
emit_text("tool", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
content = self._visible_text(msg.get("content"))
|
||||
# Leading ``\n`` before ``<response>`` only on the first of a
|
||||
@@ -415,8 +621,39 @@ class MiniMaxM2Renderer:
|
||||
# through a single emit_text call instead of splitting the merge.
|
||||
prefix = "" if prev_is_tool else "\n"
|
||||
suffix = "\n" if next_is_tool else ""
|
||||
emit_text(prefix + "<response>" + content + "</response>" + suffix, orig_idx)
|
||||
|
||||
# ``<response>`` is plain text with no separator between the
|
||||
# closing ``>`` and ``content``'s first byte, so BPE can merge
|
||||
# them into a single token (e.g., ``>The``). The shared
|
||||
# ``attribute_text_segments`` helper picks the segment of a
|
||||
# boundary-spanning token by its *first* char (here scaffold),
|
||||
# which would drop the body's leading letter out of the body
|
||||
# run. We instead use an "intersects body" rule: any token whose
|
||||
# ``[start, end)`` char range overlaps the body span gets
|
||||
# ``is_content=True``. A few scaffold bytes (the leading ``>``
|
||||
# or trailing ``<``) bleed into the body run, but body bytes are
|
||||
# recoverable as a substring of the decoded body span.
|
||||
body_text = prefix + "<response>" + content + "</response>" + suffix
|
||||
body_start = len(prefix) + len("<response>")
|
||||
body_end = body_start + len(content)
|
||||
if content and emit_token_overlap_body is not None:
|
||||
emit_token_overlap_body(
|
||||
body_text, body_start, body_end, orig_idx, is_sampled=False
|
||||
)
|
||||
else:
|
||||
# Empty body or no overlap-aware emitter available — fall back
|
||||
# to the standard segments path.
|
||||
tool_segments: list[tuple[str, bool]] = []
|
||||
if prefix:
|
||||
tool_segments.append((prefix, False))
|
||||
tool_segments.append(("<response>", False))
|
||||
if content:
|
||||
tool_segments.append((content, True))
|
||||
tool_segments.append(("</response>", False))
|
||||
if suffix:
|
||||
tool_segments.append((suffix, False))
|
||||
emit_text_segments(tool_segments, orig_idx, is_sampled=False)
|
||||
|
||||
if not next_is_tool:
|
||||
emit_special(self._eos, orig_idx)
|
||||
emit_text("\n", orig_idx)
|
||||
emit_special(self._eos, orig_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+231
-78
@@ -24,10 +24,12 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Nemotron3RendererConfig
|
||||
from renderers.parsing import parse_qwen35
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -78,17 +80,10 @@ class Nemotron3Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: Nemotron3RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or Nemotron3RendererConfig()
|
||||
|
||||
# Look up special token IDs from the tokenizer (not hardcoded).
|
||||
# <|endoftext|> is optional: Nemotron-3 Nano / Super tokenizers ship
|
||||
@@ -240,17 +235,45 @@ class Nemotron3Renderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
emit_ids(self._encode(text), msg_idx)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── 1. System message + optional tools ──────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
@@ -259,8 +282,7 @@ class Nemotron3Renderer:
|
||||
# Nemotron 3: system prompt BEFORE tools block
|
||||
sys_idx = orig_idx(0) if first_is_system else -1
|
||||
|
||||
emit_special(self._im_start, sys_idx)
|
||||
emit_text("system\n", sys_idx)
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build system content: user's system text first, then tools
|
||||
if first_is_system:
|
||||
@@ -279,22 +301,27 @@ class Nemotron3Renderer:
|
||||
+ _TOOLS_INSTRUCTIONS
|
||||
)
|
||||
|
||||
# Body = caller's system text only; tools block (header, per-
|
||||
# tool XML, footer, instructions) is scaffold.
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
full_sys = sys_content + "\n\n" + tools_block
|
||||
else:
|
||||
full_sys = tools_block
|
||||
|
||||
emit_text(full_sys, sys_idx)
|
||||
emit_special(self._im_end, sys_idx)
|
||||
emit_text("\n", sys_idx)
|
||||
sys_segments.append((sys_content, True))
|
||||
sys_segments.append(("\n\n", False))
|
||||
sys_segments.append((tools_block, False))
|
||||
emit_text_segments(sys_segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
elif first_is_system:
|
||||
sys_idx = orig_idx(0)
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
emit_special(self._im_start, sys_idx)
|
||||
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, is_content=False)
|
||||
sys_segments2: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
sys_segments2.append((sys_content, True))
|
||||
emit_text_segments(sys_segments2, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Track the most-recent plain (non-tool-call) assistant so we can
|
||||
# preserve its reasoning while stripping reasoning from earlier
|
||||
@@ -319,18 +346,25 @@ 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, is_content=False
|
||||
)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, msg_orig_idx, is_sampled=False)
|
||||
emit_special(
|
||||
self._im_end, msg_orig_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
emit_text("\n", msg_orig_idx, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
is_last_turn = i >= last_plain_assistant_idx
|
||||
preserve_thinking = msg_orig_idx >= 0 and should_preserve_past_thinking(
|
||||
original_messages,
|
||||
msg_orig_idx,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
@@ -341,6 +375,7 @@ class Nemotron3Renderer:
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_ids=emit_ids,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
@@ -352,6 +387,7 @@ class Nemotron3Renderer:
|
||||
auto_system_injected=auto_system_injected,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
else:
|
||||
@@ -359,17 +395,23 @@ class Nemotron3Renderer:
|
||||
|
||||
# ── 3. Generation prompt ────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
# Disable-thinking suffix: <think></think> with no trailing newlines
|
||||
emit_special(self._think, -1)
|
||||
emit_special(self._think_end, -1)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
|
||||
return RenderedTokens(token_ids=tokens, message_indices=indices)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in original_messages],
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
@@ -384,7 +426,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 +479,54 @@ class Nemotron3Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask.
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
emit_text("\n", -1)
|
||||
|
||||
@@ -446,12 +535,18 @@ class Nemotron3Renderer:
|
||||
content = self._render_content(msg.get("content")).strip()
|
||||
if role == "user":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("user\n" + content, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "system":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("system\n" + content, i)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if content:
|
||||
sys_segments.append((content, True))
|
||||
emit_text_segments(sys_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "tool":
|
||||
@@ -463,6 +558,7 @@ class Nemotron3Renderer:
|
||||
auto_system_injected=False,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
@@ -470,14 +566,21 @@ class Nemotron3Renderer:
|
||||
# Generation prompt.
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
else:
|
||||
emit_special(self._think, -1)
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Assistant message rendering
|
||||
@@ -494,6 +597,7 @@ class Nemotron3Renderer:
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_ids,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Extract reasoning_content
|
||||
reasoning_content = ""
|
||||
@@ -510,8 +614,14 @@ 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. On assistant the
|
||||
# invariant ``is_content == sampled_mask`` holds.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Nemotron 3 keeps reasoning on the most-recent plain assistant but
|
||||
# strips it from historical turns, which collapse to an empty
|
||||
@@ -525,36 +635,65 @@ class Nemotron3Renderer:
|
||||
# <tool_call>, whether the content is empty or not.
|
||||
content_suffix = "\n" if tool_calls else ""
|
||||
|
||||
if reasoning_content and (is_last_turn or preserve_thinking):
|
||||
emit_special(self._think, msg_idx)
|
||||
emit_text("\n" + reasoning_content + "\n", msg_idx)
|
||||
emit_special(self._think_end, msg_idx)
|
||||
if reasoning_content and (
|
||||
is_last_turn
|
||||
or preserve_thinking
|
||||
or not self.config.truncate_history_thinking
|
||||
):
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n" + reasoning_content + "\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
# Single \n separator (not \n\n like Qwen3.5)
|
||||
emit_text("\n" + content + content_suffix, msg_idx)
|
||||
emit_text(
|
||||
"\n" + content + content_suffix,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
elif reasoning_content:
|
||||
# Historical assistant whose reasoning got stripped — template
|
||||
# keeps a single \n between the collapsed <think></think> and
|
||||
# the content as a marker that reasoning existed.
|
||||
emit_special(self._think, msg_idx)
|
||||
emit_special(self._think_end, msg_idx)
|
||||
emit_text("\n" + content + content_suffix, msg_idx)
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
"\n" + content + content_suffix,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
else:
|
||||
# No reasoning ever — <think></think> glued directly to content.
|
||||
emit_special(self._think, msg_idx)
|
||||
emit_special(self._think_end, msg_idx)
|
||||
emit_text(content + content_suffix, msg_idx)
|
||||
emit_special(self._think, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
content + content_suffix,
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
# Tool calls (leading \n was glued to the content above; each
|
||||
# iteration's trailing \n after </tool_call> handles the
|
||||
# separator to the next block).
|
||||
if tool_calls:
|
||||
for tc_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, is_content=True)
|
||||
emit_text(
|
||||
"\n<function=" + name + ">\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
# Render arguments
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
@@ -577,15 +716,22 @@ class Nemotron3Renderer:
|
||||
+ value_str
|
||||
+ "\n</parameter>\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
emit_text("</function>\n", msg_idx)
|
||||
emit_special(self._tool_call_end, msg_idx)
|
||||
emit_text("</function>\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
# Trailing \n after </tool_call> (Nemotron 3 specific)
|
||||
emit_text("\n", msg_idx)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=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, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Tool message rendering
|
||||
@@ -601,8 +747,13 @@ class Nemotron3Renderer:
|
||||
auto_system_injected: bool,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> 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. The ``content``
|
||||
# body bytes get ``is_content=True``; the surrounding wrap is
|
||||
# scaffold.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
@@ -610,17 +761,19 @@ 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, is_content=False)
|
||||
emit_text("user\n", oi, is_sampled=False, is_content=False)
|
||||
# else: the previous tool's trailing \n already provides the
|
||||
# separator into this block.
|
||||
|
||||
emit_special(self._tool_response, oi)
|
||||
emit_text("\n" + content + "\n", oi)
|
||||
emit_special(self._tool_response_end, oi)
|
||||
emit_special(self._tool_response, oi, is_sampled=False, is_content=False)
|
||||
emit_text_segments(
|
||||
[("\n", False), (content, True), ("\n", False)], oi, is_sampled=False
|
||||
)
|
||||
emit_special(self._tool_response_end, oi, is_sampled=False, is_content=False)
|
||||
# Nemotron 3: trailing \n after </tool_response>
|
||||
emit_text("\n", oi)
|
||||
emit_text("\n", oi, is_sampled=False, is_content=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, is_content=False)
|
||||
emit_text("\n", oi, is_sampled=False, is_content=False)
|
||||
|
||||
+168
-52
@@ -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
File diff suppressed because it is too large
Load Diff
+234
-75
@@ -18,10 +18,12 @@ from renderers.base import (
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen3RendererConfig
|
||||
from renderers.parsing import parse_qwen3
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
@@ -47,17 +49,10 @@ class Qwen3Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = True,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
config: Qwen3RendererConfig | None = None,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or Qwen3RendererConfig()
|
||||
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
self._im_end = self._token_id("<|im_end|>")
|
||||
@@ -107,39 +102,77 @@ class Qwen3Renderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
emit_ids(self._encode(text), msg_idx)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated segments as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment.
|
||||
|
||||
Lets call sites express "this wrap + this body, joined the
|
||||
same way as the chat template, but attributed separately"
|
||||
without splitting the encode call (which could shift BPE
|
||||
merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
# ── 1. System + tools ───────────────────────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
|
||||
if tools:
|
||||
sys_idx = 0 if first_is_system else -1
|
||||
emit_special(self._im_start, sys_idx)
|
||||
tool_text = "system\n"
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
# Body = system content (if any). Everything else in this
|
||||
# block — role tag, tools header / footer, the JSON tool
|
||||
# specs — is scaffold. The tools dict is recoverable from
|
||||
# the ``tools`` argument; don't re-attribute its embedded
|
||||
# JSON as message body.
|
||||
segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if first_is_system:
|
||||
tool_text += (messages[0].get("content") or "") + "\n\n"
|
||||
tool_text += _TOOLS_HEADER
|
||||
sys_content = messages[0].get("content") or ""
|
||||
if sys_content:
|
||||
segments.append((sys_content, True))
|
||||
segments.append(("\n\n", False))
|
||||
segments.append((_TOOLS_HEADER, False))
|
||||
for tool in tools:
|
||||
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
|
||||
tool_text += _TOOLS_FOOTER
|
||||
emit_text(tool_text, sys_idx)
|
||||
emit_special(self._im_end, sys_idx)
|
||||
emit_text("\n", sys_idx)
|
||||
segments.append(("\n" + json.dumps(tool, ensure_ascii=False), False))
|
||||
segments.append((_TOOLS_FOOTER, False))
|
||||
emit_text_segments(segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
elif first_is_system:
|
||||
emit_special(self._im_start, 0)
|
||||
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, is_content=False)
|
||||
sys_content = messages[0].get("content") or ""
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
sys_segments.append((sys_content, True))
|
||||
emit_text_segments(sys_segments, 0, is_sampled=False)
|
||||
emit_special(self._im_end, 0, is_sampled=False, is_content=False)
|
||||
emit_text("\n", 0, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Compute last_query_index ─────────────────────────────
|
||||
last_qi = self._last_query_index(messages)
|
||||
@@ -153,23 +186,29 @@ 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, is_content=False)
|
||||
msg_segments: list[tuple[str, bool]] = [(role + "\n", False)]
|
||||
if content:
|
||||
msg_segments.append((content, True))
|
||||
emit_text_segments(msg_segments, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False, is_content=False)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._im_start, i)
|
||||
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, is_content=False)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False, is_content=False)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
@@ -180,21 +219,35 @@ class Qwen3Renderer:
|
||||
preserve_thinking=preserve_thinking,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
messages, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
# ── 4. Generation prompt ────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if not self._enable_thinking:
|
||||
emit_text("<think>\n\n</think>\n\n", -1)
|
||||
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
|
||||
if not self.config.enable_thinking:
|
||||
emit_text(
|
||||
"<think>\n\n</think>\n\n", -1, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
return RenderedTokens(token_ids=tokens, message_indices=indices)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
@@ -209,7 +262,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 +304,56 @@ class Qwen3Renderer:
|
||||
return None
|
||||
|
||||
ext: list[int] = []
|
||||
ext_indices: list[int] = []
|
||||
ext_sampled: list[bool] = []
|
||||
ext_content: list[bool] = []
|
||||
|
||||
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
def emit_special(
|
||||
token_id: int,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ext.append(token_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
def emit_text(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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
ext.extend(ids)
|
||||
ext_indices.extend([msg_idx] * len(ids))
|
||||
ext_sampled.extend([is_sampled] * len(ids))
|
||||
ext_content.extend([is_content] * len(ids))
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
ext.append(tok_id)
|
||||
ext_indices.append(msg_idx)
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
# Trailing ``\n`` after the turn-close token. ``render()`` emits this
|
||||
# as part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
|
||||
@@ -263,12 +365,18 @@ class Qwen3Renderer:
|
||||
content = msg.get("content") if isinstance(msg.get("content"), str) else ""
|
||||
if role == "user":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("user\n" + content, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "system":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("system\n" + content, i)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if content:
|
||||
sys_segments.append((content, True))
|
||||
emit_text_segments(sys_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "tool":
|
||||
@@ -278,16 +386,24 @@ class Qwen3Renderer:
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if not self._enable_thinking:
|
||||
if not self.config.enable_thinking:
|
||||
emit_text("<think>\n\n</think>\n\n", -1)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
total_len = len(previous_ids) + len(ext)
|
||||
return RenderedTokens(
|
||||
token_ids=previous_ids + ext,
|
||||
message_indices=[-1] * len(previous_ids) + ext_indices,
|
||||
sampled_mask=[False] * total_len,
|
||||
is_content=[False] * len(previous_ids) + ext_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
@@ -300,6 +416,7 @@ class Qwen3Renderer:
|
||||
preserve_thinking: bool = False,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
):
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
@@ -313,11 +430,24 @@ 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. ``is_content`` is
|
||||
# also False here — the role tag isn't part of any message's
|
||||
# body, on any role.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build the 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``). For assistant messages
|
||||
# the invariant ``is_content == sampled_mask`` holds — every
|
||||
# sampled token is body, every scaffold token isn't.
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
|
||||
emit_in_template_window = msg_idx > last_query_index and (
|
||||
@@ -325,17 +455,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, is_content=True)
|
||||
else:
|
||||
for tc_idx, tc in enumerate(tool_calls):
|
||||
func = tc.get("function") or tc
|
||||
@@ -350,19 +480,29 @@ 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, is_content=True
|
||||
)
|
||||
else:
|
||||
emit_text("\n", msg_idx)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
emit_special(self._tool_call, msg_idx)
|
||||
emit_special(self._tool_call, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text(
|
||||
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
emit_special(self._tool_call_end, msg_idx)
|
||||
|
||||
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 (and the
|
||||
# assistant's body). The trailing ``\n`` is template-appended
|
||||
# between turns and never sampled — scaffold for is_content too.
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -372,21 +512,40 @@ class Qwen3Renderer:
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. The ``content``
|
||||
# field's body bytes get ``is_content=True``; everything else —
|
||||
# the ``<|im_start|>user`` wrap, the inter-section ``\n``s, the
|
||||
# ``<|tool_response>`` specials — is scaffold so the SFT mask
|
||||
# for tool body never trains the model to emit them.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
)
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._im_start, msg_idx)
|
||||
emit_text("user", msg_idx)
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("user", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
emit_text("\n", msg_idx)
|
||||
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, is_content=False)
|
||||
emit_special(self._tool_response, msg_idx, is_sampled=False, is_content=False)
|
||||
# ``\n`` + content + ``\n`` — body is the middle segment only.
|
||||
# Single BPE pass over the joined text preserves boundary
|
||||
# merges (Qwen3 keeps ``\n`` as its own token, so this is
|
||||
# mostly a no-op, but we route through segments anyway so the
|
||||
# attribution doesn't depend on tokenizer-specific behaviour).
|
||||
emit_text_segments(
|
||||
[("\n", False), (content, True), ("\n", False)],
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
)
|
||||
emit_special(
|
||||
self._tool_response_end, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
|
||||
if not next_is_tool:
|
||||
emit_special(self._im_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+405
-115
@@ -26,10 +26,12 @@ from renderers.base import (
|
||||
PlaceholderRange,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
should_preserve_past_thinking,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.parsing import parse_qwen35
|
||||
from renderers.qwen3_vl import (
|
||||
_image_hash,
|
||||
@@ -102,25 +104,27 @@ def _detect_enable_thinking_default(tokenizer: PreTrainedTokenizer) -> bool:
|
||||
class Qwen35Renderer:
|
||||
"""Deterministic message → token renderer for Qwen3.5 models."""
|
||||
|
||||
_config_cls: type = Qwen35RendererConfig
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Qwen35RendererConfig | None = None,
|
||||
*,
|
||||
processor: Any = None,
|
||||
enable_thinking: bool | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
image_cache_max: int = 256,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
if enable_thinking is None:
|
||||
enable_thinking = _detect_enable_thinking_default(tokenizer)
|
||||
self._enable_thinking = enable_thinking
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
cfg = config or type(self)._config_cls()
|
||||
# ``enable_thinking=None`` defers to the tokenizer's chat-template
|
||||
# default (Instruct → off, Thinking → on). Materialise here so
|
||||
# downstream reads see a concrete bool; rebind the config with
|
||||
# the resolved value so introspection sees the same.
|
||||
if cfg.enable_thinking is None:
|
||||
cfg = cfg.model_copy(
|
||||
update={"enable_thinking": _detect_enable_thinking_default(tokenizer)}
|
||||
)
|
||||
self.config = cfg
|
||||
|
||||
# Look up special token IDs from the tokenizer (not hardcoded)
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
@@ -141,7 +145,6 @@ class Qwen35Renderer:
|
||||
# rationale (FIFO-bounded; same image seen across rollouts /
|
||||
# bridge re-renders).
|
||||
self._image_cache: dict[str, tuple[Any, int]] = {}
|
||||
self._image_cache_max = image_cache_max
|
||||
|
||||
@property
|
||||
def mm_token_type_id_map(self) -> dict[int, int]:
|
||||
@@ -186,7 +189,7 @@ class Qwen35Renderer:
|
||||
grid_thw = out["image_grid_thw"][0]
|
||||
merge_size = proc.image_processor.merge_size
|
||||
num_image_tokens = int(grid_thw.prod()) // (merge_size * merge_size)
|
||||
if len(self._image_cache) >= self._image_cache_max:
|
||||
if len(self._image_cache) >= self.config.image_cache_max:
|
||||
self._image_cache.pop(next(iter(self._image_cache)))
|
||||
self._image_cache[h] = (out, num_image_tokens)
|
||||
return pil, out, num_image_tokens, h
|
||||
@@ -290,28 +293,89 @@ class Qwen35Renderer:
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
sampled: list[bool] = []
|
||||
content_mask: list[bool] = []
|
||||
mm_hashes: dict[str, list[str]] = {}
|
||||
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
mm_items: dict[str, list[dict[str, Any]]] = {}
|
||||
# 1-indexed counters for ``add_vision_id`` (mirrors the Jinja's
|
||||
# ``image_count`` / ``video_count`` namespaces). Increment only
|
||||
# in the main message loop — the template renders the system
|
||||
# message with ``do_vision_count=False`` and would raise on
|
||||
# vision in system content anyway, so the renderer's
|
||||
# ``emit_image`` is only reached from user / tool emission paths.
|
||||
vision_counts = {"image": 0, "video": 0}
|
||||
|
||||
def emit_ids(ids: list[int], msg_idx: int) -> None:
|
||||
def emit_ids(
|
||||
ids: list[int], msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
def emit_special(
|
||||
token_id: int, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
emit_ids(self._encode(text), msg_idx)
|
||||
def emit_text(
|
||||
text: str, msg_idx: int, *, is_sampled: bool, is_content: bool
|
||||
) -> None:
|
||||
emit_ids(
|
||||
self._encode(text),
|
||||
msg_idx,
|
||||
is_sampled=is_sampled,
|
||||
is_content=is_content,
|
||||
)
|
||||
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]], msg_idx: int, *, is_sampled: bool
|
||||
) -> None:
|
||||
"""Tokenize concatenated segments as one BPE pass; per-token
|
||||
``is_content`` follows each token's source segment.
|
||||
|
||||
Lets call sites express "this wrap + this body, joined the
|
||||
same way as the chat template, but attributed separately"
|
||||
without splitting the encode call (which could shift BPE
|
||||
merges at the boundary)."""
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_image(part: dict[str, Any], msg_idx: int) -> None:
|
||||
# Image placeholders only appear in user / tool messages; the
|
||||
# model never samples them. Pin is_sampled=False here so
|
||||
# callers don't need to thread the flag through. The
|
||||
# ``<|image_pad|>`` placeholders represent caller-provided
|
||||
# image data, so they ARE body content (is_content=True);
|
||||
# the surrounding ``<|vision_start|>`` / ``<|vision_end|>``
|
||||
# specials are template scaffold.
|
||||
_, out, n, h = self._process_image(part)
|
||||
emit_special(self._vision_start, msg_idx)
|
||||
vision_counts["image"] += 1
|
||||
if self.config.add_vision_id:
|
||||
emit_text(
|
||||
f"Picture {vision_counts['image']}: ",
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
emit_special(
|
||||
self._vision_start, msg_idx, is_sampled=False, is_content=False
|
||||
)
|
||||
offset = len(tokens)
|
||||
for _ in range(n):
|
||||
emit_special(self._image_pad, msg_idx)
|
||||
emit_special(self._vision_end, msg_idx)
|
||||
emit_special(
|
||||
self._image_pad, msg_idx, is_sampled=False, is_content=True
|
||||
)
|
||||
emit_special(self._vision_end, msg_idx, is_sampled=False, is_content=False)
|
||||
mm_hashes.setdefault("image", []).append(h)
|
||||
mm_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=n)
|
||||
@@ -331,18 +395,28 @@ class Qwen35Renderer:
|
||||
``<|im_end|>``), matching how Jinja's ``render_content`` macro
|
||||
concatenates strings before tokenization. This preserves BPE
|
||||
byte-parity against ``apply_chat_template``.
|
||||
|
||||
Within each flush the ``"user\\n"`` wrap is scaffold and the
|
||||
text parts are body. ``emit_text_segments`` carries that
|
||||
attribution through the BPE pass.
|
||||
"""
|
||||
emit_special(self._im_start, msg_idx)
|
||||
buf: list[str] = ["user\n"]
|
||||
# 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, is_content=False)
|
||||
# First flush includes the ``"user\n"`` wrap as a scaffold
|
||||
# segment; subsequent flushes are pure body (after a media
|
||||
# break).
|
||||
buf_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
|
||||
def flush_buf() -> None:
|
||||
if buf:
|
||||
emit_text("".join(buf), msg_idx)
|
||||
buf.clear()
|
||||
if buf_segments:
|
||||
emit_text_segments(buf_segments, msg_idx, is_sampled=False)
|
||||
buf_segments.clear()
|
||||
|
||||
for item in content_list:
|
||||
if isinstance(item, str):
|
||||
buf.append(item)
|
||||
if item:
|
||||
buf_segments.append((item, True))
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
flush_buf()
|
||||
@@ -352,14 +426,15 @@ class Qwen35Renderer:
|
||||
"Video parts are not yet supported by Qwen35Renderer."
|
||||
)
|
||||
elif "text" in item:
|
||||
buf.append(item["text"])
|
||||
if item["text"]:
|
||||
buf_segments.append((item["text"], True))
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
flush_buf()
|
||||
emit_special(self._im_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
emit_special(self._im_end, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 1. System message + optional tools ──────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
@@ -368,31 +443,37 @@ class Qwen35Renderer:
|
||||
# System message index for attribution
|
||||
sys_idx = 0 if first_is_system else -1
|
||||
|
||||
emit_special(self._im_start, sys_idx)
|
||||
emit_text("system\n", sys_idx)
|
||||
|
||||
# Tools header + JSON definitions
|
||||
tool_text = _TOOLS_HEADER
|
||||
emit_special(self._im_start, sys_idx, is_sampled=False, is_content=False)
|
||||
# Body = system content (if any). Everything else in this
|
||||
# block — role tag, tools header / footer / instructions, the
|
||||
# JSON tool specs — is scaffold. The tools dict is
|
||||
# recoverable from the ``tools`` argument; don't re-attribute
|
||||
# its embedded JSON as message body.
|
||||
segments: list[tuple[str, bool]] = [
|
||||
("system\n", False),
|
||||
(_TOOLS_HEADER, False),
|
||||
]
|
||||
for tool in tools:
|
||||
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
|
||||
tool_text += _TOOLS_FOOTER
|
||||
tool_text += _TOOLS_INSTRUCTIONS
|
||||
|
||||
# Append user's system content if present
|
||||
segments.append(("\n" + json.dumps(tool, ensure_ascii=False), False))
|
||||
segments.append((_TOOLS_FOOTER, False))
|
||||
segments.append((_TOOLS_INSTRUCTIONS, False))
|
||||
if first_is_system:
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
if sys_content:
|
||||
tool_text += "\n\n" + sys_content
|
||||
|
||||
emit_text(tool_text, sys_idx)
|
||||
emit_special(self._im_end, sys_idx)
|
||||
emit_text("\n", sys_idx)
|
||||
segments.append(("\n\n", False))
|
||||
segments.append((sys_content, True))
|
||||
emit_text_segments(segments, sys_idx, is_sampled=False)
|
||||
emit_special(self._im_end, sys_idx, is_sampled=False, is_content=False)
|
||||
emit_text("\n", sys_idx, is_sampled=False, is_content=False)
|
||||
elif first_is_system:
|
||||
sys_content = self._render_content(messages[0].get("content")).strip()
|
||||
emit_special(self._im_start, 0)
|
||||
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, is_content=False)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if sys_content:
|
||||
sys_segments.append((sys_content, True))
|
||||
emit_text_segments(sys_segments, 0, is_sampled=False)
|
||||
emit_special(self._im_end, 0, is_sampled=False, is_content=False)
|
||||
emit_text("\n", 0, is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Compute last_query_index ─────────────────────────────
|
||||
last_qi = self._last_query_index(messages)
|
||||
@@ -412,17 +493,20 @@ class Qwen35Renderer:
|
||||
if self._content_has_media(raw_content):
|
||||
emit_user_with_media(raw_content, i)
|
||||
else:
|
||||
emit_special(self._im_start, i)
|
||||
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, is_content=False)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i, is_sampled=False)
|
||||
emit_special(self._im_end, i, is_sampled=False, is_content=False)
|
||||
emit_text("\n", i, is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
preserve_thinking = should_preserve_past_thinking(
|
||||
messages,
|
||||
i,
|
||||
preserve_all_thinking=self._preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self._preserve_thinking_between_tool_calls,
|
||||
preserve_all_thinking=self.config.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.config.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._render_assistant(
|
||||
msg,
|
||||
@@ -433,15 +517,17 @@ class Qwen35Renderer:
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_ids=emit_ids,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_image=emit_image,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
|
||||
else:
|
||||
@@ -449,16 +535,16 @@ class Qwen35Renderer:
|
||||
|
||||
# ── 4. Generation prompt ────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
emit_special(self._im_start, -1, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", -1, is_sampled=False, is_content=False)
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n", -1, is_sampled=False, is_content=False)
|
||||
else:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n\n", -1)
|
||||
emit_special(self._think_end, -1)
|
||||
emit_text("\n\n", -1)
|
||||
emit_special(self._think, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n\n", -1, is_sampled=False, is_content=False)
|
||||
emit_special(self._think_end, -1, is_sampled=False, is_content=False)
|
||||
emit_text("\n\n", -1, is_sampled=False, is_content=False)
|
||||
|
||||
mm_data: MultiModalData | None = None
|
||||
if mm_hashes or mm_placeholders or mm_items:
|
||||
@@ -471,6 +557,9 @@ class Qwen35Renderer:
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -487,7 +576,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 +590,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]:
|
||||
@@ -526,26 +621,102 @@ class Qwen35Renderer:
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
# ``add_vision_id`` numbers placeholders across the whole
|
||||
# conversation. The bridge can only seed that counter from
|
||||
# ``previous_multi_modal_data`` (raw prior token ids don't carry
|
||||
# the image/video count back), so if the caller asks for
|
||||
# ``add_vision_id=True`` while omitting prior mm-data on a
|
||||
# conversation that already contains images, the bridged
|
||||
# output would silently emit ``Picture 1:`` again. Refuse the
|
||||
# bridge in that case — the caller falls back to a full
|
||||
# re-render, which has the full message list and counts from
|
||||
# scratch correctly.
|
||||
if (
|
||||
self.config.add_vision_id
|
||||
and previous_multi_modal_data is None
|
||||
and self._vision_start in previous_ids
|
||||
):
|
||||
return None
|
||||
|
||||
# Seed combined-token list with prior turn so placeholder offsets
|
||||
# are absolute in the bridged sequence (matching ``render()``).
|
||||
# Parallel ``indices``/``sampled`` are seeded with ``-1``/``False``
|
||||
# for the prior portion — the bridge has no attribution info for
|
||||
# ``previous_ids``. Bridge-added tokens get proper ``msg_idx``
|
||||
# (relative to ``new_messages``) and uniformly ``False``
|
||||
# ``sampled``: nothing the bridge emits was model-sampled.
|
||||
# ``is_content`` follows the same rules as in :meth:`render` so
|
||||
# consumers can walk the trajectory and read each step's own
|
||||
# body mask; the prior portion is uniformly False since we have
|
||||
# no attribution info for it.
|
||||
tokens: list[int] = list(previous_ids)
|
||||
indices: list[int] = [-1] * len(previous_ids)
|
||||
sampled: list[bool] = [False] * len(previous_ids)
|
||||
content_mask: list[bool] = [False] * len(previous_ids)
|
||||
new_hashes: dict[str, list[str]] = {}
|
||||
new_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
new_items: dict[str, list[dict[str, Any]]] = {}
|
||||
# Seed the ``add_vision_id`` counters from prior-turn images / videos
|
||||
# so the bridged turn's first placeholder gets ``Picture {prev+1}``.
|
||||
# Bridges can't recover the count from raw token ids, so callers
|
||||
# must thread ``previous_multi_modal_data`` through to keep
|
||||
# ``add_vision_id`` parity across turns.
|
||||
prev_image_count = 0
|
||||
prev_video_count = 0
|
||||
if previous_multi_modal_data is not None:
|
||||
prev_image_count = len(previous_multi_modal_data.mm_items.get("image", []))
|
||||
prev_video_count = len(previous_multi_modal_data.mm_items.get("video", []))
|
||||
vision_counts = {"image": prev_image_count, "video": prev_video_count}
|
||||
|
||||
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,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_text(text: str, _msg_idx: int = -1) -> None:
|
||||
tokens.extend(self._encode(text))
|
||||
def emit_text(
|
||||
text: str,
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
is_content: bool = False,
|
||||
) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
sampled.extend([is_sampled] * len(ids))
|
||||
content_mask.extend([is_content] * len(ids))
|
||||
|
||||
def emit_image(part: dict[str, Any]) -> None:
|
||||
def emit_text_segments(
|
||||
segments: list[tuple[str, bool]],
|
||||
msg_idx: int = -1,
|
||||
*,
|
||||
is_sampled: bool = False,
|
||||
) -> None:
|
||||
for tok_id, is_content in attribute_text_segments(
|
||||
self._tokenizer, segments
|
||||
):
|
||||
tokens.append(tok_id)
|
||||
indices.append(msg_idx)
|
||||
sampled.append(is_sampled)
|
||||
content_mask.append(is_content)
|
||||
|
||||
def emit_image(part: dict[str, Any], msg_idx: int = -1) -> None:
|
||||
_, out, n, h = self._process_image(part)
|
||||
emit_special(self._vision_start)
|
||||
vision_counts["image"] += 1
|
||||
if self.config.add_vision_id:
|
||||
emit_text(f"Picture {vision_counts['image']}: ", msg_idx)
|
||||
emit_special(self._vision_start, msg_idx)
|
||||
offset = len(tokens)
|
||||
for _ in range(n):
|
||||
emit_special(self._image_pad)
|
||||
emit_special(self._vision_end)
|
||||
emit_special(self._image_pad, msg_idx, is_content=True)
|
||||
emit_special(self._vision_end, msg_idx)
|
||||
new_hashes.setdefault("image", []).append(h)
|
||||
new_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=n)
|
||||
@@ -557,35 +728,37 @@ class Qwen35Renderer:
|
||||
}
|
||||
)
|
||||
|
||||
def emit_user_with_media(content_list: list[Any]) -> None:
|
||||
emit_special(self._im_start)
|
||||
buf: list[str] = ["user\n"]
|
||||
def emit_user_with_media(content_list: list[Any], msg_idx: int) -> None:
|
||||
emit_special(self._im_start, msg_idx)
|
||||
buf_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
|
||||
def flush_buf() -> None:
|
||||
if buf:
|
||||
emit_text("".join(buf))
|
||||
buf.clear()
|
||||
if buf_segments:
|
||||
emit_text_segments(buf_segments, msg_idx)
|
||||
buf_segments.clear()
|
||||
|
||||
for item in content_list:
|
||||
if isinstance(item, str):
|
||||
buf.append(item)
|
||||
if item:
|
||||
buf_segments.append((item, True))
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
flush_buf()
|
||||
emit_image(item)
|
||||
emit_image(item, msg_idx)
|
||||
elif _is_video_part(item):
|
||||
raise NotImplementedError(
|
||||
"Video parts are not yet supported by Qwen35Renderer."
|
||||
)
|
||||
elif "text" in item:
|
||||
buf.append(item["text"])
|
||||
if item["text"]:
|
||||
buf_segments.append((item["text"], True))
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
flush_buf()
|
||||
emit_special(self._im_end)
|
||||
emit_text("\n")
|
||||
emit_special(self._im_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
|
||||
# Trailing ``\n`` after ``<|im_end|>`` — ``render()`` emits it as
|
||||
# part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
|
||||
@@ -598,24 +771,31 @@ class Qwen35Renderer:
|
||||
content = self._render_content(raw_content).strip()
|
||||
if role == "user":
|
||||
if self._content_has_media(raw_content):
|
||||
emit_user_with_media(raw_content)
|
||||
emit_user_with_media(raw_content, i)
|
||||
else:
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("user\n" + content, i)
|
||||
user_segments: list[tuple[str, bool]] = [("user\n", False)]
|
||||
if content:
|
||||
user_segments.append((content, True))
|
||||
emit_text_segments(user_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "system":
|
||||
emit_special(self._im_start, i)
|
||||
emit_text("system\n" + content, i)
|
||||
sys_segments: list[tuple[str, bool]] = [("system\n", False)]
|
||||
if content:
|
||||
sys_segments.append((content, True))
|
||||
emit_text_segments(sys_segments, i)
|
||||
emit_special(self._im_end, i)
|
||||
emit_text("\n", i)
|
||||
elif role == "tool":
|
||||
self._render_tool(
|
||||
new_messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_image=emit_image,
|
||||
emit_text_segments=emit_text_segments,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
@@ -623,7 +803,7 @@ class Qwen35Renderer:
|
||||
# Generation prompt — matches the gen-prompt branch of ``render()``.
|
||||
emit_special(self._im_start, -1)
|
||||
emit_text("assistant\n", -1)
|
||||
if self._enable_thinking:
|
||||
if self.config.enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
emit_text("\n", -1)
|
||||
else:
|
||||
@@ -655,8 +835,15 @@ class Qwen35Renderer:
|
||||
for modality, vals in new_items.items():
|
||||
merged_items.setdefault(modality, []).extend(vals)
|
||||
|
||||
bridge_roles = [m.get("role") or "" for m in new_messages]
|
||||
if not (merged_hashes or merged_placeholders or merged_items):
|
||||
return RenderedTokens(token_ids=tokens)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
)
|
||||
|
||||
mm_data = MultiModalData(
|
||||
mm_hashes=merged_hashes,
|
||||
@@ -665,7 +852,10 @@ class Qwen35Renderer:
|
||||
)
|
||||
return RenderedTokens(
|
||||
token_ids=tokens,
|
||||
message_indices=[-1] * len(tokens),
|
||||
message_indices=indices,
|
||||
sampled_mask=sampled,
|
||||
is_content=content_mask,
|
||||
message_roles=bridge_roles,
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -707,6 +897,7 @@ class Qwen35Renderer:
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_ids,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Extract reasoning_content
|
||||
reasoning_content = ""
|
||||
@@ -725,20 +916,40 @@ 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. ``is_content`` is
|
||||
# also False here — the role tag isn't part of any message's
|
||||
# body, on any role.
|
||||
emit_special(self._im_start, msg_idx, is_sampled=False, is_content=False)
|
||||
emit_text("assistant\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# Build the model-sampled portion (think block + content + tool
|
||||
# calls). Text segments stay contiguous within each is_sampled
|
||||
# span to preserve BPE merges. For assistant messages the
|
||||
# invariant ``is_content == sampled_mask`` holds — every sampled
|
||||
# token is body, every scaffold token isn't. The XML-style tool
|
||||
# call tags (``<function=...>``, ``<parameter=...>``, etc.) are
|
||||
# part of the model's emitted output too — keep them
|
||||
# ``is_content=True`` per the assistant rule.
|
||||
emit_thinking = self._should_render_thinking(msg_idx, last_query_index) or (
|
||||
preserve_thinking and bool(reasoning_content)
|
||||
)
|
||||
if emit_thinking:
|
||||
# Include thinking block
|
||||
emit_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, is_content=True)
|
||||
emit_text(
|
||||
"\n" + reasoning_content + "\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
emit_special(self._think_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n\n" + content, msg_idx, is_sampled=True, is_content=True)
|
||||
else:
|
||||
emit_text("assistant\n" + content, msg_idx)
|
||||
emit_text(content, msg_idx, is_sampled=True, is_content=True)
|
||||
|
||||
# Tool calls
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
@@ -751,13 +962,18 @@ 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, is_content=True)
|
||||
# else: no separator
|
||||
else:
|
||||
emit_text("\n", msg_idx)
|
||||
emit_text("\n", msg_idx, is_sampled=True, is_content=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, is_content=True)
|
||||
emit_text(
|
||||
"\n<function=" + name + ">\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
# Render arguments
|
||||
# OpenAI canonical form: arguments is a JSON string. Parse it so the
|
||||
@@ -777,13 +993,21 @@ class Qwen35Renderer:
|
||||
+ value_str
|
||||
+ "\n</parameter>\n",
|
||||
msg_idx,
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
|
||||
emit_text("</function>\n", msg_idx)
|
||||
emit_special(self._tool_call_end, msg_idx)
|
||||
emit_text("</function>\n", msg_idx, is_sampled=True, is_content=True)
|
||||
emit_special(
|
||||
self._tool_call_end, msg_idx, is_sampled=True, is_content=True
|
||||
)
|
||||
|
||||
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 (and the
|
||||
# assistant's body). The trailing ``\n`` is template-appended
|
||||
# between turns and never sampled — scaffold for is_content too.
|
||||
emit_special(self._im_end, msg_idx, is_sampled=True, is_content=True)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Tool message rendering
|
||||
@@ -793,26 +1017,92 @@ class Qwen35Renderer:
|
||||
self,
|
||||
messages: list[Message],
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_image,
|
||||
emit_text_segments,
|
||||
) -> 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 ``content``
|
||||
# field's body bytes get ``is_content=True``; everything else —
|
||||
# the ``<|im_start|>user`` wrap, the inter-section ``\n``s, the
|
||||
# ``<|tool_response>`` specials — is scaffold so the SFT mask
|
||||
# for tool body never trains the model to emit them.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
)
|
||||
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, is_content=False)
|
||||
emit_text("user", msg_idx, is_sampled=False, is_content=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, is_content=False)
|
||||
emit_special(self._tool_response, msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
if self._content_has_media(raw_content):
|
||||
# Mirror the chat template's ``render_content`` macro for list
|
||||
# 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)
|
||||
# First flush: leading ``"\n"`` is scaffold (separates the
|
||||
# ``<|tool_response>`` special from the body); subsequent
|
||||
# text items in this run are body. After a media break, the
|
||||
# buffer resets to pure body until the next media break or
|
||||
# end-of-content.
|
||||
buf_segments: list[tuple[str, bool]] = [("\n", False)]
|
||||
|
||||
def flush_buf() -> None:
|
||||
if buf_segments:
|
||||
emit_text_segments(buf_segments, msg_idx, is_sampled=False)
|
||||
buf_segments.clear()
|
||||
|
||||
for item in raw_content:
|
||||
if isinstance(item, str):
|
||||
if item:
|
||||
buf_segments.append((item, True))
|
||||
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:
|
||||
if item["text"]:
|
||||
buf_segments.append((item["text"], True))
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
flush_buf()
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
else:
|
||||
content = self._render_content(raw_content).strip()
|
||||
# ``\n`` + content + ``\n`` — body is the middle segment only.
|
||||
# Single BPE pass over the joined text preserves boundary
|
||||
# merges.
|
||||
emit_text_segments(
|
||||
[("\n", False), (content, True), ("\n", False)],
|
||||
msg_idx,
|
||||
is_sampled=False,
|
||||
)
|
||||
|
||||
emit_special(
|
||||
self._tool_response_end, msg_idx, is_sampled=False, is_content=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, is_content=False)
|
||||
emit_text("\n", msg_idx, is_sampled=False, is_content=False)
|
||||
|
||||
+9
-6
@@ -7,12 +7,12 @@ Delta vs Qwen3.5 (template line 122):
|
||||
``None`` as ``null`` (not ``None``), fixing the single-turn extension-break
|
||||
mode where a boolean parameter's case drifted across a re-render.
|
||||
|
||||
The template's other delta vs Qwen3.5 (a ``preserve_thinking`` toggle that
|
||||
flips historical ``<think>`` retention on or off globally) is no longer
|
||||
exposed as a constructor kwarg — its default-False behaviour matches
|
||||
Qwen3.5 and is now baked in. Callers who want the toggled-on behaviour
|
||||
pass ``preserve_all_thinking=True`` to ``create_renderer``, the
|
||||
renderer-agnostic spelling of the same intent.
|
||||
Historical-thinking retention follows Qwen3.5's default (drop past
|
||||
``<think>`` blocks). The upstream template carries a ``preserve_thinking``
|
||||
Jinja toggle for the opposite polarity; on the renderer side that intent
|
||||
maps to the renderer-agnostic ``preserve_all_thinking`` /
|
||||
``preserve_thinking_between_tool_calls`` flags on
|
||||
:class:`renderers.Qwen36RendererConfig`.
|
||||
|
||||
Everything else — tool system prompt, tool-call XML structure, thinking
|
||||
markers, bridge logic, parser — is identical to Qwen3.5.
|
||||
@@ -23,12 +23,15 @@ from __future__ import annotations
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from renderers.configs import Qwen36RendererConfig
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
|
||||
|
||||
class Qwen36Renderer(Qwen35Renderer):
|
||||
"""Deterministic message → token renderer for Qwen3.6 models."""
|
||||
|
||||
_config_cls = Qwen36RendererConfig
|
||||
|
||||
@staticmethod
|
||||
def _render_arg_value(arg_value: Any) -> str:
|
||||
if isinstance(arg_value, str):
|
||||
|
||||
+305
-105
@@ -42,9 +42,11 @@ from renderers.base import (
|
||||
PlaceholderRange,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
attribute_text_segments,
|
||||
reject_assistant_in_extension,
|
||||
trim_to_turn_close,
|
||||
)
|
||||
from renderers.configs import Qwen3VLRendererConfig
|
||||
from renderers.parsing import parse_qwen3
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
@@ -70,9 +72,14 @@ def _is_image_part(item: Any) -> bool:
|
||||
t = item.get("type")
|
||||
if t in ("image", "image_url"):
|
||||
return True
|
||||
# Permissive fallback: chat templates check ``'image' in content`` to
|
||||
# accept loosely-shaped image parts, so mirror that.
|
||||
return "image" in item or "image_url" in item
|
||||
if t is not None:
|
||||
return False
|
||||
# Untyped fallback for loosely-shaped image parts. Require a truthy
|
||||
# value: HF Arrow schema unification (Dataset.from_list over a list of
|
||||
# heterogeneous content dicts) fills missing keys with None, so any
|
||||
# text part round-tripped through a Dataset will have ``image_url: None``
|
||||
# as a key. Mere key presence isn't enough.
|
||||
return bool(item.get("image")) or bool(item.get("image_url"))
|
||||
|
||||
|
||||
def _is_video_part(item: Any) -> bool:
|
||||
@@ -81,7 +88,9 @@ def _is_video_part(item: Any) -> bool:
|
||||
t = item.get("type")
|
||||
if t in ("video", "video_url"):
|
||||
return True
|
||||
return "video" in item or "video_url" in item
|
||||
if t is not None:
|
||||
return False
|
||||
return bool(item.get("video")) or bool(item.get("video_url"))
|
||||
|
||||
|
||||
def _load_pil_image(item: dict[str, Any]):
|
||||
@@ -162,14 +171,41 @@ 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.
|
||||
|
||||
``is_content`` is the per-token body/scaffold attribution. Within a
|
||||
single flush adjacent text fragments may carry different
|
||||
``is_content`` values (e.g. ``"user\\n"`` scaffold + caller content
|
||||
body): the buffer stores fragments as a list of
|
||||
``(text, is_content)`` segments and flushes via
|
||||
:func:`attribute_text_segments`, which performs one BPE pass over
|
||||
the joined text and assigns per-token is_content from each token's
|
||||
source segment. When every segment in a flush shares the same
|
||||
is_content (the common case for sampled assistant body / pure
|
||||
scaffold) the fast path of a single ``encode()`` call is used and
|
||||
no offset-tokenizer lookup is required.
|
||||
"""
|
||||
|
||||
def __init__(self, encode_fn, msg_idx: int = -1):
|
||||
def __init__(self, encode_fn, tokenizer=None, msg_idx: int = -1):
|
||||
self._encode = encode_fn
|
||||
self._tokenizer = tokenizer
|
||||
self.token_ids: list[int] = []
|
||||
self.message_indices: list[int] = []
|
||||
self._buf: str = ""
|
||||
self.sampled: list[bool] = []
|
||||
self.is_content: list[bool] = []
|
||||
# Buffered text fragments as ``(text, is_content)`` tuples. All
|
||||
# fragments share a single ``_buf_sampled`` / ``_buf_idx``;
|
||||
# changing either of those triggers a flush.
|
||||
self._segments: list[tuple[str, bool]] = []
|
||||
self._buf_idx: int = msg_idx
|
||||
self._buf_sampled: bool = False
|
||||
self.msg_idx = msg_idx
|
||||
|
||||
def set_msg_idx(self, msg_idx: int) -> None:
|
||||
@@ -177,43 +213,78 @@ class _Emitter:
|
||||
# text doesn't get glued to the previous one's BPE context.
|
||||
# In practice messages are always separated by an <|im_end|>
|
||||
# special token, which already flushes — but be defensive.
|
||||
if self._buf:
|
||||
if self._segments:
|
||||
self._flush()
|
||||
self.msg_idx = msg_idx
|
||||
self._buf_idx = msg_idx
|
||||
|
||||
def text(self, text: str) -> None:
|
||||
def text(self, text: str, *, is_sampled: bool, is_content: 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. is_content boundaries do
|
||||
# NOT force a flush: they're carried through the joined BPE pass
|
||||
# via :func:`attribute_text_segments`, preserving merges across
|
||||
# the wrap/body boundary.
|
||||
if self._segments and (
|
||||
self._buf_idx != self.msg_idx or self._buf_sampled != is_sampled
|
||||
):
|
||||
self._flush()
|
||||
if not self._buf:
|
||||
if not self._segments:
|
||||
self._buf_idx = self.msg_idx
|
||||
self._buf += text
|
||||
self._buf_sampled = is_sampled
|
||||
self._segments.append((text, is_content))
|
||||
|
||||
def special(self, token_id: int) -> None:
|
||||
if self._buf:
|
||||
def special(self, token_id: int, *, is_sampled: bool, is_content: bool) -> None:
|
||||
if self._segments:
|
||||
self._flush()
|
||||
self.token_ids.append(token_id)
|
||||
self.message_indices.append(self.msg_idx)
|
||||
self.sampled.append(is_sampled)
|
||||
self.is_content.append(is_content)
|
||||
|
||||
def cursor(self) -> int:
|
||||
"""Current token offset after flushing — used to anchor placeholder ranges."""
|
||||
if self._buf:
|
||||
if self._segments:
|
||||
self._flush()
|
||||
return len(self.token_ids)
|
||||
|
||||
def finalize(self) -> None:
|
||||
if self._buf:
|
||||
if self._segments:
|
||||
self._flush()
|
||||
|
||||
def _flush(self) -> None:
|
||||
ids = self._encode(self._buf)
|
||||
self.token_ids.extend(ids)
|
||||
self.message_indices.extend([self._buf_idx] * len(ids))
|
||||
self._buf = ""
|
||||
segments = self._segments
|
||||
self._segments = []
|
||||
if not segments:
|
||||
return
|
||||
# Fast path: every segment shares the same is_content — use the
|
||||
# plain ``encode()`` call so we don't pay for the offset
|
||||
# tokenizer. This is the common case (pure scaffold flushes, or
|
||||
# pure body flushes).
|
||||
first_ic = segments[0][1]
|
||||
all_same = all(ic == first_ic for _, ic in segments)
|
||||
if all_same:
|
||||
joined = "".join(text for text, _ in segments)
|
||||
ids = self._encode(joined)
|
||||
self.token_ids.extend(ids)
|
||||
self.message_indices.extend([self._buf_idx] * len(ids))
|
||||
self.sampled.extend([self._buf_sampled] * len(ids))
|
||||
self.is_content.extend([first_ic] * len(ids))
|
||||
return
|
||||
# Mixed body/scaffold flush — encode once and attribute back to
|
||||
# each segment via the fast tokenizer's offset_mapping. Requires
|
||||
# a tokenizer (not just the encode fn) to look up offsets.
|
||||
assert self._tokenizer is not None, (
|
||||
"_Emitter mixed-is_content flush requires a tokenizer; "
|
||||
"pass one to the constructor."
|
||||
)
|
||||
for tok_id, is_content in attribute_text_segments(self._tokenizer, segments):
|
||||
self.token_ids.append(tok_id)
|
||||
self.message_indices.append(self._buf_idx)
|
||||
self.sampled.append(self._buf_sampled)
|
||||
self.is_content.append(is_content)
|
||||
|
||||
|
||||
class Qwen3VLRenderer:
|
||||
@@ -221,35 +292,30 @@ class Qwen3VLRenderer:
|
||||
|
||||
Constructor args:
|
||||
tokenizer: HF tokenizer for the model.
|
||||
config: Typed renderer config (see
|
||||
:class:`renderers.Qwen3VLRendererConfig`). Defaults to a
|
||||
blank config with template defaults.
|
||||
processor: Optional ``Qwen3VLProcessor``. Required when rendering
|
||||
messages that contain image / video parts. If not supplied,
|
||||
the renderer lazy-loads it via ``AutoProcessor.from_pretrained``
|
||||
keyed off ``tokenizer.name_or_path`` the first time a
|
||||
multimodal part is seen.
|
||||
preserve_all_thinking / preserve_thinking_between_tool_calls:
|
||||
No-ops on Qwen3-VL — the chat template already drops past
|
||||
``<think>`` blocks unconditionally. Stored for Protocol parity.
|
||||
image_cache_max: Max entries in the per-instance image-processor
|
||||
cache (FIFO eviction). Default 256 covers typical RL pools
|
||||
(``rollouts_per_example`` × in-flight examples). Bump for runs
|
||||
with large image sets where the working set exceeds the cap.
|
||||
|
||||
``preserve_all_thinking`` / ``preserve_thinking_between_tool_calls``
|
||||
on the config are no-ops here — the chat template drops past
|
||||
``<think>`` blocks unconditionally. Stored for Protocol parity.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: Qwen3VLRendererConfig | None = None,
|
||||
*,
|
||||
processor: Any = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
image_cache_max: int = 256,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._processor = processor
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
self.config = config or Qwen3VLRendererConfig()
|
||||
|
||||
self._im_start = self._token_id("<|im_start|>")
|
||||
self._im_end = self._token_id("<|im_end|>")
|
||||
@@ -272,7 +338,6 @@ class Qwen3VLRenderer:
|
||||
# tuples of ``(processor_out, num_image_tokens)`` — bounded to
|
||||
# avoid unbounded growth on long-lived pools.
|
||||
self._image_cache: dict[str, tuple[Any, int]] = {}
|
||||
self._image_cache_max = image_cache_max
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
tid = self._tokenizer.convert_tokens_to_ids(token)
|
||||
@@ -361,7 +426,7 @@ class Qwen3VLRenderer:
|
||||
grid_thw = out["image_grid_thw"][0]
|
||||
merge_size = proc.image_processor.merge_size
|
||||
num_image_tokens = int(grid_thw.prod()) // (merge_size * merge_size)
|
||||
if len(self._image_cache) >= self._image_cache_max:
|
||||
if len(self._image_cache) >= self.config.image_cache_max:
|
||||
# FIFO eviction — Python dicts preserve insertion order, so
|
||||
# ``next(iter(...))`` is the oldest key.
|
||||
self._image_cache.pop(next(iter(self._image_cache)))
|
||||
@@ -378,18 +443,38 @@ class Qwen3VLRenderer:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
em = _Emitter(self._encode)
|
||||
em = _Emitter(self._encode, tokenizer=self._tokenizer)
|
||||
mm_hashes: dict[str, list[str]] = {}
|
||||
mm_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
mm_items: dict[str, list[dict[str, Any]]] = {}
|
||||
# ``add_vision_id`` mirrors the Jinja's ``image_count`` /
|
||||
# ``video_count`` namespaces. Counters are 1-indexed and run
|
||||
# across the entire conversation; they increment unconditionally
|
||||
# on each image / video (the Qwen3-VL template increments first,
|
||||
# then emits ``Picture N: `` only when ``add_vision_id`` is set).
|
||||
vision_counts = {"image": 0, "video": 0}
|
||||
|
||||
def emit_image(part: dict[str, Any]) -> None:
|
||||
# Image placeholders are prompt-side scaffolding the user
|
||||
# message attaches — the model never samples ``<|vision_start|>``
|
||||
# / ``<|image_pad|>`` / ``<|vision_end|>``. The
|
||||
# ``<|image_pad|>`` placeholders represent caller-provided
|
||||
# image data, so they ARE body content (is_content=True);
|
||||
# the surrounding ``<|vision_start|>`` / ``<|vision_end|>``
|
||||
# markers are renderer-emitted scaffold.
|
||||
_, out, n, h = self._process_image(part)
|
||||
em.special(self._vision_start)
|
||||
vision_counts["image"] += 1
|
||||
if self.config.add_vision_id:
|
||||
em.text(
|
||||
f"Picture {vision_counts['image']}: ",
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
em.special(self._vision_start, is_sampled=False, is_content=False)
|
||||
offset = em.cursor()
|
||||
for _ in range(n):
|
||||
em.special(self._image_pad)
|
||||
em.special(self._vision_end)
|
||||
em.special(self._image_pad, is_sampled=False, is_content=True)
|
||||
em.special(self._vision_end, is_sampled=False, is_content=False)
|
||||
mm_hashes.setdefault("image", []).append(h)
|
||||
mm_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=n)
|
||||
@@ -402,16 +487,28 @@ 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``.
|
||||
Text from the caller IS the message body, so every text
|
||||
fragment is ``is_content=True``; the vision-marker specials
|
||||
around image_pad placeholders are scaffold (handled in
|
||||
:func:`emit_image`).
|
||||
"""
|
||||
if isinstance(content, str):
|
||||
em.text(content)
|
||||
em.text(content, is_sampled=False, is_content=True)
|
||||
return
|
||||
if not isinstance(content, list):
|
||||
em.text(self._render_text_content(content))
|
||||
em.text(
|
||||
self._render_text_content(content),
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
return
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
em.text(item)
|
||||
em.text(item, is_sampled=False, is_content=True)
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
emit_image(item)
|
||||
@@ -420,7 +517,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, is_content=True)
|
||||
|
||||
# ── 1. System + tools ───────────────────────────────────────
|
||||
first_is_system = messages[0].get("role") == "system"
|
||||
@@ -428,23 +525,37 @@ class Qwen3VLRenderer:
|
||||
if tools:
|
||||
sys_idx = 0 if first_is_system else -1
|
||||
em.set_msg_idx(sys_idx)
|
||||
em.special(self._im_start)
|
||||
buf = "system\n"
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
# Body = system content (if any). Everything else in this
|
||||
# block — role tag, tools header / footer, JSON tool specs —
|
||||
# is scaffold. The tools dict is recoverable from the
|
||||
# ``tools`` argument; we don't re-attribute its embedded
|
||||
# JSON as message body.
|
||||
em.text("system\n", is_sampled=False, is_content=False)
|
||||
if first_is_system:
|
||||
buf += self._render_text_content(messages[0].get("content")) + "\n\n"
|
||||
buf += _TOOLS_HEADER
|
||||
sys_content = self._render_text_content(messages[0].get("content"))
|
||||
if sys_content:
|
||||
em.text(sys_content, is_sampled=False, is_content=True)
|
||||
em.text("\n\n", is_sampled=False, is_content=False)
|
||||
em.text(_TOOLS_HEADER, is_sampled=False, is_content=False)
|
||||
for tool in tools:
|
||||
buf += "\n" + json.dumps(tool, ensure_ascii=False)
|
||||
buf += _TOOLS_FOOTER
|
||||
em.text(buf)
|
||||
em.special(self._im_end)
|
||||
em.text("\n")
|
||||
em.text(
|
||||
"\n" + json.dumps(tool, ensure_ascii=False),
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
em.text(_TOOLS_FOOTER, is_sampled=False, is_content=False)
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
elif first_is_system:
|
||||
em.set_msg_idx(0)
|
||||
em.special(self._im_start)
|
||||
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, is_content=False)
|
||||
em.text("system\n", is_sampled=False, is_content=False)
|
||||
sys_content = self._render_text_content(messages[0].get("content"))
|
||||
if sys_content:
|
||||
em.text(sys_content, is_sampled=False, is_content=True)
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
# ── 2. Iterate messages ─────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
@@ -456,11 +567,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, is_content=False)
|
||||
em.text("user\n", is_sampled=False, is_content=False)
|
||||
render_media_content(msg.get("content"))
|
||||
em.special(self._im_end)
|
||||
em.text("\n")
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
elif role == "assistant":
|
||||
self._render_assistant(msg, em)
|
||||
@@ -474,8 +585,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, is_content=False)
|
||||
em.text("assistant\n", is_sampled=False, is_content=False)
|
||||
|
||||
em.finalize()
|
||||
|
||||
@@ -490,6 +601,9 @@ class Qwen3VLRenderer:
|
||||
return RenderedTokens(
|
||||
token_ids=em.token_ids,
|
||||
message_indices=em.message_indices,
|
||||
sampled_mask=em.sampled,
|
||||
is_content=em.is_content,
|
||||
message_roles=[m.get("role") or "" for m in messages],
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -506,7 +620,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,23 +671,74 @@ class Qwen3VLRenderer:
|
||||
if previous_ids is None:
|
||||
return None
|
||||
|
||||
em = _Emitter(self._encode)
|
||||
# ``add_vision_id`` numbers placeholders across the whole
|
||||
# conversation. The bridge can only seed that counter from
|
||||
# ``previous_multi_modal_data`` (raw prior token ids don't carry
|
||||
# the image/video count back), so if the caller asks for
|
||||
# ``add_vision_id=True`` while omitting prior mm-data on a
|
||||
# conversation that already contains images, the bridged
|
||||
# output would silently emit ``Picture 1:`` again. Refuse the
|
||||
# bridge in that case — the caller falls back to a full
|
||||
# re-render, which has the full message list and counts
|
||||
# correctly.
|
||||
if (
|
||||
self.config.add_vision_id
|
||||
and previous_multi_modal_data is None
|
||||
and self._vision_start in previous_ids
|
||||
):
|
||||
return None
|
||||
|
||||
# Bridge populates ``message_indices`` (relative to ``new_messages``)
|
||||
# and ``sampled_mask`` (uniformly ``False`` — every token the
|
||||
# bridge emits is template scaffolding for the next prompt, not
|
||||
# something the model sampled). ``is_content`` follows the same
|
||||
# rules as in :meth:`render` so consumers can walk the trajectory
|
||||
# and read each step's own body mask. Downstream consumers can
|
||||
# run :meth:`RenderedTokens.tokens_per_message` on the bridge
|
||||
# output to get per-new-message token counts without re-rendering.
|
||||
em = _Emitter(self._encode, tokenizer=self._tokenizer)
|
||||
# Seed the emitter with the prior turn's tokens so cursor() reports
|
||||
# absolute offsets in the combined sequence.
|
||||
# absolute offsets in the combined sequence. Per-token attribution
|
||||
# for the prior portion is unknown to the bridge (it only has
|
||||
# prev_prompt_ids + prev_completion_ids as raw lists), so seed
|
||||
# all side channels with the "no info" sentinel.
|
||||
em.token_ids = list(previous_ids)
|
||||
em.message_indices = [-1] * len(previous_ids)
|
||||
em.sampled = [False] * len(previous_ids)
|
||||
em.is_content = [False] * len(previous_ids)
|
||||
|
||||
new_hashes: dict[str, list[str]] = {}
|
||||
new_placeholders: dict[str, list[PlaceholderRange]] = {}
|
||||
new_items: dict[str, list[dict[str, Any]]] = {}
|
||||
# Seed the vision counters from any prior-turn images / videos
|
||||
# the bridge was handed via ``previous_multi_modal_data``. The
|
||||
# ``add_vision_id`` template numbers placeholders across the
|
||||
# whole conversation, so a new turn's first image is
|
||||
# ``Picture {prev_total + 1}``. The bridge can't recover this
|
||||
# count from raw token ids, so callers must thread
|
||||
# ``previous_multi_modal_data`` through when they want
|
||||
# ``add_vision_id`` parity across turns.
|
||||
prev_image_count = 0
|
||||
prev_video_count = 0
|
||||
if previous_multi_modal_data is not None:
|
||||
prev_image_count = len(previous_multi_modal_data.mm_items.get("image", []))
|
||||
prev_video_count = len(previous_multi_modal_data.mm_items.get("video", []))
|
||||
vision_counts = {"image": prev_image_count, "video": prev_video_count}
|
||||
|
||||
def emit_image(part: dict[str, Any]) -> None:
|
||||
_, out, n, h = self._process_image(part)
|
||||
em.special(self._vision_start)
|
||||
vision_counts["image"] += 1
|
||||
if self.config.add_vision_id:
|
||||
em.text(
|
||||
f"Picture {vision_counts['image']}: ",
|
||||
is_sampled=False,
|
||||
is_content=False,
|
||||
)
|
||||
em.special(self._vision_start, is_sampled=False, is_content=False)
|
||||
offset = em.cursor()
|
||||
for _ in range(n):
|
||||
em.special(self._image_pad)
|
||||
em.special(self._vision_end)
|
||||
em.special(self._image_pad, is_sampled=False, is_content=True)
|
||||
em.special(self._vision_end, is_sampled=False, is_content=False)
|
||||
new_hashes.setdefault("image", []).append(h)
|
||||
new_placeholders.setdefault("image", []).append(
|
||||
PlaceholderRange(offset=offset, length=n)
|
||||
@@ -582,14 +752,18 @@ class Qwen3VLRenderer:
|
||||
|
||||
def render_media_content(content: Any) -> None:
|
||||
if isinstance(content, str):
|
||||
em.text(content)
|
||||
em.text(content, is_sampled=False, is_content=True)
|
||||
return
|
||||
if not isinstance(content, list):
|
||||
em.text(self._render_text_content(content))
|
||||
em.text(
|
||||
self._render_text_content(content),
|
||||
is_sampled=False,
|
||||
is_content=True,
|
||||
)
|
||||
return
|
||||
for item in content:
|
||||
if isinstance(item, str):
|
||||
em.text(item)
|
||||
em.text(item, is_sampled=False, is_content=True)
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
emit_image(item)
|
||||
@@ -598,34 +772,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, is_content=True)
|
||||
|
||||
em.set_msg_idx(-1)
|
||||
em.text("\n")
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
em.set_msg_idx(i)
|
||||
if role == "user":
|
||||
em.special(self._im_start)
|
||||
em.text("user\n")
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("user\n", is_sampled=False, is_content=False)
|
||||
render_media_content(msg.get("content"))
|
||||
em.special(self._im_end)
|
||||
em.text("\n")
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
elif role == "system":
|
||||
em.special(self._im_start)
|
||||
em.text("system\n")
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("system\n", is_sampled=False, is_content=False)
|
||||
render_media_content(msg.get("content"))
|
||||
em.special(self._im_end)
|
||||
em.text("\n")
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
elif role == "tool":
|
||||
self._render_tool(new_messages, i, em, render_media_content)
|
||||
else:
|
||||
return None
|
||||
|
||||
em.set_msg_idx(-1)
|
||||
em.special(self._im_start)
|
||||
em.text("assistant\n")
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("assistant\n", is_sampled=False, is_content=False)
|
||||
em.finalize()
|
||||
|
||||
# Merge prev mm_data with the new turn's items.
|
||||
@@ -661,6 +835,10 @@ class Qwen3VLRenderer:
|
||||
|
||||
return RenderedTokens(
|
||||
token_ids=em.token_ids,
|
||||
message_indices=em.message_indices,
|
||||
sampled_mask=em.sampled,
|
||||
is_content=em.is_content,
|
||||
message_roles=[m.get("role") or "" for m in new_messages],
|
||||
multi_modal_data=mm_data,
|
||||
)
|
||||
|
||||
@@ -669,18 +847,26 @@ 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. For the assistant role the
|
||||
# invariant ``is_content == sampled_mask`` holds — every sampled
|
||||
# token is body, every scaffold token isn't.
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("assistant\n", is_sampled=False, is_content=False)
|
||||
|
||||
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, is_content=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, is_content=True)
|
||||
else:
|
||||
em.text("\n")
|
||||
em.text("\n", is_sampled=True, is_content=True)
|
||||
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
@@ -691,12 +877,19 @@ 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, is_content=True)
|
||||
em.text(
|
||||
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
|
||||
is_sampled=True,
|
||||
is_content=True,
|
||||
)
|
||||
em.special(self._tool_call_end, is_sampled=True, is_content=True)
|
||||
|
||||
em.special(self._im_end)
|
||||
em.text("\n")
|
||||
# ``<|im_end|>`` is the model's stop signal — it samples this to
|
||||
# end its turn (and counts as part of its body). The trailing
|
||||
# ``\n`` is template-appended between turns and never sampled.
|
||||
em.special(self._im_end, is_sampled=True, is_content=True)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
def _render_tool(
|
||||
self,
|
||||
@@ -705,22 +898,29 @@ 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. The
|
||||
# ``content`` body bytes get ``is_content=True`` (via
|
||||
# ``render_media_content``); everything else — the
|
||||
# ``<|im_start|>user`` wrap, inter-section ``\n``s, and the
|
||||
# ``<|tool_response>`` specials — is scaffold.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
)
|
||||
|
||||
if not prev_is_tool:
|
||||
em.special(self._im_start)
|
||||
em.text("user")
|
||||
em.special(self._im_start, is_sampled=False, is_content=False)
|
||||
em.text("user", is_sampled=False, is_content=False)
|
||||
|
||||
em.text("\n")
|
||||
em.special(self._tool_response)
|
||||
em.text("\n")
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
em.special(self._tool_response, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
render_media_content(messages[msg_idx].get("content"))
|
||||
em.text("\n")
|
||||
em.special(self._tool_response_end)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
em.special(self._tool_response_end, is_sampled=False, is_content=False)
|
||||
|
||||
if not next_is_tool:
|
||||
em.special(self._im_end)
|
||||
em.text("\n")
|
||||
em.special(self._im_end, is_sampled=False, is_content=False)
|
||||
em.text("\n", is_sampled=False, is_content=False)
|
||||
|
||||
+3
-1
@@ -10,6 +10,7 @@ import pytest
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import config_from_name
|
||||
|
||||
# (HuggingFace model name, renderer name or "auto")
|
||||
#
|
||||
@@ -32,6 +33,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"),
|
||||
]
|
||||
@@ -43,7 +45,7 @@ def _load(model_name: str, renderer_name: str):
|
||||
key = f"{model_name}:{renderer_name}"
|
||||
if key not in _cache:
|
||||
tokenizer = load_tokenizer(model_name)
|
||||
renderer = create_renderer(tokenizer, renderer=renderer_name)
|
||||
renderer = create_renderer(tokenizer, config_from_name(renderer_name))
|
||||
_cache[key] = (tokenizer, renderer)
|
||||
return _cache[key]
|
||||
|
||||
|
||||
@@ -41,9 +41,10 @@ _BRIDGE_MODELS = [
|
||||
def _load(model_name: str, renderer_name: str):
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.configs import config_from_name
|
||||
|
||||
tok = load_tokenizer(model_name)
|
||||
return tok, create_renderer(tok, renderer=renderer_name)
|
||||
return tok, create_renderer(tok, config_from_name(renderer_name))
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc):
|
||||
|
||||
+306
-44
@@ -1,9 +1,16 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
|
||||
import httpx
|
||||
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
|
||||
|
||||
|
||||
@@ -14,7 +21,15 @@ class _FakeRenderer:
|
||||
assert messages == [{"role": "user", "content": "hi"}]
|
||||
assert tools == [{"type": "function", "function": {"name": "echo"}}]
|
||||
assert add_generation_prompt is True
|
||||
return RenderedTokens(token_ids=[1, 2, 3])
|
||||
# Populate the full attribution surface so the test can verify
|
||||
# ``generate`` threads it through to the result dict unchanged.
|
||||
return RenderedTokens(
|
||||
token_ids=[1, 2, 3],
|
||||
message_indices=[0, 0, -1],
|
||||
sampled_mask=[False, False, False],
|
||||
is_content=[False, True, False],
|
||||
message_roles=["user"],
|
||||
)
|
||||
|
||||
def render_ids(self, messages, *, tools=None, add_generation_prompt=False):
|
||||
return self.render(
|
||||
@@ -24,18 +39,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,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
@@ -53,8 +72,8 @@ class _FakeClient:
|
||||
self.calls.append(
|
||||
{"path": path, "cast_to": cast_to, "body": body, "options": options}
|
||||
)
|
||||
routed_experts = np.array([[[1]], [[2]]], dtype=np.int32)
|
||||
return {
|
||||
routed_experts = np.array([[[1]], [[2]]], dtype=np.uint8)
|
||||
payload = {
|
||||
"request_id": "gen-test",
|
||||
"choices": [
|
||||
{
|
||||
@@ -68,7 +87,7 @@ class _FakeClient:
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
"routed_experts": {
|
||||
"data": base64.b85encode(routed_experts.tobytes()).decode(
|
||||
"data": base64.b64encode(routed_experts.tobytes()).decode(
|
||||
"ascii"
|
||||
),
|
||||
"shape": list(routed_experts.shape),
|
||||
@@ -76,15 +95,20 @@ class _FakeClient:
|
||||
}
|
||||
],
|
||||
}
|
||||
return httpx.Response(
|
||||
200,
|
||||
content=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
|
||||
)
|
||||
|
||||
|
||||
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,10 +117,17 @@ 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.
|
||||
assert client.calls[0]["path"] == "http://fake-host:8000/inference/v1/generate"
|
||||
assert client.calls[0]["cast_to"] is httpx.Response
|
||||
assert client.calls[0]["body"] == {
|
||||
"model": "test-model",
|
||||
"token_ids": [1, 2, 3],
|
||||
@@ -111,26 +142,74 @@ 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"]["shape"] == [2, 1, 1]
|
||||
assert isinstance(result["routed_experts"]["data"], memoryview)
|
||||
assert result["routed_experts"]["data"].tobytes() == base64.b64encode(b"\x01\x02")
|
||||
assert result["multi_modal_data"] is None
|
||||
assert result["request_id"] == "gen-test"
|
||||
# Per-token attribution from the renderer surfaces on the result so
|
||||
# downstream consumers (verifiers RendererClient → prime-rl) can
|
||||
# build selective loss masks without a second render pass.
|
||||
attr = result["prompt_attribution"]
|
||||
assert attr is not None
|
||||
assert isinstance(attr, RenderedTokens)
|
||||
assert attr.token_ids == [1, 2, 3]
|
||||
assert attr.is_content == [False, True, False]
|
||||
assert attr.sampled_mask == [False, False, False]
|
||||
assert attr.message_indices == [0, 0, -1]
|
||||
assert attr.message_roles == ["user"]
|
||||
assert len(result["tool_calls"]) == 1
|
||||
tc = result["tool_calls"][0]
|
||||
assert tc.name == "echo"
|
||||
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):
|
||||
@@ -156,6 +235,44 @@ def test_generate_uses_prebuilt_prompt_ids_without_rendering():
|
||||
|
||||
assert client.calls[0]["body"]["token_ids"] == [11, 12, 13]
|
||||
assert result["prompt_ids"] == [11, 12, 13]
|
||||
# Pre-built prompt without explicit attribution → ``None`` carried
|
||||
# through. Consumers fall back to whatever attribution-free path
|
||||
# they have (e.g. uniform completion mask).
|
||||
assert result["prompt_attribution"] is None
|
||||
|
||||
|
||||
def test_generate_threads_prompt_attribution_through_prebuilt_prompt_path():
|
||||
"""When the caller passes both ``prompt_ids`` and ``prompt_attribution``
|
||||
(the multi-turn bridge path in verifiers), ``generate`` must thread
|
||||
the attribution through to the result dict unchanged — no re-rendering,
|
||||
no per-token reshuffling. Lets downstream consumers carry the
|
||||
renderer's body/scaffold cut into the trajectory step without an
|
||||
extra render pass."""
|
||||
client = _FakeClient()
|
||||
# Caller-supplied attribution; mirrors what
|
||||
# ``RendererClient._get_incremental_prompt_ids`` returns from the
|
||||
# bridge_to_next_turn output.
|
||||
supplied = RenderedTokens(
|
||||
token_ids=[11, 12, 13],
|
||||
message_indices=[-1, 0, 0],
|
||||
sampled_mask=[False, False, False],
|
||||
is_content=[False, True, True],
|
||||
message_roles=["tool"],
|
||||
)
|
||||
|
||||
result = asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=_NoRenderRenderer(),
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
prompt_ids=[11, 12, 13],
|
||||
prompt_attribution=supplied,
|
||||
)
|
||||
)
|
||||
|
||||
# Exact passthrough — same object, no copy / no transform.
|
||||
assert result["prompt_attribution"] is supplied
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -163,30 +280,42 @@ def test_generate_uses_prebuilt_prompt_ids_without_rendering():
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_generate_serializes_multimodal_features_for_qwen3_vl():
|
||||
@pytest.mark.parametrize(
|
||||
"model_id,renderer_class_path",
|
||||
[
|
||||
("Qwen/Qwen3-VL-4B-Instruct", "renderers.qwen3_vl:Qwen3VLRenderer"),
|
||||
("Qwen/Qwen3.5-2B", "renderers.qwen35:Qwen35Renderer"),
|
||||
],
|
||||
ids=["qwen3_vl", "qwen35"],
|
||||
)
|
||||
def test_generate_serializes_multimodal_features_for_qwen_vl_family(
|
||||
model_id, renderer_class_path
|
||||
):
|
||||
"""When the renderer emits ``MultiModalData``, ``generate`` translates
|
||||
it into vLLM's ``features`` payload (mm_hashes + mm_placeholders +
|
||||
base64-encoded kwargs_data) and sticks it in the request body."""
|
||||
import pytest as _pytest
|
||||
base64-encoded kwargs_data) and sticks it in the request body. Covers
|
||||
every renderer routed through ``_build_qwen_vl_features``."""
|
||||
import importlib
|
||||
|
||||
_pytest.importorskip("torch")
|
||||
_pytest.importorskip("vllm", reason="vllm needed for features serialization")
|
||||
pytest.importorskip("torch")
|
||||
pytest.importorskip("vllm", reason="vllm needed for features serialization")
|
||||
|
||||
import torch as _torch
|
||||
|
||||
from renderers.base import (
|
||||
MultiModalData,
|
||||
PlaceholderRange,
|
||||
load_tokenizer,
|
||||
)
|
||||
from renderers.qwen3_vl import Qwen3VLRenderer
|
||||
|
||||
# Build a minimal real Qwen3VLRenderer so type dispatch in
|
||||
mod_name, cls_name = renderer_class_path.split(":")
|
||||
renderer_cls = getattr(importlib.import_module(mod_name), cls_name)
|
||||
|
||||
# Build a minimal real renderer so type dispatch in
|
||||
# _build_mm_features hits the qwen branch. The tokenizer is only
|
||||
# touched in __init__ to grab special-token ids; render() / etc.
|
||||
# aren't called here because we pre-supply prompt_ids + mm_data.
|
||||
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
|
||||
renderer = Qwen3VLRenderer(tokenizer)
|
||||
tokenizer = load_tokenizer(model_id)
|
||||
renderer = renderer_cls(tokenizer)
|
||||
|
||||
# Two synthetic 1×2×2 images. Field factory expects pixel_values
|
||||
# shape ``(sum_HW, embed_dim)`` and grid_thw shape ``(N, 3)``; the
|
||||
@@ -240,3 +369,136 @@ def test_generate_serializes_multimodal_features_for_qwen3_vl():
|
||||
# Items are base64 strings (encode_mm_kwargs_item output).
|
||||
for item in features["kwargs_data"]["image"]:
|
||||
assert isinstance(item, str) and len(item) > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompt overflow handling.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _LongRenderer(_FakeRenderer):
|
||||
"""Renders a 10-token prompt regardless of input — enough to overflow a
|
||||
small ``max_prompt_len``."""
|
||||
|
||||
def render(self, messages, *, tools=None, add_generation_prompt=False):
|
||||
from renderers.base import RenderedTokens
|
||||
|
||||
return RenderedTokens(token_ids=list(range(10)))
|
||||
|
||||
|
||||
def test_generate_raises_overlong_prompt_when_explicit_cap_exceeded():
|
||||
"""Pre-flight overflow check: when an explicit ``max_prompt_len`` is set
|
||||
and the rendered prompt is longer, ``generate`` raises
|
||||
``OverlongPromptError`` without dispatching the request to the engine."""
|
||||
from renderers.client import OverlongPromptError
|
||||
|
||||
client = _FakeClient()
|
||||
renderer = _LongRenderer()
|
||||
|
||||
with pytest.raises(OverlongPromptError) as excinfo:
|
||||
asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=renderer,
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
max_prompt_len=4,
|
||||
)
|
||||
)
|
||||
|
||||
assert excinfo.value.prompt_len == 10
|
||||
assert excinfo.value.max_prompt_len == 4
|
||||
assert client.calls == [], "request must not be dispatched on pre-flight fail"
|
||||
|
||||
|
||||
def test_generate_allows_prompt_at_max_prompt_len():
|
||||
"""A prompt exactly equal to ``max_prompt_len`` is allowed (the check is
|
||||
strict ``>``); only longer prompts trip the pre-flight."""
|
||||
client = _FakeClient()
|
||||
renderer = _LongRenderer()
|
||||
|
||||
result = asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=renderer,
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
max_prompt_len=10,
|
||||
)
|
||||
)
|
||||
|
||||
assert len(client.calls) == 1
|
||||
assert result["prompt_ids"] == list(range(10))
|
||||
|
||||
|
||||
def test_generate_auto_discovers_max_prompt_len_from_models_endpoint():
|
||||
"""When ``max_prompt_len`` is ``None`` (default), ``generate`` discovers
|
||||
the cap via ``GET /v1/models`` and reads ``ModelCard.max_model_len``.
|
||||
The result is cached per ``(base_url, model)`` so subsequent calls
|
||||
don't re-query."""
|
||||
from renderers.client import OverlongPromptError, _max_prompt_len_cache
|
||||
|
||||
class _ClientWithModels(_FakeClient):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.base_url = "http://disco-host:8000/v1"
|
||||
self.models_calls = 0
|
||||
|
||||
async def get(self, path, *, cast_to):
|
||||
self.models_calls += 1
|
||||
assert path == "/models"
|
||||
return {
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id": "test-model", "max_model_len": 4},
|
||||
{"id": "other", "max_model_len": 999},
|
||||
],
|
||||
}
|
||||
|
||||
# Clear cache so this test isn't affected by earlier ones.
|
||||
_max_prompt_len_cache.clear()
|
||||
|
||||
client = _ClientWithModels()
|
||||
renderer = _LongRenderer()
|
||||
|
||||
with pytest.raises(OverlongPromptError) as excinfo:
|
||||
asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=renderer,
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
)
|
||||
)
|
||||
|
||||
assert excinfo.value.max_prompt_len == 4
|
||||
assert excinfo.value.prompt_len == 10
|
||||
assert client.models_calls == 1, "lookup must hit /models once"
|
||||
assert client.calls == [], "pre-flight must short-circuit the request"
|
||||
|
||||
|
||||
def test_generate_caches_max_prompt_len_lookup_failure():
|
||||
"""When ``GET /v1/models`` fails (e.g. mock client without ``.get``),
|
||||
the lookup result is cached as ``None`` and the pre-flight quietly
|
||||
disables — the request still goes through, callers fall back to
|
||||
whatever reactive overflow handling they have."""
|
||||
from renderers.client import _max_prompt_len_cache
|
||||
|
||||
# _FakeClient has no .get method → AttributeError → cached None.
|
||||
_max_prompt_len_cache.clear()
|
||||
client = _FakeClient()
|
||||
client.base_url = "http://no-models:8000/v1"
|
||||
|
||||
result = asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=_LongRenderer(),
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
)
|
||||
)
|
||||
|
||||
# Request was dispatched (no pre-flight rejection) and round-tripped.
|
||||
assert len(client.calls) == 1
|
||||
assert result["prompt_ids"] == list(range(10))
|
||||
assert _max_prompt_len_cache[("http://no-models:8000/v1", "test-model")] is None
|
||||
|
||||
@@ -33,6 +33,7 @@ from openai_harmony import (
|
||||
ToolDescription,
|
||||
load_harmony_encoding,
|
||||
)
|
||||
from renderers.configs import GptOssRendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
@@ -49,7 +50,9 @@ def tokenizer():
|
||||
def renderer(tokenizer):
|
||||
# Pin the date so the rendered preamble matches the harmony oracle
|
||||
# built with the same fixed date.
|
||||
return GptOssRenderer(tokenizer, conversation_start_date=DATE_FOR_PARITY)
|
||||
return GptOssRenderer(
|
||||
tokenizer, GptOssRendererConfig(conversation_start_date=DATE_FOR_PARITY)
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
"""Per-token ``RenderedTokens.is_content`` invariants.
|
||||
|
||||
``is_content[k]`` answers "does ``token_ids[k]`` come from message body
|
||||
bytes (caller-provided content / tool_calls / reasoning_content, or
|
||||
the model's sampled emission for the assistant role) or is it template
|
||||
scaffolding the renderer added around the body (role tags, special
|
||||
tokens, separators, tool-response wraps, generation prompt)?"
|
||||
|
||||
By design ``is_content`` is a superset of ``sampled_mask``:
|
||||
|
||||
- Equal on every token attributed to an assistant message (sampled ==
|
||||
body for that role by construction).
|
||||
- Carries new information on every other role: the model never samples
|
||||
user / tool / system tokens, so ``sampled_mask`` is uniformly
|
||||
``False`` over those — ``is_content`` differentiates body from wrap.
|
||||
|
||||
These tests parametrise across every renderer in
|
||||
``conftest.RENDERER_MODELS`` and verify the contract for hand-coded
|
||||
renderers. ``DefaultRenderer`` leaves ``is_content`` empty by design
|
||||
(the Jinja template is opaque, so the renderer cannot know the
|
||||
wrap/body split) and is exempt from the populated-length check.
|
||||
|
||||
The body-bytes decode invariant uses ``in`` (substring) rather than
|
||||
strict equality because some renderers normalise whitespace, strip
|
||||
trailing newlines, etc. within the message body emit — but the
|
||||
caller-provided content must always be recoverable as a substring of
|
||||
the decoded body run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _is_populated(rendered) -> bool:
|
||||
return len(rendered.is_content) == len(rendered.token_ids) and bool(
|
||||
rendered.is_content
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_length_or_empty(model_name, renderer):
|
||||
"""``is_content`` is either empty (opt-out) or matches token_ids
|
||||
length exactly. No partial fills."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
n_tokens = len(rendered.token_ids)
|
||||
n_mask = len(rendered.is_content)
|
||||
assert n_mask == 0 or n_mask == n_tokens, (
|
||||
f"{model_name}: is_content length {n_mask} must be 0 or match "
|
||||
f"token_ids length {n_tokens}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_equals_sampled_on_assistant(model_name, renderer):
|
||||
"""On every token attributed to an assistant message,
|
||||
``is_content[k] == sampled_mask[k]``. The two signals collapse on
|
||||
that role by design — the model's sampled output IS the assistant
|
||||
message's body, and the surrounding scaffold is neither sampled
|
||||
nor body."""
|
||||
msgs = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello world!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
if len(rendered.sampled_mask) != len(rendered.token_ids):
|
||||
return # renderer opts out of sampled_mask
|
||||
|
||||
mismatches = []
|
||||
for k, msg_idx in enumerate(rendered.message_indices):
|
||||
if msg_idx < 0:
|
||||
continue
|
||||
if msgs[msg_idx].get("role") != "assistant":
|
||||
continue
|
||||
if rendered.is_content[k] != rendered.sampled_mask[k]:
|
||||
mismatches.append((k, rendered.is_content[k], rendered.sampled_mask[k]))
|
||||
assert not mismatches, (
|
||||
f"{model_name}: is_content != sampled_mask on assistant tokens "
|
||||
f"(k, is_content, sampled): {mismatches[:8]}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_excludes_generation_prompt(model_name, renderer):
|
||||
"""All generation-prompt tokens (msg_idx=-1) are scaffold — the
|
||||
next-turn opener the chat template injects so the model can
|
||||
continue. ``is_content`` must be False over that entire span."""
|
||||
msgs = [{"role": "user", "content": "Hi"}]
|
||||
rendered = renderer.render(msgs, add_generation_prompt=True)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
bad = [
|
||||
k
|
||||
for k, (msg_idx, is_content) in enumerate(
|
||||
zip(rendered.message_indices, rendered.is_content)
|
||||
)
|
||||
if msg_idx == -1 and is_content
|
||||
]
|
||||
assert not bad, (
|
||||
f"{model_name}: generation-prompt tokens marked is_content=True "
|
||||
f"at positions {bad[:8]}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_recovers_user_body(model_name, tokenizer, renderer):
|
||||
"""The decoded run of is_content=True tokens within a user message
|
||||
contains the user's original content. ``in`` rather than equality
|
||||
because some templates normalise whitespace inside the body emit;
|
||||
the input substring must still be recoverable from the decoded
|
||||
body run."""
|
||||
user_text = "Hello, my name is Sebastian."
|
||||
msgs = [
|
||||
{"role": "user", "content": user_text},
|
||||
{"role": "assistant", "content": "Hi!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
user_body_ids = [
|
||||
tid
|
||||
for tid, mi, ic in zip(
|
||||
rendered.token_ids, rendered.message_indices, rendered.is_content
|
||||
)
|
||||
if mi == 0 and ic
|
||||
]
|
||||
assert user_body_ids, (
|
||||
f"{model_name}: no is_content=True tokens attributed to user message"
|
||||
)
|
||||
decoded = tokenizer.decode(user_body_ids).strip()
|
||||
assert user_text in decoded or decoded in user_text, (
|
||||
f"{model_name}: user body run decodes to {decoded!r}, "
|
||||
f"expected to contain {user_text!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_recovers_tool_body(model_name, tokenizer, renderer):
|
||||
"""The decoded run of is_content=True tokens within a tool message
|
||||
contains the tool response body. The whole point of the body/wrap
|
||||
cut: SFT on this run trains the model to anticipate tool outputs
|
||||
without learning to emit the surrounding ``<|tool_response>`` /
|
||||
role-tag scaffold (which would interrupt a real rollout)."""
|
||||
tool_text = "The capital of France is Paris."
|
||||
msgs = [
|
||||
{"role": "user", "content": "What's the capital of France?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"id": "call_1",
|
||||
"function": {
|
||||
"name": "lookup",
|
||||
"arguments": {"q": "capital of France"},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": tool_text, "tool_call_id": "call_1"},
|
||||
{"role": "assistant", "content": "Paris."},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
tool_body_ids = [
|
||||
tid
|
||||
for tid, mi, ic in zip(
|
||||
rendered.token_ids, rendered.message_indices, rendered.is_content
|
||||
)
|
||||
if mi == 2 and ic
|
||||
]
|
||||
assert tool_body_ids, (
|
||||
f"{model_name}: no is_content=True tokens attributed to tool message"
|
||||
)
|
||||
decoded = tokenizer.decode(tool_body_ids).strip()
|
||||
assert tool_text in decoded, (
|
||||
f"{model_name}: tool body run decodes to {decoded!r}, "
|
||||
f"expected to contain {tool_text!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_recovers_system_body(model_name, tokenizer, renderer):
|
||||
"""The decoded run of is_content=True tokens within a system
|
||||
message contains the caller-provided system content. Tools header
|
||||
/ footer (if present) are scaffold and never appear as body."""
|
||||
sys_text = "You are an unusually precise assistant."
|
||||
msgs = [
|
||||
{"role": "system", "content": sys_text},
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hi!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
sys_body_ids = [
|
||||
tid
|
||||
for tid, mi, ic in zip(
|
||||
rendered.token_ids, rendered.message_indices, rendered.is_content
|
||||
)
|
||||
if mi == 0 and ic
|
||||
]
|
||||
assert sys_body_ids, (
|
||||
f"{model_name}: no is_content=True tokens attributed to system message"
|
||||
)
|
||||
decoded = tokenizer.decode(sys_body_ids).strip()
|
||||
assert sys_text in decoded, (
|
||||
f"{model_name}: system body run decodes to {decoded!r}, "
|
||||
f"expected to contain {sys_text!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_is_content_no_body_on_role_tag(model_name, renderer):
|
||||
"""The first token attributed to a user/system/tool message must
|
||||
have ``is_content=False`` — that's the leading role-tag run
|
||||
(``<|im_start|>`` / equivalent), which is template scaffold, never
|
||||
body."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
user_positions = [k for k, idx in enumerate(rendered.message_indices) if idx == 0]
|
||||
assert user_positions, f"{model_name}: no tokens attributed to user message"
|
||||
first_k = user_positions[0]
|
||||
assert not rendered.is_content[first_k], (
|
||||
f"{model_name}: first user-attributed token at k={first_k} should "
|
||||
f"be is_content=False (role-tag scaffolding), but was True"
|
||||
)
|
||||
|
||||
|
||||
def test_content_token_spans_by_role_isolates_tool_body(
|
||||
model_name, tokenizer, renderer
|
||||
):
|
||||
"""``content_token_spans_by_role()["tool"]`` returns spans over
|
||||
which every token is the tool message body. Joining the decoded
|
||||
spans recovers the tool response. Adjacent scaffold tokens
|
||||
(``<|tool_response>``, role-tag openers) are never inside any
|
||||
returned span."""
|
||||
tool_text = "Result: 42"
|
||||
msgs = [
|
||||
{"role": "user", "content": "What's 6*7?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"id": "call_x",
|
||||
"function": {"name": "calc", "arguments": {"e": "6*7"}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": tool_text, "tool_call_id": "call_x"},
|
||||
{"role": "assistant", "content": "42."},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
spans = rendered.content_token_spans_by_role()
|
||||
tool_spans = spans.get("tool") or []
|
||||
assert tool_spans, f"{model_name}: no tool content spans returned"
|
||||
|
||||
pieces: list[str] = []
|
||||
for s, e in tool_spans:
|
||||
run_ids = rendered.token_ids[s:e]
|
||||
# All tokens in the span must be is_content=True by definition.
|
||||
for k in range(s, e):
|
||||
assert rendered.is_content[k], (
|
||||
f"{model_name}: span {(s, e)} contains is_content=False at k={k}"
|
||||
)
|
||||
pieces.append(tokenizer.decode(run_ids))
|
||||
joined = "".join(pieces).strip()
|
||||
assert tool_text in joined, (
|
||||
f"{model_name}: joined tool spans decode to {joined!r}, "
|
||||
f"expected to contain {tool_text!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_content_mask_for_roles_excludes_assistant_when_unset(model_name, renderer):
|
||||
"""``content_mask_for_roles({"tool"})`` returns a mask that's True
|
||||
only on tool body tokens — never on assistant tokens, even though
|
||||
those also have ``is_content=True``. The role filter is the whole
|
||||
point: SFT-on-tool-body must not bleed into the assistant span."""
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"id": "call_a",
|
||||
"function": {"name": "ping", "arguments": {}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "pong", "tool_call_id": "call_a"},
|
||||
{"role": "assistant", "content": "OK."},
|
||||
]
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
tool_mask = rendered.content_mask_for_roles({"tool"})
|
||||
assert len(tool_mask) == len(rendered.token_ids)
|
||||
|
||||
for k, mi in enumerate(rendered.message_indices):
|
||||
if mi < 0:
|
||||
assert not tool_mask[k], (
|
||||
f"{model_name}: scaffold token k={k} (msg_idx=-1) marked in tool mask"
|
||||
)
|
||||
continue
|
||||
role = msgs[mi].get("role")
|
||||
if role != "tool" and tool_mask[k]:
|
||||
raise AssertionError(
|
||||
f"{model_name}: tool-role mask True on a {role!r} token at k={k}"
|
||||
)
|
||||
|
||||
|
||||
def test_build_training_sample_content_sft_roles_picks_up_tool_body(
|
||||
model_name, renderer
|
||||
):
|
||||
"""``build_training_sample(..., content_sft_roles={"tool"})``
|
||||
produces a loss mask that's True on tool body tokens AND assistant
|
||||
sampled tokens, but False on the tool-message scaffold (role tag,
|
||||
``<|tool_response>`` wraps, separators). The canonical
|
||||
SFT-on-tool-body + RL-on-assistant composition."""
|
||||
from renderers import build_training_sample
|
||||
|
||||
msgs = [
|
||||
{"role": "user", "content": "Hi"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"type": "function",
|
||||
"id": "call_z",
|
||||
"function": {"name": "noop", "arguments": {}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": "done", "tool_call_id": "call_z"},
|
||||
{"role": "assistant", "content": "OK."},
|
||||
]
|
||||
ids, mask = build_training_sample(
|
||||
renderer,
|
||||
msgs,
|
||||
role_to_mask=lambda m: m["role"] == "assistant",
|
||||
content_sft_roles={"tool"},
|
||||
)
|
||||
assert len(mask) == len(ids)
|
||||
|
||||
# We need at least one trainable tool-body token if the renderer
|
||||
# populates is_content. Renderers that opt out (empty is_content)
|
||||
# fall back to the existing role_to_mask behaviour, which leaves
|
||||
# tool tokens False — that's the documented fallback and is fine.
|
||||
rendered = renderer.render(msgs)
|
||||
if not _is_populated(rendered):
|
||||
return
|
||||
|
||||
trainable_per_role: dict[str, int] = {}
|
||||
for k, mi in enumerate(rendered.message_indices):
|
||||
if mi < 0:
|
||||
continue
|
||||
if mask[k]:
|
||||
r = msgs[mi].get("role") or ""
|
||||
trainable_per_role[r] = trainable_per_role.get(r, 0) + 1
|
||||
|
||||
assert trainable_per_role.get("tool", 0) > 0, (
|
||||
f"{model_name}: build_training_sample with content_sft_roles={{'tool'}} "
|
||||
f"trained on zero tool tokens"
|
||||
)
|
||||
assert trainable_per_role.get("assistant", 0) > 0, (
|
||||
f"{model_name}: assistant tokens dropped from training mask"
|
||||
)
|
||||
assert trainable_per_role.get("user", 0) == 0, (
|
||||
f"{model_name}: user tokens leaked into training mask: {trainable_per_role}"
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Kimi K2.5 tool-schema TypeScript rendering: bool/null literal correctness.
|
||||
|
||||
Regression for PR #55: ``_function_to_typescript`` used to leak Python
|
||||
literals (``True`` / ``False`` / ``None``) into output advertised as
|
||||
TypeScript. Both call sites — ``_EnumType.to_typescript_style`` (for
|
||||
non-string enum members) and ``_TypedParam.to_typescript_style`` (for
|
||||
bool defaults) — now route non-string values through ``json.dumps`` so
|
||||
booleans and ``None`` render as ``true`` / ``false`` / ``null``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from renderers.kimi_k25 import _function_to_typescript
|
||||
|
||||
|
||||
def test_bool_default_renders_as_json_literal():
|
||||
"""Bool defaults must render as ``true`` / ``false``, not ``True`` / ``False``."""
|
||||
out = _function_to_typescript(
|
||||
{
|
||||
"name": "set_logging",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"verbose": {"type": "boolean", "default": True},
|
||||
"quiet": {"type": "boolean", "default": False},
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
assert "// Default: true" in out
|
||||
assert "// Default: false" in out
|
||||
assert "Default: True" not in out
|
||||
assert "Default: False" not in out
|
||||
|
||||
|
||||
def test_enum_non_string_members_render_as_json_literals():
|
||||
"""``null`` / bool / int enum members must render as JSON literals, not Python ``repr``."""
|
||||
out = _function_to_typescript(
|
||||
{
|
||||
"name": "set_mode",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {"enum": ["auto", None, True, False, 0]},
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
assert '"auto" | null | true | false | 0' in out
|
||||
# Python literals must not leak through.
|
||||
assert "None" not in out
|
||||
assert "True" not in out
|
||||
assert "False" not in out
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Coverage for the fastokens fast-path in ``renderers.base.load_tokenizer``.
|
||||
|
||||
``load_tokenizer`` defaults to routing every supported model through
|
||||
``fastokens.patch_transformers()`` for ~10x faster encode. Models in
|
||||
``FASTOKENS_INCOMPATIBLE`` skip the patch (DeepSeek's Metaspace
|
||||
pretokenizer isn't supported). Callers can opt out per-call with
|
||||
``use_fastokens=False``.
|
||||
|
||||
These tests pin the policy:
|
||||
|
||||
1. The denylist contains the empirically-verified incompat models —
|
||||
adding to it should be a deliberate review action.
|
||||
2. With ``use_fastokens=True`` (the default) on a compatible model, the
|
||||
resulting tokenizer's backend is the fastokens shim. Encode output
|
||||
stays byte-identical to vanilla.
|
||||
3. With ``use_fastokens=False``, the resulting tokenizer is vanilla.
|
||||
4. For incompat models, the fast path is silently skipped and the
|
||||
tokenizer still loads + encodes correctly.
|
||||
5. The fastokens patch is removed immediately after the load so it
|
||||
doesn't leak into the caller's process — subsequent
|
||||
``AutoTokenizer.from_pretrained`` calls outside ``load_tokenizer``
|
||||
use vanilla.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from renderers.base import (
|
||||
FASTOKENS_INCOMPATIBLE,
|
||||
load_tokenizer,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Denylist shape
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_fastokens_incompatible_is_explicit_set():
|
||||
"""The denylist is small and audited — pinning the exact contents
|
||||
catches accidental drift. Adding/removing entries should be a
|
||||
deliberate action with a parity probe."""
|
||||
assert FASTOKENS_INCOMPATIBLE == frozenset(
|
||||
{
|
||||
"deepseek-ai/DeepSeek-V3",
|
||||
"deepseek-ai/DeepSeek-V3-Base",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fast path (compatible model — Qwen3.5-9B as representative)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
_FAST_MODEL = "Qwen/Qwen3.5-9B"
|
||||
|
||||
|
||||
def _backend_class_name(tok) -> str:
|
||||
"""Return the class name of the underlying backend object so tests
|
||||
can tell vanilla from fastokens-shimmed tokenizers."""
|
||||
backend = getattr(tok, "_tokenizer", None)
|
||||
return type(backend).__name__ if backend is not None else type(tok).__name__
|
||||
|
||||
|
||||
def test_default_uses_fastokens_on_compatible_model():
|
||||
tok = load_tokenizer(_FAST_MODEL)
|
||||
# The shim type is named ``_TokenizerShim`` (see fastokens._compat);
|
||||
# match by name so we don't import private fastokens internals.
|
||||
assert "Shim" in _backend_class_name(tok), (
|
||||
f"Expected fastokens shim backend, got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_explicit_off_returns_vanilla_backend():
|
||||
tok = load_tokenizer(_FAST_MODEL, use_fastokens=False)
|
||||
assert "Shim" not in _backend_class_name(tok), (
|
||||
f"Expected vanilla backend, got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_fast_and_vanilla_encode_identically_on_compatible_model():
|
||||
fast = load_tokenizer(_FAST_MODEL)
|
||||
vanilla = load_tokenizer(_FAST_MODEL, use_fastokens=False)
|
||||
samples = [
|
||||
"Hello, world!",
|
||||
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
|
||||
"🌍 emoji + 中文 + tabs\there",
|
||||
" ".join([f"word_{i}" for i in range(50)]),
|
||||
]
|
||||
for s in samples:
|
||||
assert fast.encode(s, add_special_tokens=False) == vanilla.encode(
|
||||
s, add_special_tokens=False
|
||||
), f"encode diverged on {s!r}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Denylist: incompat models silently skip the patch and still load.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", sorted(FASTOKENS_INCOMPATIBLE))
|
||||
def test_incompat_model_loads_via_vanilla_backend(model):
|
||||
"""For models we know diverge / fail under fastokens, the fast path
|
||||
must be skipped so the load still succeeds with a vanilla backend."""
|
||||
if "DeepSeek" in model:
|
||||
# Skip if upstream gating / size makes the load impractical here.
|
||||
# We only care that the path doesn't try fastokens. Probe the
|
||||
# tokenizer_config to make sure the repo is reachable; if not,
|
||||
# skip rather than fail (CI without HF auth, network issues).
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
try:
|
||||
HfApi().repo_info(model)
|
||||
except Exception as e:
|
||||
pytest.skip(f"{model}: repo unreachable in this env ({e})")
|
||||
tok = load_tokenizer(model)
|
||||
assert "Shim" not in _backend_class_name(tok), (
|
||||
f"{model}: should NOT have been patched; got {_backend_class_name(tok)!r}"
|
||||
)
|
||||
# And it still encodes.
|
||||
ids = tok.encode("hello", add_special_tokens=False)
|
||||
assert len(ids) > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Patch must not leak: AutoTokenizer.from_pretrained calls OUTSIDE
|
||||
# load_tokenizer should still produce a vanilla tokenizer.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_patch_is_unloaded_after_call():
|
||||
"""``load_tokenizer`` brackets the fastokens patch. After it returns
|
||||
a fastokens-shimmed tokenizer, a fresh ``AutoTokenizer.from_pretrained``
|
||||
call must NOT pick up the patch — the user's process stays clean."""
|
||||
fast = load_tokenizer(_FAST_MODEL)
|
||||
assert "Shim" in _backend_class_name(fast), "preconditions: fast path active"
|
||||
|
||||
# Now call AutoTokenizer.from_pretrained directly. It MUST be vanilla.
|
||||
direct = AutoTokenizer.from_pretrained(_FAST_MODEL, trust_remote_code=False)
|
||||
assert "Shim" not in _backend_class_name(direct), (
|
||||
f"fastokens patch leaked into user-side AutoTokenizer call: "
|
||||
f"got {_backend_class_name(direct)!r}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Failure-mode fallback: if fastokens raises during the patched load,
|
||||
# load_tokenizer falls back to vanilla without surfacing the error.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_fallback_on_fastokens_load_error(monkeypatch):
|
||||
"""Simulate fastokens raising during patched load — load_tokenizer
|
||||
should fall back to vanilla and return a working tokenizer."""
|
||||
import renderers.base as rb
|
||||
|
||||
def _boom(*args, **kwargs):
|
||||
raise ValueError("simulated fastokens failure: unsupported pre-tokenizer")
|
||||
|
||||
monkeypatch.setattr(rb, "_patched_load", _boom)
|
||||
|
||||
tok = load_tokenizer(_FAST_MODEL) # default use_fastokens=True
|
||||
# The vanilla fallback ran — backend is not a fastokens shim.
|
||||
assert "Shim" not in _backend_class_name(tok)
|
||||
# Still works.
|
||||
assert len(tok.encode("hi", add_special_tokens=False)) > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Print suppression: fastokens itself prints "[fastokens]
|
||||
# patch_transformers: ..." on every patch/unpatch call. Building a
|
||||
# RendererPool of size N would emit ~N lines (the pool factory calls
|
||||
# load_tokenizer once per slot). load_tokenizer swallows that stdout
|
||||
# chatter and emits a single INFO log on the first patch instead.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_no_fastokens_stdout_chatter(capsys, caplog):
|
||||
"""``load_tokenizer`` must not leak ``[fastokens]`` prints onto
|
||||
stdout, and must emit exactly one INFO log per process announcing
|
||||
the fast path (not once per call)."""
|
||||
import logging
|
||||
|
||||
import renderers.base as rb
|
||||
|
||||
# Reset the process-wide "announced" flag so this test sees the
|
||||
# first-call log even if another test loaded a tokenizer earlier.
|
||||
rb._FASTOKENS_ANNOUNCED = False
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="renderers.base"):
|
||||
load_tokenizer(_FAST_MODEL)
|
||||
load_tokenizer(_FAST_MODEL)
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert "[fastokens]" not in captured.out, (
|
||||
f"fastokens print leaked to stdout: {captured.out!r}"
|
||||
)
|
||||
assert "[fastokens]" not in captured.err, (
|
||||
f"fastokens print leaked to stderr: {captured.err!r}"
|
||||
)
|
||||
|
||||
fastokens_info = [
|
||||
r for r in caplog.records if "fastokens enabled" in r.getMessage()
|
||||
]
|
||||
assert len(fastokens_info) == 1, (
|
||||
f"expected exactly one fastokens INFO log across two loads, "
|
||||
f"got {len(fastokens_info)}"
|
||||
)
|
||||
@@ -99,7 +99,7 @@ def test_kimi_k2_unknown_role_message_indices():
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer("moonshotai/Kimi-K2-Instruct")
|
||||
renderer = create_renderer(tok, renderer="auto")
|
||||
renderer = create_renderer(tok)
|
||||
|
||||
msgs = [
|
||||
{"role": "user", "content": "hi"},
|
||||
|
||||
+389
-4
@@ -33,7 +33,16 @@ from renderers import (
|
||||
Qwen3VLRenderer,
|
||||
create_renderer,
|
||||
)
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
|
||||
def _config_with_add_vision_id(model_name: str, add_vision_id: bool):
|
||||
"""Build the typed config for ``model_name`` (resolved via
|
||||
``MODEL_RENDERER_MAP``) with ``add_vision_id`` set. The qwen_vl
|
||||
family — Qwen3.5 and Qwen3-VL — both expose this field."""
|
||||
renderer_name = MODEL_RENDERER_MAP[model_name]
|
||||
return _config_class_for(renderer_name)(add_vision_id=add_vision_id)
|
||||
|
||||
|
||||
pytest.importorskip("PIL", reason="Pillow required for multimodal tests")
|
||||
@@ -111,7 +120,7 @@ def _load_processor_and_renderer(model_name: str):
|
||||
)
|
||||
else:
|
||||
processor = AutoProcessor.from_pretrained(model_name)
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
# Inject processor so the renderer doesn't try to fetch it lazily.
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
@@ -299,11 +308,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]
|
||||
)
|
||||
@@ -505,7 +645,7 @@ def test_modality_registry_models_route_to_renderer():
|
||||
if not _hf_snapshot_cached(model_name):
|
||||
continue
|
||||
tokenizer = load_tokenizer(model_name)
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
# We expect a hand-coded VL renderer, not the default fallback.
|
||||
assert not type(renderer).__name__.startswith("Default"), (
|
||||
f"{model_name} routed to DefaultRenderer despite being in "
|
||||
@@ -513,6 +653,214 @@ 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 _qwen_vl_processor_input_ids_with_kwargs(
|
||||
processor, messages, add_gp, **template_kwargs
|
||||
):
|
||||
"""Variant of ``_qwen_vl_processor_input_ids`` that forwards
|
||||
``template_kwargs`` to ``apply_chat_template`` so the parity oracle
|
||||
can exercise the same typed-config template field the renderer was
|
||||
constructed with (e.g. ``add_vision_id=True``).
|
||||
"""
|
||||
text = processor.apply_chat_template(
|
||||
messages,
|
||||
tokenize=False,
|
||||
add_generation_prompt=add_gp,
|
||||
**template_kwargs,
|
||||
)
|
||||
images = []
|
||||
for msg in messages:
|
||||
content = msg.get("content")
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for item in content:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if (
|
||||
item.get("type") in ("image", "image_url")
|
||||
or "image" in item
|
||||
or "image_url" in item
|
||||
):
|
||||
if "image" in item and not isinstance(item["image"], dict):
|
||||
images.append(item["image"])
|
||||
return processor(images=images, text=text, return_tensors="pt")["input_ids"][
|
||||
0
|
||||
].tolist()
|
||||
|
||||
|
||||
# ``add_vision_id`` is exposed on the Qwen-VL family renderers
|
||||
# (Qwen3.5 / Qwen3.6 / Qwen3-VL) per the chat-template audit. Kimi K2.5
|
||||
# / K2.6's template has no equivalent toggle, so it's intentionally
|
||||
# absent from ``KimiK25RendererConfig`` and skipped here.
|
||||
_ADD_VISION_ID_CASES = [
|
||||
(m, mo) for m, mo in _CASES if mo == "image" and _detect_family(m) == "qwen_vl"
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mm_model_name,modality",
|
||||
_ADD_VISION_ID_CASES,
|
||||
ids=[f"{m}|{mo}" for m, mo in _ADD_VISION_ID_CASES],
|
||||
)
|
||||
@pytest.mark.parametrize("add_vision_id", [True, False])
|
||||
def test_add_vision_id_parity_vs_processor(
|
||||
mm_model_name, modality, add_vision_id, tiny_image
|
||||
):
|
||||
"""Parity for ``add_vision_id`` across image-bearing shapes.
|
||||
|
||||
When True, the renderer must prefix each image / video placeholder
|
||||
with ``Picture N: `` / ``Video N: `` matching the Jinja template's
|
||||
``image_count`` / ``video_count`` namespaces. When False, the
|
||||
prefix is suppressed entirely. Both branches must reproduce
|
||||
``processor.apply_chat_template(messages, add_vision_id=<value>)``
|
||||
token-for-token after image expansion.
|
||||
"""
|
||||
if not _hf_snapshot_cached(mm_model_name):
|
||||
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
|
||||
|
||||
kit = _modality_kit(modality, mm_model_name)
|
||||
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
|
||||
# Build a fresh renderer for the kwarg under test (the shared
|
||||
# fixture has ``add_vision_id=False`` baked in).
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
_config_with_add_vision_id(mm_model_name, add_vision_id),
|
||||
)
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
|
||||
for case in _build_cases(kit["make_part"], tiny_image):
|
||||
messages, add_gp = case.values
|
||||
ours = renderer.render_ids(messages, add_generation_prompt=add_gp)
|
||||
theirs = _qwen_vl_processor_input_ids_with_kwargs(
|
||||
processor, messages, add_gp, add_vision_id=add_vision_id
|
||||
)
|
||||
assert ours == theirs, (
|
||||
f"{mm_model_name} / add_vision_id={add_vision_id} / "
|
||||
f"case={case.id}: renderer diverges from processor.\n"
|
||||
f" ours[:80]={ours[:80]}\n theirs[:80]={theirs[:80]}\n"
|
||||
f" len(ours)={len(ours)} len(theirs)={len(theirs)}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mm_model_name,modality",
|
||||
_ADD_VISION_ID_CASES,
|
||||
ids=[f"{m}|{mo}" for m, mo in _ADD_VISION_ID_CASES],
|
||||
)
|
||||
def test_bridge_refuses_when_add_vision_id_loses_prior_count(
|
||||
mm_model_name, modality, tiny_image
|
||||
):
|
||||
"""When ``add_vision_id=True``, the bridge needs the prior turn's
|
||||
image / video count to keep the ``Picture N:`` numbering correct.
|
||||
The only source of that count for the bridged turn is
|
||||
``previous_multi_modal_data``; raw prior token ids don't carry it
|
||||
back unambiguously (``<|vision_start|>`` is shared between image
|
||||
and video placeholders).
|
||||
|
||||
If a caller omits ``previous_multi_modal_data`` on a conversation
|
||||
that already contains images, naively continuing the bridge would
|
||||
emit ``Picture 1:`` again for the new turn — diverging from
|
||||
``apply_chat_template`` and a full re-render. The bridge must
|
||||
refuse (return None) so the caller falls back to a full re-render.
|
||||
"""
|
||||
if not _hf_snapshot_cached(mm_model_name):
|
||||
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
|
||||
|
||||
kit = _modality_kit(modality, mm_model_name)
|
||||
tokenizer, processor, _ = _load_processor_and_renderer(mm_model_name)
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
_config_with_add_vision_id(mm_model_name, True),
|
||||
)
|
||||
if hasattr(renderer, "_processor") and renderer._processor is None:
|
||||
renderer._processor = processor
|
||||
|
||||
initial = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
kit["make_part"](tiny_image),
|
||||
{"type": "text", "text": "Turn one."},
|
||||
],
|
||||
}
|
||||
]
|
||||
new_messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
kit["make_part"](tiny_image),
|
||||
{"type": "text", "text": "Turn two."},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
initial_rendered = renderer.render(initial, add_generation_prompt=True)
|
||||
im_end_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
|
||||
completion_ids = tokenizer.encode("Saw it.", add_special_tokens=False) + [im_end_id]
|
||||
|
||||
# No previous_multi_modal_data → bridge must refuse so the caller
|
||||
# falls back to a full re-render (where the counter restarts from
|
||||
# the full message list and lands on Picture 2: correctly).
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
previous_prompt_ids=initial_rendered.token_ids,
|
||||
previous_completion_ids=completion_ids,
|
||||
new_messages=new_messages,
|
||||
)
|
||||
assert bridged is None, (
|
||||
f"{mm_model_name}: bridge should refuse when add_vision_id=True "
|
||||
"and previous_multi_modal_data is omitted but prior contains images"
|
||||
)
|
||||
|
||||
# With the prior mm_data threaded through, the bridge proceeds.
|
||||
bridged_ok = renderer.bridge_to_next_turn(
|
||||
previous_prompt_ids=initial_rendered.token_ids,
|
||||
previous_completion_ids=completion_ids,
|
||||
new_messages=new_messages,
|
||||
previous_multi_modal_data=initial_rendered.multi_modal_data,
|
||||
)
|
||||
assert bridged_ok is not None, (
|
||||
f"{mm_model_name}: bridge unexpectedly refused even with previous_multi_modal_data"
|
||||
)
|
||||
|
||||
|
||||
def test_qwen3_vl_renderer_exposes_image_modality():
|
||||
"""The flagship multimodal renderer is concretely Qwen3VLRenderer.
|
||||
|
||||
@@ -523,6 +871,43 @@ def test_qwen3_vl_renderer_exposes_image_modality():
|
||||
if not _hf_snapshot_cached(model):
|
||||
pytest.skip(f"{model}: HF snapshot not cached locally")
|
||||
tokenizer = load_tokenizer(model)
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
assert isinstance(renderer, Qwen3VLRenderer)
|
||||
assert "image" in MULTIMODAL_MODELS[model]
|
||||
|
||||
|
||||
def test_is_image_part_treats_type_field_as_authoritative():
|
||||
"""``Dataset.from_list`` unifies the Arrow schema across the elements
|
||||
of a list-typed column. A content list mixing text and image parts
|
||||
round-trips with ``image_url: None`` added to every text part (and
|
||||
``text: None`` added to every image part). The classifier must treat
|
||||
the ``type`` field as authoritative when present — falling back to
|
||||
a key-presence check on ``image_url`` would misclassify the text
|
||||
part and the renderer would later raise on ``_load_pil_image(None)``.
|
||||
"""
|
||||
from renderers.qwen3_vl import _is_image_part, _is_video_part
|
||||
|
||||
# Typed parts classify by their ``type``.
|
||||
assert _is_image_part(
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,XXX"}}
|
||||
)
|
||||
assert _is_image_part({"type": "image", "image": object()})
|
||||
assert _is_video_part(
|
||||
{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,XXX"}}
|
||||
)
|
||||
|
||||
# Schema-unified text parts — typed as text, with a None zombie key
|
||||
# for the sibling modality — must NOT classify as image / video.
|
||||
schema_unified_text = {"type": "text", "text": "hello", "image_url": None}
|
||||
assert not _is_image_part(schema_unified_text)
|
||||
assert not _is_video_part(schema_unified_text)
|
||||
schema_unified_text_with_video = {"type": "text", "text": "hi", "video_url": None}
|
||||
assert not _is_video_part(schema_unified_text_with_video)
|
||||
|
||||
# Untyped fallback only fires when ``type`` is absent, and requires
|
||||
# a truthy value (mere key presence isn't enough).
|
||||
assert _is_image_part({"image_url": {"url": "data:..."}})
|
||||
assert _is_image_part({"image": object()})
|
||||
assert not _is_image_part({"image_url": None})
|
||||
assert not _is_image_part({"image": None})
|
||||
assert not _is_video_part({"video_url": None})
|
||||
|
||||
@@ -7,13 +7,13 @@ 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
|
||||
def _qwen3_vl():
|
||||
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
@@ -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)
|
||||
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
|
||||
|
||||
@@ -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,16 @@ 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.
|
||||
"""
|
||||
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)
|
||||
|
||||
+51
-12
@@ -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)
|
||||
@@ -77,11 +114,12 @@ def test_think_reasoning_parser_no_block():
|
||||
|
||||
def test_default_renderer_uses_parsers():
|
||||
"""DefaultRenderer + parsers should extract tool calls and reasoning."""
|
||||
from renderers import create_renderer
|
||||
from renderers import DefaultRendererConfig, create_renderer
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen3-0.6B")
|
||||
renderer = create_renderer(
|
||||
tok, renderer="default", tool_parser="qwen3", reasoning_parser="think"
|
||||
tok,
|
||||
DefaultRendererConfig(tool_parser="qwen3", reasoning_parser="think"),
|
||||
)
|
||||
assert renderer.supports_tools is True
|
||||
|
||||
@@ -90,20 +128,21 @@ 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():
|
||||
"""Without parsers, DefaultRenderer still does basic <think> extraction."""
|
||||
from renderers import create_renderer
|
||||
from renderers import DefaultRendererConfig, create_renderer
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen3-0.6B")
|
||||
renderer = create_renderer(tok, renderer="default")
|
||||
renderer = create_renderer(tok, DefaultRendererConfig())
|
||||
assert renderer.supports_tools is False
|
||||
|
||||
ids = tok.encode("<think>r</think>a", add_special_tokens=False)
|
||||
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,9 +1,10 @@
|
||||
"""Smoke coverage for the ``preserve_*_thinking`` override flags.
|
||||
|
||||
Flags are constructor-only (``create_renderer(..., preserve_all_thinking=True)``)
|
||||
and stored as instance attributes — there is no call-site ``render`` /
|
||||
``render_ids`` override. Each test that wants a non-default flag builds
|
||||
a fresh renderer for that configuration via ``_make`` below.
|
||||
Flags live on the typed renderer config (e.g.
|
||||
``Qwen3RendererConfig(preserve_all_thinking=True)``) and are stored on
|
||||
the renderer as ``self.config.preserve_*``. Each test that wants a
|
||||
non-default flag builds a fresh renderer for that configuration via
|
||||
``_make`` below.
|
||||
|
||||
Two invariants per renderer:
|
||||
|
||||
@@ -22,15 +23,22 @@ default==override equality instead of strict growth.
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import should_preserve_past_thinking
|
||||
from renderers.base import MODEL_RENDERER_MAP, should_preserve_past_thinking
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
|
||||
def _make(tokenizer, renderer_name, **flags):
|
||||
"""Build a fresh renderer with the given preserve_*_thinking flags
|
||||
bound at construction. Reuses the cached tokenizer fixture."""
|
||||
return create_renderer(tokenizer, renderer=renderer_name, **flags)
|
||||
if renderer_name == "auto":
|
||||
renderer_name = MODEL_RENDERER_MAP.get(
|
||||
getattr(tokenizer, "name_or_path", ""), "default"
|
||||
)
|
||||
config = _config_class_for(renderer_name)(**flags)
|
||||
return create_renderer(tokenizer, config)
|
||||
|
||||
|
||||
# Renderers whose template doesn't drop past-asst thinking or has no
|
||||
@@ -42,6 +50,7 @@ NO_OP_MODELS = {
|
||||
"Qwen/Qwen3-VL-4B-Instruct",
|
||||
"Qwen/Qwen3-VL-8B-Instruct",
|
||||
"Qwen/Qwen3-VL-30B-A3B-Instruct",
|
||||
"poolside/Laguna-XS.2",
|
||||
}
|
||||
|
||||
|
||||
@@ -378,17 +387,19 @@ def test_default_renderer_raises_on_flags():
|
||||
"""``DefaultRenderer`` falls back to apply_chat_template with no
|
||||
selective re-emit pathway, so constructing one with either flag set
|
||||
must raise — fail fast, before any render is attempted."""
|
||||
from renderers import DefaultRendererConfig
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen2.5-0.5B-Instruct")
|
||||
# No flags → constructs cleanly.
|
||||
create_renderer(tok, renderer="default")
|
||||
create_renderer(tok, DefaultRendererConfig())
|
||||
# Either flag set → raises at construction.
|
||||
with pytest.raises(NotImplementedError):
|
||||
create_renderer(tok, renderer="default", preserve_all_thinking=True)
|
||||
create_renderer(tok, DefaultRendererConfig(preserve_all_thinking=True))
|
||||
with pytest.raises(NotImplementedError):
|
||||
create_renderer(
|
||||
tok, renderer="default", preserve_thinking_between_tool_calls=True
|
||||
tok,
|
||||
DefaultRendererConfig(preserve_thinking_between_tool_calls=True),
|
||||
)
|
||||
|
||||
|
||||
@@ -398,31 +409,27 @@ def test_default_renderer_raises_on_flags():
|
||||
|
||||
|
||||
def test_create_renderer_records_flag_state(model_name, renderer_name, tokenizer):
|
||||
"""Each renderer exposes the bound flag state via ``_preserve_*``
|
||||
attributes — useful for downstream code (pool cache keys, logging,
|
||||
test assertions) that needs to confirm what was constructed."""
|
||||
"""Each renderer exposes the bound flag state via ``self.config`` —
|
||||
useful for downstream code (pool cache keys, logging, test
|
||||
assertions) that needs to confirm what was constructed."""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
bare = create_renderer(tokenizer, renderer=renderer_name)
|
||||
assert bare._preserve_all_thinking is False
|
||||
assert bare._preserve_thinking_between_tool_calls is False
|
||||
bare = _make(tokenizer, renderer_name)
|
||||
assert bare.config.preserve_all_thinking is False
|
||||
assert bare.config.preserve_thinking_between_tool_calls is False
|
||||
|
||||
if not isinstance(bare, DefaultRenderer):
|
||||
# DefaultRenderer raises at construction with either flag set —
|
||||
# covered by ``test_default_renderer_raises_on_flags``.
|
||||
all_on = create_renderer(
|
||||
tokenizer, renderer=renderer_name, preserve_all_thinking=True
|
||||
)
|
||||
assert all_on._preserve_all_thinking is True
|
||||
assert all_on._preserve_thinking_between_tool_calls is False
|
||||
all_on = _make(tokenizer, renderer_name, preserve_all_thinking=True)
|
||||
assert all_on.config.preserve_all_thinking is True
|
||||
assert all_on.config.preserve_thinking_between_tool_calls is False
|
||||
|
||||
btc_on = create_renderer(
|
||||
tokenizer,
|
||||
renderer=renderer_name,
|
||||
preserve_thinking_between_tool_calls=True,
|
||||
btc_on = _make(
|
||||
tokenizer, renderer_name, preserve_thinking_between_tool_calls=True
|
||||
)
|
||||
assert btc_on._preserve_all_thinking is False
|
||||
assert btc_on._preserve_thinking_between_tool_calls is True
|
||||
assert btc_on.config.preserve_all_thinking is False
|
||||
assert btc_on.config.preserve_thinking_between_tool_calls is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -430,30 +437,31 @@ def test_create_renderer_records_flag_state(model_name, renderer_name, tokenizer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_glm5_constructor_rejects_clear_thinking():
|
||||
"""``clear_thinking`` was a chat-template-kwarg pass-through. It is
|
||||
superseded by the renderer-agnostic ``preserve_all_thinking`` override
|
||||
and must no longer be accepted by the constructor — its default-True
|
||||
semantics are now baked into the render gate."""
|
||||
def test_glm5_config_accepts_clear_thinking():
|
||||
"""``clear_thinking`` is a chat-template field on GLM-5's typed
|
||||
config. The GLM-5 / GLM-5.1 Jinja templates gate historical
|
||||
reasoning on ``clear_thinking is defined and not clear_thinking``,
|
||||
so passing ``clear_thinking=False`` here must reach the renderer's
|
||||
historical-reasoning gate. Parity vs ``apply_chat_template`` is
|
||||
asserted in ``test_renderer_config_parity``."""
|
||||
from renderers import GLM5RendererConfig
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.glm5 import GLM5Renderer
|
||||
|
||||
tok = load_tokenizer("zai-org/GLM-5")
|
||||
with pytest.raises(TypeError):
|
||||
GLM5Renderer(tok, clear_thinking=True) # type: ignore[call-arg]
|
||||
with pytest.raises(TypeError):
|
||||
GLM5Renderer(tok, clear_thinking=False) # type: ignore[call-arg]
|
||||
# Both values must be accepted without raising.
|
||||
GLM5Renderer(tok, GLM5RendererConfig(clear_thinking=True))
|
||||
GLM5Renderer(tok, GLM5RendererConfig(clear_thinking=False))
|
||||
|
||||
|
||||
def test_qwen36_constructor_rejects_preserve_thinking():
|
||||
def test_qwen36_config_rejects_unknown_field():
|
||||
"""``preserve_thinking`` on Qwen3.6 was a chat-template-kwarg
|
||||
pass-through. It is superseded by the renderer-agnostic
|
||||
``preserve_all_thinking`` override and must no longer be accepted by
|
||||
the constructor — its default-False semantics are now inherited from
|
||||
Qwen3.5's render gate."""
|
||||
from renderers.base import load_tokenizer
|
||||
from renderers.qwen36 import Qwen36Renderer
|
||||
pass-through in an earlier revision. It is superseded by the
|
||||
renderer-agnostic ``preserve_all_thinking`` override and must not
|
||||
appear on the typed config — its default-False semantics are now
|
||||
inherited from Qwen3.5's render gate. ``extra="forbid"`` on the
|
||||
pydantic model enforces this at construction."""
|
||||
from renderers import Qwen36RendererConfig
|
||||
|
||||
tok = load_tokenizer("Qwen/Qwen3.6-35B-A3B")
|
||||
with pytest.raises(TypeError):
|
||||
Qwen36Renderer(tok, preserve_thinking=True) # type: ignore[call-arg]
|
||||
with pytest.raises(ValidationError, match="preserve_thinking"):
|
||||
Qwen36RendererConfig(preserve_thinking=True) # type: ignore[call-arg]
|
||||
|
||||
@@ -19,7 +19,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import Qwen35Renderer, create_renderer
|
||||
from renderers import Qwen35Renderer, Qwen35RendererConfig, create_renderer
|
||||
from renderers.base import MODEL_RENDERER_MAP, load_tokenizer
|
||||
|
||||
|
||||
@@ -78,11 +78,11 @@ def test_qwen35_enable_thinking_polarity_autodetected(qwen35_model, expected_def
|
||||
own default when no explicit flag is passed — so big / small sizes
|
||||
each match their own template at the gen-prompt boundary."""
|
||||
tok = load_tokenizer(qwen35_model)
|
||||
renderer = create_renderer(tok, renderer="qwen3.5")
|
||||
renderer = create_renderer(tok, Qwen35RendererConfig())
|
||||
assert isinstance(renderer, Qwen35Renderer)
|
||||
assert renderer._enable_thinking is expected_default, (
|
||||
assert renderer.config.enable_thinking is expected_default, (
|
||||
f"{qwen35_model}: expected enable_thinking default {expected_default}, "
|
||||
f"got {renderer._enable_thinking}"
|
||||
f"got {renderer.config.enable_thinking}"
|
||||
)
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_qwen35_size_parity_with_apply_chat_template(
|
||||
share ``Qwen35Renderer`` across all seven sizes — the polarity
|
||||
flip on 0.8B / 2B is absorbed by the constructor's auto-detect."""
|
||||
tok = load_tokenizer(qwen35_model)
|
||||
renderer = create_renderer(tok, renderer="qwen3.5")
|
||||
renderer = create_renderer(tok, Qwen35RendererConfig())
|
||||
assert isinstance(renderer, Qwen35Renderer)
|
||||
|
||||
ours = renderer.render_ids(messages, add_generation_prompt=add_gen_prompt)
|
||||
|
||||
@@ -338,7 +338,7 @@ def test_multi_step_tool_cycle(model_name, tokenizer, renderer):
|
||||
@lru_cache
|
||||
def _qwen3_vl():
|
||||
tokenizer = load_tokenizer("Qwen/Qwen3-VL-4B-Instruct")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
@@ -353,7 +353,7 @@ def test_qwen3_vl_auto_renderer():
|
||||
@lru_cache
|
||||
def _kimi_k25():
|
||||
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
return tokenizer, renderer
|
||||
|
||||
|
||||
@@ -366,7 +366,7 @@ def test_kimi_k2_inline_think_tags_render_verbatim():
|
||||
reasoning, producing tokens that disagreed with ``apply_chat_template``.
|
||||
"""
|
||||
tokenizer = load_tokenizer("moonshotai/Kimi-K2-Instruct")
|
||||
renderer = create_renderer(tokenizer, renderer="auto")
|
||||
renderer = create_renderer(tokenizer)
|
||||
msgs = [
|
||||
{"role": "user", "content": "hi"},
|
||||
{"role": "assistant", "content": "<think>secret</think>visible"},
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Unit tests for the typed-config surface — discriminated union,
|
||||
auto-resolution, and ``extra="forbid"`` enforcement on per-renderer
|
||||
configs."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pydantic import TypeAdapter, ValidationError
|
||||
|
||||
from renderers import (
|
||||
AutoRendererConfig,
|
||||
DefaultRendererConfig,
|
||||
GLM5RendererConfig,
|
||||
Qwen3RendererConfig,
|
||||
Qwen35RendererConfig,
|
||||
RendererConfig,
|
||||
base,
|
||||
create_renderer,
|
||||
)
|
||||
|
||||
|
||||
def test_per_renderer_config_rejects_unknown_fields():
|
||||
"""``extra="forbid"`` on every typed variant catches bogus keys at
|
||||
construction: ``add_vision_id`` doesn't exist on ``Qwen3RendererConfig``
|
||||
(Qwen3 is text-only), so passing it must raise."""
|
||||
with pytest.raises(ValidationError, match="add_vision_id"):
|
||||
Qwen3RendererConfig(add_vision_id=True)
|
||||
|
||||
|
||||
def test_discriminated_union_dispatches_on_name():
|
||||
"""A dict shaped like ``{"name": "glm-5", ...}`` deserialises to the
|
||||
matching typed config; the union ``RendererConfig`` is what
|
||||
downstream consumers (prime-rl, verifiers) hold as a single field."""
|
||||
ta = TypeAdapter(RendererConfig)
|
||||
parsed = ta.validate_python(
|
||||
{"name": "glm-5", "enable_thinking": False, "clear_thinking": False}
|
||||
)
|
||||
assert isinstance(parsed, GLM5RendererConfig)
|
||||
assert parsed.enable_thinking is False
|
||||
assert parsed.clear_thinking is False
|
||||
|
||||
|
||||
def test_discriminated_union_rejects_wrong_renderer_kwargs():
|
||||
"""``add_vision_id`` under ``name="qwen3"`` is invalid at deserialise
|
||||
time — the discriminator narrows to ``Qwen3RendererConfig`` whose
|
||||
schema does not include that field."""
|
||||
ta = TypeAdapter(RendererConfig)
|
||||
with pytest.raises(ValidationError, match="add_vision_id"):
|
||||
ta.validate_python({"name": "qwen3", "add_vision_id": True})
|
||||
|
||||
|
||||
def test_default_renderer_config_accepts_arbitrary_extras():
|
||||
"""``DefaultRenderer`` wraps ``apply_chat_template`` for unknown
|
||||
templates, so its config uses ``extra="allow"`` and surfaces extras
|
||||
via ``model_extra``."""
|
||||
cfg = DefaultRendererConfig(
|
||||
tool_parser="qwen3", enable_thinking=False, custom_jinja_kwarg=True
|
||||
)
|
||||
assert cfg.tool_parser == "qwen3"
|
||||
assert cfg.model_extra == {
|
||||
"enable_thinking": False,
|
||||
"custom_jinja_kwarg": True,
|
||||
}
|
||||
|
||||
|
||||
def test_create_renderer_forwards_typed_config_to_renderer(monkeypatch):
|
||||
"""``create_renderer`` dispatches on ``config.name`` via
|
||||
``RENDERER_REGISTRY``; the renderer stores the config it was given."""
|
||||
|
||||
class _FakeRenderer:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.tokenizer = tokenizer
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3", _FakeRenderer)
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="unused"),
|
||||
Qwen3RendererConfig(enable_thinking=False),
|
||||
)
|
||||
assert isinstance(renderer.config, Qwen3RendererConfig)
|
||||
assert renderer.config.enable_thinking is False
|
||||
|
||||
|
||||
def test_create_renderer_auto_resolves_via_model_map(monkeypatch):
|
||||
"""``AutoRendererConfig`` (or ``config=None``) routes through
|
||||
``MODEL_RENDERER_MAP`` to pick the matching renderer + typed config,
|
||||
carrying the shared ``preserve_*`` flags over from the auto config."""
|
||||
|
||||
class _FakeQwen35:
|
||||
def __init__(self, tokenizer, config):
|
||||
self.tokenizer = tokenizer
|
||||
self.config = config
|
||||
|
||||
monkeypatch.setitem(base.RENDERER_REGISTRY, "qwen3.5", _FakeQwen35)
|
||||
monkeypatch.setitem(base.MODEL_RENDERER_MAP, "fake/qwen35", "qwen3.5")
|
||||
|
||||
renderer = create_renderer(
|
||||
SimpleNamespace(name_or_path="fake/qwen35"),
|
||||
AutoRendererConfig(preserve_all_thinking=True),
|
||||
)
|
||||
|
||||
assert isinstance(renderer.config, Qwen35RendererConfig)
|
||||
assert renderer.config.preserve_all_thinking is True
|
||||
# Template-level kwargs stay at their per-renderer defaults — auto
|
||||
# carries only the preserve_* flags.
|
||||
assert renderer.config.add_vision_id is False
|
||||
|
||||
|
||||
def test_create_renderer_default_argument_is_auto():
|
||||
"""Passing no config is equivalent to passing ``AutoRendererConfig()``
|
||||
— short form for the common case."""
|
||||
tok = SimpleNamespace(name_or_path="") # no MODEL_RENDERER_MAP entry
|
||||
renderer = create_renderer(tok)
|
||||
# Falls through to DefaultRenderer when no match and no vision config.
|
||||
assert renderer.__class__.__name__ == "DefaultRenderer"
|
||||
@@ -0,0 +1,513 @@
|
||||
"""Parity for typed-config template fields against the upstream chat
|
||||
template.
|
||||
|
||||
Each renderer's typed config (see ``renderers.configs``) declares the
|
||||
fields that mirror chat-template kwargs via
|
||||
``Config.template_field_names()``. ``test_renderer_config.py`` covers
|
||||
the typed-config wiring; this file covers the only thing that matters
|
||||
downstream: that flipping a template field on the typed config produces
|
||||
token streams byte-identical to
|
||||
``tokenizer.apply_chat_template(messages, **{field: value})``.
|
||||
|
||||
Without this, the typed surface is a promise the renderer doesn't keep.
|
||||
|
||||
Discovery is automatic — the parity matrix is built from each config
|
||||
class's ``template_field_names()`` crossed with the per-field value list
|
||||
in ``_KWARG_VALUES``. To extend coverage to a new field: declare it on
|
||||
the typed config and add the values to exercise to ``_KWARG_VALUES``
|
||||
below.
|
||||
|
||||
``gpt-oss`` parity is against ``openai-harmony`` (its renderer diverges
|
||||
from HF Jinja by design — see ``test_gpt_oss_harmony_parity.py``); it
|
||||
lives in its own test below, with the same auto-derived discovery.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from renderers import create_renderer
|
||||
from renderers.base import (
|
||||
MODEL_RENDERER_MAP,
|
||||
_populate_registry,
|
||||
load_tokenizer,
|
||||
)
|
||||
from renderers.configs import _config_class_for
|
||||
|
||||
|
||||
# Models exercised by the parity tests. Mirrors ``conftest.RENDERER_MODELS``
|
||||
# in spirit — one representative model per renderer family — plus the
|
||||
# ``gpt-oss`` entry that conftest skips for HF parity (gpt-oss parity is
|
||||
# against harmony, handled separately below).
|
||||
_RENDERER_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"),
|
||||
("Qwen/Qwen3.5-9B", "auto"),
|
||||
("Qwen/Qwen3.6-35B-A3B", "auto"),
|
||||
("zai-org/GLM-5", "auto"),
|
||||
("zai-org/GLM-5.1", "auto"),
|
||||
("zai-org/GLM-4.7-Flash", "auto"),
|
||||
("THUDM/GLM-4.5-Air", "auto"),
|
||||
("moonshotai/Kimi-K2.5", "auto"),
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("deepseek-ai/DeepSeek-V3", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
]
|
||||
|
||||
|
||||
# Per-kwarg value list. Each template field any renderer's typed config
|
||||
# declares (via ``Config.template_field_names()``) must have an entry
|
||||
# here, or the parity matrix silently skips it. The test below asserts
|
||||
# coverage so a future kwarg can't slip through without an explicit
|
||||
# value list.
|
||||
_KWARG_VALUES: dict[str, list[Any]] = {
|
||||
"enable_thinking": [True, False],
|
||||
# Kimi K2.5 / K2.6 — same semantics as ``enable_thinking`` but the
|
||||
# upstream template uses ``thinking`` as the variable name. The
|
||||
# renderer's typed config (``KimiK25RendererConfig.thinking``)
|
||||
# mirrors that name so the field maps 1:1 onto the template gate.
|
||||
"thinking": [True, False],
|
||||
"reasoning_effort": ["low", "medium", "high"],
|
||||
# GLM-5 / GLM-5.1 — ``clear_thinking=False`` preserves the
|
||||
# ``<think>{reasoning}</think>`` wrap on historical assistants too
|
||||
# (default True collapses past-cycle reasoning to ``</think>``).
|
||||
"clear_thinking": [True, False],
|
||||
# Nemotron-3 — mirror of ``clear_thinking`` under a different name.
|
||||
# ``truncate_history_thinking=False`` keeps reasoning on historical
|
||||
# assistants instead of collapsing to ``<think></think>``.
|
||||
"truncate_history_thinking": [True, False],
|
||||
# MiniMax-M2 — fallback persona string when no system message is
|
||||
# supplied. Two arbitrary values to verify the renderer threads the
|
||||
# exact bytes through (whitespace included).
|
||||
"model_identity": [
|
||||
"You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax.",
|
||||
"You are CustomBot, a research assistant.",
|
||||
],
|
||||
# Laguna-XS.2 — switches assistant rendering to a verbatim
|
||||
# passthrough mode. The renderer paths diverge significantly under
|
||||
# this flag, so both values are exercised.
|
||||
"render_assistant_messages_raw": [True, False],
|
||||
# Qwen3.5 / Qwen3.6 / Qwen3-VL — when True, prefix each image /
|
||||
# video placeholder with ``Picture N: `` / ``Video N: ``.
|
||||
"add_vision_id": [True, False],
|
||||
# gpt-oss — pin to a fixed date so the renderer's preamble matches
|
||||
# the harmony oracle built with the same date. The default
|
||||
# ``today's date`` is intentionally avoided here so the assertion
|
||||
# doesn't flake on a UTC midnight crossing.
|
||||
"conversation_start_date": ["2025-01-15"],
|
||||
}
|
||||
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "The city name"},
|
||||
},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
# (id, messages, render_kwargs). Each shape exercises a distinct branch
|
||||
# at least one renderer is known to flip on a kwarg:
|
||||
#
|
||||
# - ``system_user_gen``: forces the generation-prompt branch (e.g.
|
||||
# Qwen3 / GLM / Nemotron emit a synthesized ``<think></think>`` here
|
||||
# under ``enable_thinking=False``).
|
||||
# - ``single_turn``: terminal assistant with plain content — the
|
||||
# "render historical thinking?" branch.
|
||||
# - ``with_reasoning``: assistant carries ``reasoning_content`` — flips
|
||||
# whether thinking is emitted into the rendered history.
|
||||
# - ``multi_turn``: two assistant turns separated by a user; the
|
||||
# in-flight-vs-historical distinction matters for several renderers.
|
||||
# - ``tool_cycle``: assistant tool call + tool response + final
|
||||
# assistant, with ``add_generation_prompt=True`` so the second
|
||||
# gen-prompt branch is hit too.
|
||||
_MESSAGE_SHAPES = [
|
||||
(
|
||||
"system_user_gen",
|
||||
[
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{"role": "user", "content": "Hi"},
|
||||
],
|
||||
{"add_generation_prompt": True},
|
||||
),
|
||||
(
|
||||
"single_turn",
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{"role": "assistant", "content": "4"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"with_reasoning",
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Simple arithmetic.",
|
||||
"content": "4",
|
||||
},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"multi_turn",
|
||||
[
|
||||
{"role": "user", "content": "A"},
|
||||
{"role": "assistant", "content": "B"},
|
||||
{"role": "user", "content": "C"},
|
||||
{"role": "assistant", "content": "D"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"tool_cycle",
|
||||
[
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": {"city": "Paris"},
|
||||
}
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "content": '{"temp": 20}'},
|
||||
{"role": "assistant", "content": "It is 20 degrees."},
|
||||
],
|
||||
{"tools": TOOLS, "add_generation_prompt": True},
|
||||
),
|
||||
# ``no_system_user_gen``: no system message — exercises the
|
||||
# template fallback persona (e.g. MiniMax-M2's ``model_identity``).
|
||||
(
|
||||
"no_system_user_gen",
|
||||
[{"role": "user", "content": "Hi"}],
|
||||
{"add_generation_prompt": True},
|
||||
),
|
||||
# ``historical_reasoning``: multi-turn with ``reasoning_content`` on
|
||||
# a historical assistant. Exercises ``clear_thinking`` /
|
||||
# ``truncate_history_thinking`` (which only diverge from default
|
||||
# behaviour when a past-cycle assistant carries reasoning).
|
||||
(
|
||||
"historical_reasoning",
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Adding small ints.",
|
||||
"content": "4",
|
||||
},
|
||||
{"role": "user", "content": "Now 3+3?"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"reasoning_content": "Same idea.",
|
||||
"content": "6",
|
||||
},
|
||||
],
|
||||
{},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# ── Matrix discovery ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
_populate_registry()
|
||||
|
||||
|
||||
def _resolve_renderer_name(model: str, renderer_name: str) -> str:
|
||||
"""Resolve ``(model, renderer_name)`` to the concrete renderer name."""
|
||||
if renderer_name == "auto":
|
||||
return MODEL_RENDERER_MAP.get(model, "default")
|
||||
return renderer_name
|
||||
|
||||
|
||||
def _template_fields_for(model: str, renderer_name: str) -> frozenset[str]:
|
||||
"""Discover the typed-config template-field set for a renderer."""
|
||||
resolved = _resolve_renderer_name(model, renderer_name)
|
||||
return _config_class_for(resolved).template_field_names()
|
||||
|
||||
|
||||
def _hf_parity_matrix() -> list[Any]:
|
||||
"""Auto-derived ``(model, renderer_name, kwarg, value)`` matrix for
|
||||
every renderer with template fields, minus gpt-oss (handled
|
||||
separately against harmony).
|
||||
"""
|
||||
out = []
|
||||
for model, name in _RENDERER_MODELS:
|
||||
if name == "gpt-oss":
|
||||
continue
|
||||
for kwarg in sorted(_template_fields_for(model, name)):
|
||||
for value in _KWARG_VALUES.get(kwarg, []):
|
||||
out.append(
|
||||
pytest.param(
|
||||
model, name, kwarg, value, id=f"{model}-{kwarg}={value}"
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _harmony_parity_matrix() -> list[Any]:
|
||||
"""Auto-derived ``(model, renderer_name, kwarg, value)`` matrix for
|
||||
gpt-oss (parity against ``openai-harmony``).
|
||||
"""
|
||||
out = []
|
||||
for model, name in _RENDERER_MODELS:
|
||||
if name != "gpt-oss":
|
||||
continue
|
||||
for kwarg in sorted(_template_fields_for(model, name)):
|
||||
for value in _KWARG_VALUES.get(kwarg, []):
|
||||
out.append(
|
||||
pytest.param(
|
||||
model, name, kwarg, value, id=f"{model}-{kwarg}={value}"
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_kwarg_values_covers_every_declared_kwarg():
|
||||
"""Every template field any renderer declares must have an entry in
|
||||
``_KWARG_VALUES`` — otherwise it silently drops out of parity
|
||||
coverage.
|
||||
"""
|
||||
declared: set[str] = set()
|
||||
for model, name in _RENDERER_MODELS:
|
||||
declared.update(_template_fields_for(model, name))
|
||||
missing = sorted(declared - _KWARG_VALUES.keys())
|
||||
assert not missing, (
|
||||
f"Typed-config template fields declared but not covered: {missing}. "
|
||||
f"Add a value list to _KWARG_VALUES in this file."
|
||||
)
|
||||
|
||||
|
||||
# ── Test caches ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _tokenizer(model_name: str):
|
||||
return load_tokenizer(model_name)
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _renderer_with_kwarg(model_name: str, renderer_name: str, kwarg: str, value: Any):
|
||||
tok = _tokenizer(model_name)
|
||||
resolved = _resolve_renderer_name(model_name, renderer_name)
|
||||
config = _config_class_for(resolved)(**{kwarg: value})
|
||||
return create_renderer(tok, config)
|
||||
|
||||
|
||||
def _expected_hf(tokenizer, messages, *, kwarg: str, value: Any, **render_kwargs):
|
||||
"""Render via ``apply_chat_template`` with the kwarg spread as a
|
||||
top-level argument.
|
||||
|
||||
transformers v5.x silently drops ``chat_template_kwargs={...}`` —
|
||||
only direct kwargs propagate into the Jinja environment. The two
|
||||
invocation styles are semantically the same for the Jinja template,
|
||||
so we pick the one that actually fires. (Our ``create_renderer``
|
||||
API accepts the dict form because it is the standard wire format
|
||||
in OpenAI-compatible servers; we translate it to constructor kwargs
|
||||
on our side.)
|
||||
"""
|
||||
render_kwargs.setdefault("add_generation_prompt", False)
|
||||
result = tokenizer.apply_chat_template(
|
||||
messages,
|
||||
tokenize=True,
|
||||
return_dict=False,
|
||||
**{kwarg: value},
|
||||
**render_kwargs,
|
||||
)
|
||||
if isinstance(result, dict):
|
||||
return list(result["input_ids"])
|
||||
if isinstance(result, str):
|
||||
return list(tokenizer.encode(result, add_special_tokens=False))
|
||||
return list(result)
|
||||
|
||||
|
||||
# ── HF-Jinja parity (every renderer except gpt-oss) ────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model,renderer_name,kwarg,value", _hf_parity_matrix())
|
||||
@pytest.mark.parametrize(
|
||||
"shape_id,messages,render_kwargs",
|
||||
_MESSAGE_SHAPES,
|
||||
ids=[s[0] for s in _MESSAGE_SHAPES],
|
||||
)
|
||||
def test_chat_template_kwarg_parity_hf(
|
||||
model,
|
||||
renderer_name,
|
||||
kwarg,
|
||||
value,
|
||||
shape_id,
|
||||
messages,
|
||||
render_kwargs,
|
||||
):
|
||||
tokenizer = _tokenizer(model)
|
||||
renderer = _renderer_with_kwarg(model, renderer_name, kwarg, value)
|
||||
# Guard: the typed config must actually declare the kwarg as a
|
||||
# template field. Pydantic ``extra="forbid"`` already enforces this
|
||||
# at construction; asserting here gives a louder failure on a future
|
||||
# config subclass that drops the field.
|
||||
assert kwarg in type(renderer.config).template_field_names()
|
||||
|
||||
try:
|
||||
expected = _expected_hf(
|
||||
tokenizer, messages, kwarg=kwarg, value=value, **render_kwargs
|
||||
)
|
||||
except Exception as exc:
|
||||
pytest.xfail(
|
||||
f"{model}: apply_chat_template raised {type(exc).__name__}: "
|
||||
f"{str(exc)[:160]}"
|
||||
)
|
||||
|
||||
got = renderer.render_ids(messages, **render_kwargs)
|
||||
assert got == expected, (
|
||||
f"{model} / shape={shape_id} / {kwarg}={value}: renderer diverged "
|
||||
f"from apply_chat_template (len got={len(got)}, expected={len(expected)})"
|
||||
)
|
||||
|
||||
|
||||
# ── Harmony parity (gpt-oss only) ──────────────────────────────────────
|
||||
|
||||
|
||||
_DATE_FOR_PARITY = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _gpt_oss_renderer(kwarg: str, value: Any):
|
||||
from renderers.configs import GptOssRendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
|
||||
tok = _tokenizer("openai/gpt-oss-20b")
|
||||
# Pin a default conversation_start_date so the rendered preamble
|
||||
# matches the harmony oracle's fixed date. Any explicit
|
||||
# ``conversation_start_date`` from the kwarg-under-test overrides
|
||||
# it (the per-kwarg branch replays the same value into the oracle
|
||||
# below so the assertion still holds).
|
||||
kwargs: dict[str, Any] = {"conversation_start_date": _DATE_FOR_PARITY}
|
||||
kwargs[kwarg] = value
|
||||
return GptOssRenderer(tok, GptOssRendererConfig(**kwargs))
|
||||
|
||||
|
||||
def _harmony_expected(
|
||||
kwarg: str, value: Any, messages: list[dict[str, Any]]
|
||||
) -> list[int]:
|
||||
from openai_harmony import (
|
||||
Conversation,
|
||||
HarmonyEncodingName,
|
||||
Message as HarmonyMessage,
|
||||
ReasoningEffort,
|
||||
Role,
|
||||
SystemContent,
|
||||
load_harmony_encoding,
|
||||
)
|
||||
|
||||
# Base preamble pins the same default date the renderer fixture
|
||||
# uses so the unrelated kwargs don't drift on date semantics.
|
||||
sys_content = SystemContent.new().with_conversation_start_date(_DATE_FOR_PARITY)
|
||||
if kwarg == "reasoning_effort":
|
||||
effort_enum = {
|
||||
"low": ReasoningEffort.LOW,
|
||||
"medium": ReasoningEffort.MEDIUM,
|
||||
"high": ReasoningEffort.HIGH,
|
||||
}[value]
|
||||
sys_content = sys_content.with_reasoning_effort(effort_enum)
|
||||
elif kwarg == "conversation_start_date":
|
||||
# Override the pinned date with the value under test.
|
||||
sys_content = sys_content.with_conversation_start_date(value)
|
||||
else:
|
||||
raise AssertionError(
|
||||
f"Harmony oracle: unhandled gpt-oss chat_template_kwarg {kwarg!r}. "
|
||||
"Add a branch here when extending GptOssRendererConfig's template fields."
|
||||
)
|
||||
|
||||
harmony_msgs: list[HarmonyMessage] = [
|
||||
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
|
||||
]
|
||||
for m in messages:
|
||||
role = m["role"]
|
||||
content = m.get("content", "") or ""
|
||||
if role == "user":
|
||||
harmony_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(Role.USER, content)
|
||||
)
|
||||
elif role == "assistant":
|
||||
harmony_msgs.append(
|
||||
HarmonyMessage.from_role_and_content(
|
||||
Role.ASSISTANT, content
|
||||
).with_channel("final")
|
||||
)
|
||||
else:
|
||||
raise AssertionError(
|
||||
f"Harmony oracle helper does not handle role={role!r}; add a "
|
||||
"branch or constrain the shapes used for gpt-oss parity."
|
||||
)
|
||||
encoder = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
|
||||
return encoder.render_conversation_for_training(
|
||||
Conversation.from_messages(harmony_msgs)
|
||||
)
|
||||
|
||||
|
||||
# Harmony oracle is only wired for the simplest shapes (user-only and
|
||||
# user+assistant content). Tool-call and reasoning_content shapes have
|
||||
# a richer mapping that the dedicated ``test_gpt_oss_harmony_parity.py``
|
||||
# already covers — duplicating that here would only test the harness.
|
||||
_HARMONY_SHAPES = [
|
||||
(
|
||||
"user_only_gen",
|
||||
[{"role": "user", "content": "Hello!"}],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"user_and_assistant",
|
||||
[
|
||||
{"role": "user", "content": "Hi"},
|
||||
{"role": "assistant", "content": "Hello!"},
|
||||
],
|
||||
{},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model,renderer_name,kwarg,value", _harmony_parity_matrix())
|
||||
@pytest.mark.parametrize(
|
||||
"shape_id,messages,render_kwargs",
|
||||
_HARMONY_SHAPES,
|
||||
ids=[s[0] for s in _HARMONY_SHAPES],
|
||||
)
|
||||
def test_chat_template_kwarg_parity_harmony(
|
||||
model,
|
||||
renderer_name,
|
||||
kwarg,
|
||||
value,
|
||||
shape_id,
|
||||
messages,
|
||||
render_kwargs,
|
||||
):
|
||||
renderer = _gpt_oss_renderer(kwarg, value)
|
||||
assert kwarg in type(renderer.config).template_field_names()
|
||||
|
||||
got = renderer.render_ids(messages, **render_kwargs)
|
||||
expected = _harmony_expected(kwarg, value, messages)
|
||||
assert got == expected, (
|
||||
f"{model} / shape={shape_id} / {kwarg}={value}: renderer diverged "
|
||||
f"from harmony oracle (len got={len(got)}, expected={len(expected)})"
|
||||
)
|
||||
+13
-18
@@ -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"),
|
||||
]
|
||||
@@ -50,11 +51,11 @@ _ROUNDTRIP_MODELS = [
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _load_renderer(model_name: str, renderer_name: str):
|
||||
from renderers import create_renderer
|
||||
from renderers import config_from_name, create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer(model_name)
|
||||
return tok, create_renderer(tok, renderer=renderer_name)
|
||||
return tok, create_renderer(tok, config_from_name(renderer_name))
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc):
|
||||
@@ -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 ─────────────────────────────────────
|
||||
@@ -321,7 +316,7 @@ def test_default_renderer_fallback_parser_preserves_boundary_whitespace(
|
||||
"""
|
||||
from renderers.default import DefaultRenderer
|
||||
|
||||
renderer = DefaultRenderer(rt_tokenizer, tool_parser=None, reasoning_parser=None)
|
||||
renderer = DefaultRenderer(rt_tokenizer)
|
||||
|
||||
# Encode `<think>reason</think>\nvisible` as text and run through
|
||||
# parse_response. We don't need the template to emit `<think>` here
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
@@ -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)
|
||||
@@ -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 config_from_name, create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer(model)
|
||||
return tok, create_renderer(tok, config_from_name(renderer_name))
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc):
|
||||
if "model" in metafunc.fixturenames:
|
||||
metafunc.parametrize(
|
||||
"model,renderer_name",
|
||||
_MODELS,
|
||||
ids=[m for m, _ in _MODELS],
|
||||
)
|
||||
|
||||
|
||||
@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}"
|
||||
)
|
||||
@@ -9,9 +9,13 @@ resolution-markers = [
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "2026-05-03T21:26:00.600500892Z"
|
||||
exclude-newer = "2026-05-18T21:42:54.18041997Z"
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
prime-pydantic-config = false
|
||||
fastokens = false
|
||||
|
||||
[[package]]
|
||||
name = "annotated-doc"
|
||||
version = "0.0.4"
|
||||
@@ -264,6 +268,35 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastokens"
|
||||
version = "0.2.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/14/8e/7e88ec1d48db5a6e8d8d44318ce285e38c04b81508bdc2a60e17045a116f/fastokens-0.2.0.tar.gz", hash = "sha256:ef0e175de5c8cb1b616b3210d75dce1fab78e35fc02f77f03f7847d4678be686", size = 675822, upload-time = "2026-05-17T10:32:55.642Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e8/14/3d640cbe3c866ee6c113ea4ca37c16c5aa44be6412918928bbd3f3b739ef/fastokens-0.2.0-cp313-cp313t-macosx_10_12_x86_64.whl", hash = "sha256:e7db86c2785a502e3cd993c7d3a91c46e2751f94d1f446caa9600e9cf3dafbd1", size = 3078350, upload-time = "2026-05-17T10:32:41.313Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/bf/33ca3798842fb8bdacf03a97c874454d50fe328d44e0d3c3ba7a633fd3ab/fastokens-0.2.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fa8dcbc6ad3f7a7e9f5bf1ef3cfc9f0c04f0c8779be9e38864815dc567b27de4", size = 2983397, upload-time = "2026-05-17T10:32:38.823Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/0a/1bfd13fb855bce3ce50faa644d6e0e19343035706c2628e17da1247bbf50/fastokens-0.2.0-cp313-cp313t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:09b399600ae5beaa34e45afd05c6835b8569861955dfdc3e05afba25fe414e5a", size = 3309835, upload-time = "2026-05-17T10:32:33.427Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/32/ce/33292977a81011ffc59cee1c20b6f8d0dbd9cb39209c327dc74dc542178d/fastokens-0.2.0-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f363b1e89fe4ed979224c326b25b33b28e1172134f3e7959238276170f12328e", size = 3615173, upload-time = "2026-05-17T10:32:30.898Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/07/1c/1bef8b4831bf9220ae182fcee3e250273b7f537c81aec96041f6eb4bc990/fastokens-0.2.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d79358faa11658d8908fbdfab321b6ae6a0ff52ae3cdce7a0fda5c30629a276", size = 3295485, upload-time = "2026-05-17T10:32:36.109Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/92/11/49afb739800b6a82af04fa1e991b68669c789ebeaa3bcbc96c2544c8ff9c/fastokens-0.2.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:cf6ae284b70d65989548a8143e1f463f31126f5650ad45ce6af05b83e4afb3e7", size = 3329524, upload-time = "2026-05-17T10:32:44.607Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/d2/f9b1c01535a0ce994d30e86cf49616023246134d2a406b74c5dd49df7825/fastokens-0.2.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:40fa091ff12aa8ac00fa8e2133c7256b96209827b88de5120eb1361600d7f68f", size = 3149194, upload-time = "2026-05-17T10:32:47.596Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/0b/95b2e5d25efc684988918658c90445e0e5f1dc4fee7dae5edd586b4feaba/fastokens-0.2.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:f643f4739b20c86ed21e2c46e7fe203e6a621e21124074f138819423882e3aba", size = 3401011, upload-time = "2026-05-17T10:32:50.13Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9b/31/80b74196524d7a9576fa96685a39ee1f333ffd12eb29dbeb5e65c6e3dcb2/fastokens-0.2.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:3cd4effdc6610cbee0be717032652a1997976f1a2f21949435d925c7982cf6f3", size = 3593240, upload-time = "2026-05-17T10:32:52.661Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/59/96/12814aa955b7277adb07a8b36176181f247f3b9cf973d05b34294df6a72c/fastokens-0.2.0-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:d29eb1d608977d63fc4679d6ce2b360fdb8b0ea8d66a0eaf804f7ac31ba52a3a", size = 3089011, upload-time = "2026-05-17T10:32:43.16Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c0/05/553b59c6a8542ad7d443306fc1fd7bb012e4aae459ccf9ab422ea4c681b7/fastokens-0.2.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:f8ec7a20322aafe245201727c7a507b87333c51dc580940b9ee5456dbfe3963c", size = 2992964, upload-time = "2026-05-17T10:32:39.992Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/13/66/a53c2309003510de7c189ba8a9d2ea5a1833e9b447d9f69b95449c3dfe34/fastokens-0.2.0-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:dc4c0a25726620b1cc4cfb7e9dc1a53b17bbe3f2f9adbaa57b8375b5f36ac5d4", size = 3316289, upload-time = "2026-05-17T10:32:34.557Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b4/54/e0e4318ee1ad0b5196df72cf93615bba0b81f7869d659a44ccc475969151/fastokens-0.2.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:160253f8d30747cf66e7ed895c513e16f7b173dd9e644fa641e2eecbd43a616a", size = 3303534, upload-time = "2026-05-17T10:32:37.462Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/64/44/bfff90e4b1a43c17edf7305dafbd56dc992bbe832cc08da78f1f50104c2d/fastokens-0.2.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:b61b9fe5b41e0bb36ad86e7551dc53293c9833909ef07b1cdbaa2055b06c3b3e", size = 3254096, upload-time = "2026-05-17T10:32:28.489Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/df/89/bec1a0368100c5f1134ab1ce588d71f88697fadbbad5f26bb130eda00fe8/fastokens-0.2.0-cp39-abi3-manylinux_2_28_armv7l.whl", hash = "sha256:8f138fc64e355589be43068e6996ac0bfcfd872cd75fb5793d11d06cb9c0ac9b", size = 3000177, upload-time = "2026-05-17T10:32:29.745Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/fd/cbe8a033e2ef565ce5aef4e02316054b04adad96ee9805cba74a50a84ed9/fastokens-0.2.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:c1a6cd93d16e880d81deb12519cc2eb20149d7423321cf00a34ce25ea9c9ef15", size = 3626561, upload-time = "2026-05-17T10:32:32.087Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/05/bf/1cad7f0e8d03f5f5b2b417cda8859e4d968d2eebdca0cd336b23d7dbbdbb/fastokens-0.2.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:01b9bdba818d7b2c67d57d9917faf7a1dad32ece0734440130de94ad768b819f", size = 3336689, upload-time = "2026-05-17T10:32:46.21Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/05/56/0030c6e67c60ee88b74336d1bb03eb556b2afa60445268921ad02d9cb3b3/fastokens-0.2.0-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:9aec70b85a06bf2ac95dd76e07e404040dbcfb06eb165f29bc61ef2ab68dc87a", size = 3154666, upload-time = "2026-05-17T10:32:48.835Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/5b/02cc5d501ccc2fbd4b068a7aa34a35347bdb3a4189b96af647ef0407af87/fastokens-0.2.0-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:8c41f5278ac53853249c1170d653ee0afaa0906c9bc32c8d25c9443b6d667298", size = 3406657, upload-time = "2026-05-17T10:32:51.392Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/d7/f5fb2564e16b1f5733e05c41b090f95a3fe767f6b888ba7d864193bc5447/fastokens-0.2.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d068bc50082ad67d5d542847075f1f7b8d10f703274e56e241312f18b4d9e772", size = 3598064, upload-time = "2026-05-17T10:32:54.109Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0a/39/2098de2aa01c3e2ef62b066926d70015f88845e3ac1a976ba1cc3a363c05/fastokens-0.2.0-cp39-abi3-win_amd64.whl", hash = "sha256:5729c44ce1d60cb03e506731dcb17d8c2d69c267098c3ff35ca8be37d618714d", size = 2767905, upload-time = "2026-05-17T10:32:56.759Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filelock"
|
||||
version = "3.29.0"
|
||||
@@ -374,11 +407,11 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "3.13"
|
||||
version = "3.15"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ce/cc/762dfb036166873f0059f3b7de4565e1b5bc3d6f28a414c13da27e442f99/idna-3.13.tar.gz", hash = "sha256:585ea8fe5d69b9181ec1afba340451fba6ba764af97026f92a91d4eef164a242", size = 194210, upload-time = "2026-04-22T16:42:42.314Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/82/77/7b3966d0b9d1d31a36ddf1746926a11dface89a83409bf1483f0237aa758/idna-3.15.tar.gz", hash = "sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc", size = 199245, upload-time = "2026-05-12T22:45:57.011Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5d/13/ad7d7ca3808a898b4612b6fe93cde56b53f3034dcde235acb1f0e1df24c6/idna-3.13-py3-none-any.whl", hash = "sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3", size = 68629, upload-time = "2026-04-22T16:42:40.909Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1041,6 +1074,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/80/6e/4b28b62ecb6aae56769c34a8ff1d661473ec1e9519e2d5f8b2c150086b26/pre_commit-4.6.0-py2.py3-none-any.whl", hash = "sha256:e2cf246f7299edcabcf15f9b0571fdce06058527f0a06535068a86d38089f29b", size = 226472, upload-time = "2026-04-21T20:31:40.092Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-pydantic-config"
|
||||
version = "0.3.0.dev83"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b3/4e/bcdb244336d3abae60c7767626aaf635ef724bdc3f2cb46e317d11b23d91/prime_pydantic_config-0.3.0.dev83.tar.gz", hash = "sha256:7446e6439ba6de2f2c332acb292ba5b53da7c1a4ad60e4a25b78393b17859fdd", size = 73322, upload-time = "2026-05-24T02:58:49.485Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/1a/6b/372380c6f5cc3a6f0b6690acb453e9aa9d848e8c1ec421e883c1c3c7a293/prime_pydantic_config-0.3.0.dev83-py3-none-any.whl", hash = "sha256:91a8d883181aff069a4a07f56b636c399c32f1814d8177b9e167a8398643e313", size = 26259, upload-time = "2026-05-24T02:58:48.432Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pydantic"
|
||||
version = "2.13.3"
|
||||
@@ -1333,14 +1378,15 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "renderers"
|
||||
version = "0.1.7"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "fastokens" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "openai" },
|
||||
{ name = "openai-harmony" },
|
||||
{ name = "prime-pydantic-config" },
|
||||
{ name = "tiktoken" },
|
||||
{ name = "transformers" },
|
||||
]
|
||||
@@ -1359,10 +1405,12 @@ dev = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "fastokens", specifier = ">=0.2.0" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "numpy" },
|
||||
{ name = "openai", specifier = ">=1.108.1" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.8" },
|
||||
{ name = "prime-pydantic-config", specifier = ">=0.3.0.dev83" },
|
||||
{ name = "tiktoken" },
|
||||
{ name = "transformers", specifier = ">=4.50.0" },
|
||||
]
|
||||
@@ -1799,11 +1847,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]]
|
||||
|
||||
Reference in New Issue
Block a user