* fix(parsing): don't parse in-<think> tool calls as real calls
Reasoning models (Qwen3-*-Thinking, Kimi-K2.5, R1-distill via the
DeepSeek-V3 renderer) routinely draft tool-call syntax *inside* their
<think>...</think> trace while planning. The qwen3, deepseek_v3, and
kimi_k2.5 parsers scanned the whole completion for tool-call delimiters
and only extracted reasoning afterward, so those in-think drafts were
mis-parsed. Symptoms differed by format but all corrupt the tool result:
- qwen3 / qwen3_vl: emits the draft *and* the real call -> phantom
duplicate (the reported #78 case; same code executed twice).
- kimi_k2.5: the in-think section trips the "truncated reasoning" guard
and *all* tool calls are dropped (returns zero).
- deepseek_v3: returns the *wrong* call (the draft) and loses reasoning.
Fix: extract reasoning first, then scan for tool calls only in the
post-</think> region — mirroring vLLM's DelegatingParser (reasoning
parser runs before the tool parser). Where </think> is a single special
token (Qwen3) we anchor on its id; where it's multi-token / context-
sensitive text (DeepSeek-V3, Kimi-K2.5) we locate the boundary by
decoding. content_ids still starts at 0 so reasoning extraction is
unchanged, and genuine parallel calls after </think> are preserved.
Audited all parsers: qwen3.5/glm/minimax/laguna/nemotron3 already strip
reasoning first; gpt_oss (channel-segregated) and llama_3 (no reasoning)
are safe; kimi_k2 (K2-Instruct) has no thinking path so is unaffected.
Validated against real Qwen3, Kimi-K2.5 and DeepSeek-V3 tokenizers.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* style: ruff format
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
runtime_checkable Protocol's isinstance check uses inspect.getattr_static,
which returns property descriptors found on the class regardless of
whether their fget raises AttributeError. The previous implementation
exposed mm_token_type_id_map as a @property that raised AttributeError
for text-only pools — but isinstance still saw the property descriptor
and returned True, so isinstance(text_only_pool, MultimodalRenderer)
incorrectly resolved to True.
Set the attribute conditionally in __init__ instead: present in the
instance __dict__ only for pools wrapping a MultimodalRenderer, which
is what isinstance via getattr_static actually checks against.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- RendererPool now structurally satisfies Renderer (and MultimodalRenderer
when wrapping multimodal renderers) via method delegation, so callers can
use isinstance dispatch and call methods directly without reaching into
checkout().
- size=1 fast path: lock-protected single instance instead of a queue, since
the queue's role for size>1 collapses to a mutex.
- Snapshot supports_tools, is_multimodal, mm_token_type_id_map at
construction so per-call overhead is a struct read.
- is_multimodal(r) helper caches per-type, avoiding runtime_checkable
Protocol's hasattr walk on hot paths (per-bridge dispatch).
- renderers/client.py: drop pool-vs-bare branching ladder; pool method calls
go through asyncio.to_thread via _maybe_offload, bare renderer inline.
_build_mm_features uses pool.renderer_cls snapshot instead of a checkout.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Cleaner Protocol split + uniform bridge return shape across all renderers.
renderers/base.py
- Add `MultimodalRenderer(Renderer, Protocol)`, runtime-checkable.
Marker Protocol for renderers that support image/video content parts.
Carries the two pieces of contract that distinguish multimodal:
1. ``mm_token_type_id_map`` (1 = image_pad, 2 = video_pad) so
consumers can stamp per-token modality markers without re-deriving
2. ``bridge_to_next_turn`` extended with ``previous_multi_modal_data``
kwarg so prior-turn images carry forward into the new prompt's
``mm_placeholders``. Without that carry-forward, vLLM sees
placeholder counts that don't match the combined token sequence
and silently falls back to hash-cache lookup (or errors)
- ``Renderer.bridge_to_next_turn`` return type narrowed: previously
``list[int] | RenderedTokens | None`` (wide union to accommodate both
text-only and multimodal), now uniformly ``RenderedTokens | None``.
Text-only callers read ``bridged.token_ids``; multimodal callers also
read ``bridged.multi_modal_data``. Same shape end-to-end.
- Drop ``as_rendered_tokens`` helper — it existed solely to normalize
the wide union and is no longer needed.
9 text-only renderers (qwen3, glm45, glm5, gpt_oss, deepseek_v3,
minimax_m2, nemotron3, kimi_k2, default):
- Bridge return: ``list[int] | None`` -> ``RenderedTokens | None``
- Wrap ``previous_ids + ext`` in ``RenderedTokens(token_ids=...)``
before returning; default ``message_indices=[]`` since text-only
bridges produce no per-message attribution
2 multimodal renderers (qwen35, kimi_k25):
- Return type narrowed from ``list[int] | RenderedTokens | None`` to
uniform ``RenderedTokens | None``
- No-media branch now wraps tokens in ``RenderedTokens`` instead of
returning bare list
tests/test_bridge.py
- Update slicing assertions from ``bridged[: n]`` to
``bridged.token_ids[: n]`` and use ``bridged.token_ids`` for length
comparisons
renderers/__init__.py
- Export ``MultimodalRenderer``; drop ``as_rendered_tokens``
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
``test_multimodal_bridge_matches_full_render`` asserted that
``bridge_to_next_turn`` produces the same tokens as a fresh
``render()`` of the fully-combined message list. That invariant
held for Qwen3-VL only because Qwen3-VL's gen prompt has nothing
between ``<|im_start|>assistant\n`` and the sampler's first
emitted token. For Qwen3.5 / Qwen3.6 / Kimi K2.5 / K2.6 the gen
prompt bakes in a ``<think>`` prefill that the sampler conditions
on — bridge preserves that verbatim (correctly: it's part of the
sampler-seen prompt), while a fresh re-render does NOT re-emit
``<think>`` for past assistants (matching HF chat-template
semantics — verified against ``tokenizer.apply_chat_template``).
The two paths intentionally diverge on thinking renderers.
The cross-renderer ``test_bridge.py`` already exercises the right
invariant for every renderer: bridge extends ``prev_prompt_ids +
prev_completion_ids`` verbatim. The multimodal version of that
check now lives here as
``test_multimodal_bridge_extends_and_carries_mm_data``, asserting:
1. Verbatim prefix — what the sampler saw is what the trainer
reconstructs.
2. ``mm_data`` carry-forward — prior images survive in merged
``mm_placeholders`` / ``mm_items`` / ``mm_hashes``; new turn's
images get appended.
3. New-turn placeholder lands inside the extension region (offset
>= len(prev), and the modality's pad token id appears in the
post-prefix slice).
These hold for every renderer including thinking-mode ones — no
per-renderer skip needed. 41/41 multimodal tests pass across
Qwen3-VL / Qwen3.5 (x7) / Qwen3.6 / Kimi K2.5 / K2.6.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Kimi K2.5 / K2.6 are unified VLMs (HF tag ``image-text-to-text``)
distinct from Qwen-VL in three ways that drive this change:
1. **Vision wrap is different**:
``<|media_begin|>image<|media_content|><|media_pad|><|media_end|>\n``
per image, with a literal trailing newline emitted by the chat
template after every ``<|media_end|>`` (regardless of what
follows). The renderer matches this byte-for-byte.
2. **One pad per image in ``input_ids``** — not N. The model expands
per-patch attention internally from ``pixel_values`` / ``grid_thws``;
the text stream only carries a single placeholder. ``mm_placeholders``
records ``length=1`` per image accordingly.
3. **Processor needs ``trust_remote_code=True``** + pinned revision.
``KimiK25VisionProcessor`` is custom Python in the model repo;
its ``preprocess`` returns ``pixel_values`` and ``grid_thws``
(Kimi's keys; differ from Qwen-VL's ``image_grid_thw``). The
renderer ships those verbatim in ``mm_items`` so the orchestrator's
generic ``torch.cat`` packer routes them straight into the model's
forward kwargs without any prime-rl-side knowledge of Kimi's
schema. Pool / test loaders gain a per-model trusted-revision
table mirroring ``renderers.base.TRUSTED_REVISIONS``.
Implementation mirrors ``Qwen3VLRenderer``: ``processor`` /
``image_cache_max`` constructor kwargs, FIFO-bounded per-instance
image cache, ``_process_image``, ``mm_token_type_id_map`` property
(only ``<|media_pad|>`` carries marker=1). ``_emit_content`` gains
an opt-in ``emit_image`` callback threaded from the user / tool
content paths in ``render`` and ``bridge_to_next_turn``; text-only
branches keep their current behavior.
``_load_pil_image`` in qwen3_vl.py learns to accept Kimi's
non-standard ``image_url``-as-raw-PIL shape in addition to the
OpenAI canonical ``image_url: {"url": ...}`` dict. Both work; the
helper is family-agnostic.
Tests: byte-parity vs ``KimiK25Processor`` (called with
``messages=`` directly, via the per-family dispatch added in the
previous commit) passes for both K2.5 and K2.6. Placeholder spans
match the actual single-pad runs. The bridge-vs-full test skips
for thinking-mode renderers (same documented reason as Qwen3.5/3.6:
the past gen prompt's ``<think>`` prefill is preserved by bridge
but not re-emitted by a full re-render).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The byte-parity test previously hard-coded the Qwen-VL processor
shape — ``processor(images=, text=)`` after a separate
``apply_chat_template`` — which doesn't fit Kimi K2.5 / K2.6, whose
``KimiK25Processor.__call__`` accepts ``messages=`` directly and runs
template + vision preprocessing in one shot. Kimi also reads
``content_part['image_url']`` even when ``type == 'image'``, so the
test must use the OpenAI-ish shape for that family.
Refactor:
- ``_modality_kit(modality, model_name)`` now picks the family from
``model_name`` and returns a ``make_part`` content-shape builder
alongside a ``processor_input_ids(processor, messages, add_gp)``
callable that runs the family's native processor pipeline.
- Two family hooks today: ``_qwen_vl_processor_input_ids`` (two-step
template + processor) and ``_kimi_processor_input_ids`` (one-shot
``processor(messages=...)``).
- ``_load_processor_and_renderer`` now respects a per-model
``trust_remote_code=True`` + pinned-revision policy for processors
(mirrors ``renderers.base.TRUSTED_REVISIONS`` for tokenizers).
Today only Kimi K2.5 / K2.6 opt in.
No behavior change for the existing Qwen3-VL / Qwen3.5 / Qwen3.6
parity tests — all still pass. The plumbing now lets a Kimi K2.5
renderer drop into ``MULTIMODAL_MODELS`` and automatically get
parity-tested.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Qwen3.5 and Qwen3.6 are themselves unified VLM families (HF tag
``image-text-to-text``; processor class ``Qwen3VLProcessor``;
vision tokens ``<|vision_start|>``+``<|image_pad|>``+``<|vision_end|>``
identical to Qwen3-VL). Previously rendered text-only, silently
dropping any ``ImagePart`` content.
Per-renderer changes mirror ``Qwen3VLRenderer``: ``processor`` /
``image_cache_max`` kwargs, FIFO-bounded image cache, ``_process_image``,
``mm_token_type_id_map`` property. The user branch in ``render()`` /
``bridge_to_next_turn`` dispatches to a buffered media-aware path
only when image parts are present; the text-only fast path remains
bit-identical to the prior renderer output. Qwen3.6 inherits the
new VL capabilities transparently via its ``Qwen35Renderer`` base.
Tests: byte-parity against HF ``processor.apply_chat_template`` +
``processor(...)`` passes for all 7 Qwen3.5 sizes + Qwen3.6-35B-A3B;
placeholder spans match actual pad runs. The bridge-vs-full test
skips for thinking-mode renderers (Qwen3.5/3.6) with a documented
reason: the past gen prompt's ``<think>\n`` opener is preserved by
bridge but never re-emitted by a full re-render — verified against
``tokenizer.apply_chat_template`` as HF-template semantics, not a
renderer bug.
Also:
- ``Qwen3VLRenderer``: ``image_cache_max`` is now a constructor kwarg
(default 256, prior behavior).
- ``renderers/client.py::_build_mm_features``: docstring note that the
vLLM-specific encoder will need pluggability (per-renderer methods or
call-site strategy) when a second inference engine arrives. YAGNI today.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add `mm_token_type_id_map` property so the orchestrator can build per-token
modality markers (1=image, 2=video) from the renderer's vocab IDs without
loading a separate processor. Add a per-instance hashed image cache so
repeated images (same input across rollouts_per_example, or carried-forward
turns) hit a memoized HF image_processor result instead of reprocessing.
Lift the auto-renderer fallback in `create_renderer` for VLMs: raise loudly
when the tokenizer points at a model with vision config but no Qwen3VLRenderer-style
entry in MODEL_RENDERER_MAP. Silent fallback to DefaultRenderer is wrong for
VLM training and surfaces as cryptic shape errors downstream.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds image content parts, a multi-modal sidecar on RenderedTokens, and
real image handling in Qwen3VLRenderer (it had been text-only by
design). Token output is byte-identical to Qwen3VLProcessor.apply_chat_template
+ processor(images=, text=); placeholder ranges and per-item processed
tensors flow through MultiModalData so the inference glue can build
vLLM's /inference/v1/generate features payload.
Pieces:
- base.py: ImagePart / VideoPart TypedDicts; MultiModalData
(mm_hashes, mm_placeholders, mm_items); RenderedTokens.multi_modal_data;
MULTIMODAL_MODELS registry (Qwen3-VL family); as_rendered_tokens
normalizer for the bridge return-type union; build_trajectory_step
now surfaces mm_data
- qwen3_vl.py: _Emitter buffers text between special tokens so BPE
merges match the chat template's continuous-string output; image
parts run through the processor at render-time and expand to
vision_start + N×image_pad + vision_end with N = grid_thw.prod() //
merge_size**2; bridge_to_next_turn accepts previous_multi_modal_data
and merges
- client.py: generate() forwards features alongside token_ids and
surfaces mm_data on the result; _build_qwen_vl_features serializes
per-image dicts → MultiModalKwargsItems → base64 via vLLM's mm_serde
(lazy import — text-only path doesn't pay for vllm)
- tests/test_multimodal.py: parametrized (model, modality) parity
matrix — three Qwen3-VL sizes, four message scenarios; placeholder
anchoring; bridge byte-parity
- tests/test_client.py: features payload roundtrip through real vLLM
types when available (skipped here)
950 tests pass (939 existing + 11 new); existing text-only renderer
parity intact.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: drop legacy chat-template-pass-through kwargs
``GLM5Renderer.__init__`` no longer accepts ``clear_thinking``, and
``Qwen36Renderer.__init__`` no longer accepts ``preserve_thinking``.
Both were chat-template-kwarg pass-throughs whose default values are
now baked straight into the renderer:
- GLM-5 default: drop ``<think>`` on past-cycle assistants, keep on
in-flight cycle and trailing assistant. (What ``clear_thinking=True``
did before.) The render gate is now ``msg_idx > last_user_index or
preserve_thinking`` — clean and consistent with the rest of the
family.
- Qwen3.6 default: identical to Qwen3.5 (``msg_idx > last_query_index``
via the inherited ``_should_render_thinking``). The class shrinks to
just the ``_render_arg_value`` override, which is the only real
template delta vs Qwen3.5.
Callers who want the toggled-on behaviour pass
``preserve_all_thinking=True`` to ``create_renderer`` — the
renderer-agnostic spelling of the same intent landed in #3/#5. Two
regression tests pin the dropped kwargs (constructor must raise
``TypeError`` when either is passed).
The README's §1 "Preserving past reasoning" subsection (added in #5)
already motivates the override flags; no new prose needed here. §3.d
is unchanged (still cross-links to the override flag for compaction).
Bump 0.1.9 → 0.1.10. 895 tests pass locally.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: consolidate version to 0.1.6 (PyPI-aligned)
PyPI's latest published renderers is 0.1.5 — the in-tree bumps in #3 →
#5 → this PR (0.1.6 → 0.1.7 → 0.1.8 → 0.1.9 → 0.1.10) accumulated
against PyPI without ever publishing. Roll forward to 0.1.6 once for
the actual release; tag ``renderers-v0.1.6`` post-merge to fire the
publish workflow (.github/workflows/publish.yml asserts the tag's
``-vX.Y.Z`` suffix matches pyproject.toml).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replace the OpenAI-chat-completions-shaped ``completions_request`` with
a lean ``generate()`` built around what /inference/v1/generate actually
exposes:
- Structured ``sampling_params: dict`` arg, forwarded to vLLM verbatim.
No more ``extra_body`` fallback, no ``_SAMPLING_KEYS`` allowlist, no
``max_completion_tokens`` ↔ ``max_tokens`` aliasing — those are
OpenAI-SDK habits that don't apply here.
- Top-level ``cache_salt`` / ``priority`` / ``extra_headers`` as named
args (matching the wire shape, no rummaging through extra_body).
- Result dict drops the ChatCompletion-shaped fillers (``id``,
``created``, ``model``, ``usage``); keeps ``request_id`` (the actual
field /inference/v1/generate returns) and the renderer-specific
fields (content, reasoning_content, tool_calls, finish_reason,
prompt/completion_ids, completion_logprobs, routed_experts).
- ``stop_token_ids`` (from the renderer) and ``logprobs=1`` are forced
by us; everything else flows through.
Kept: the ``finish_reason: stop → tool_calls`` promotion when the
renderer extracts tool calls client-side (downstream agent loops
genuinely depend on it), the AsyncOpenAI transport (auth + retries),
and the overlong-prompt 4xx diagnostic.
Bump version 0.1.5 → 0.1.6 — the wire format change is a break against
v0.1.5 (which targets the legacy /generate route). Tag renderers-v0.1.6
to publish.
Lifted from PrimeIntellect-ai/verifiers#1282 packages/renderers/ now
that this package lives in its own repo.
Trigger: push of a tag matching renderers-v* (or manual workflow_dispatch
with a tag input). Validates that the tag's version matches
pyproject.toml's project.version, then ``uv build`` + ``uv publish``.
Ported from PrimeIntellect-ai/verifiers's publish-renderers.yml — paths
adjusted now that renderers is its own repo (no more packages/renderers/
prefix). Same PYPI_RENDERERS_TOKEN secret name; needs to be configured
on this repo before the first release.
Mirror verifiers' local-hook pattern: ruff check/format on commit, ty
check on push (matches CI). Add ``pre-commit`` to the dev dep group
so ``uv sync`` installs it.