Repository navigation
feat(thinking): replace preserve_* bools with thinking_retention, respected by the bridge - #88
Conversation
ce78cae to
5d18ccf
Compare
ApprovabilityVerdict: Needs human review This PR replaces boolean thinking-retention flags with a new enum-based bridge policy across all renderers, changing runtime behavior for when bridges are attempted vs declined. Two unresolved review comments identify potential bugs in the implementation. The scope and behavioral impact warrant human review. You can customize Macroscope's approvability policy. Learn more. |
…ention
The two booleans `preserve_all_thinking` and
`preserve_thinking_between_tool_calls` were confusing: `False` never
meant "drop", it meant "defer to the chat template", and the second flag
was a strict subset of the first — so four bool combos collapsed to three
real states with one nonsensical combination.
Replace both with a single ordinal field whose default names the floor:
thinking_retention: Literal["template", "tool_cycle", "all"] = "template"
- "template" (default) — defer entirely to the chat template (the floor;
never drops)
- "tool_cycle" — also keep thinking in the in-flight tool cycle
- "all" — also keep all past thinking
This makes the baseline explicit (no value reads as "drop"), encodes the
"all" ⊇ "tool_cycle" ⊇ "template" nesting, and removes the redundant
combo. `should_preserve_past_thinking` now branches on the level; all 8
renderer call sites, the auto carry-over/guard, and DefaultRenderer's
guard are updated.
Breaking change: the old boolean keys are no longer accepted — `extra=
"forbid"` rejects them at config-load. Downstream TOML/configs (prime-rl,
verifiers) must migrate to `thinking_retention`.
Also fixes a stale Llama3RendererConfig docstring that claimed the flags
raise; the renderer treats them as no-ops (matched by test_llama_3.py).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
5d18ccf to
d163ef3
Compare
…daries Qwen3's template drops a past assistant block's thinking once a new user turn arrives, but bridge_to_next_turn carried prior tokens verbatim — so a multi-turn RL rollout kept <think> the template strips, feeding the model context its own template would never produce (unfaithful to the chat template / native serving distribution). The bridge now consults thinking_retention: when the prior turns carry sampled thinking and new_messages opens a real user query (not a tool response), it declines under "template"/"tool_cycle" so the caller re-renders — which honors thinking_retention and drops the stale thinking, byte-faithful to apply_chat_template. thinking_retention="all" keeps thinking on every path, and in-flight tool cycles (no new user query) still bridge verbatim, matching the template there too. Adds shared introduces_user_query helper (sibling to reject_assistant_in_extension) and a regression test diffing the bridge decision + fallback render against the chat template. Qwen3 only for now; glm45/glm5/qwen35/qwen36/nemotron3/minimax to follow. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
44117ee to
efece49
Compare
…5/nemotron3 bridges Extract the qwen3 bridge faithfulness check into a shared reject_thinking_strip_in_extension (base.py) and wire it into every token-based thinking renderer: a bridge refuses to span a new user-query boundary while carrying a <think> block the template strips, so the caller re-renders faithfully. thinking_retention="all" keeps thinking on every path (no decline); in-flight tool cycles still bridge verbatim. - qwen36 inherits qwen35's bridge. - glm5/nemotron3: the guard is correct regardless of the clear_thinking / truncate_history_thinking kwargs (it only over-declines, never keeps unfaithfully, in the clear_thinking=False + retention!="all" combo). - Parametrized regression test across all guarded renderers. Deferred (need different detection): kimi_k25 (multi-token </think>), gpt_oss (harmony analysis channel); minimax has no bridge (always re-renders). Reconciliation of clear_thinking/truncate_history_thinking vs thinking_retention (raise-on-conflict) to follow. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…aise on thinking-kwarg conflict Generalize reject_thinking_strip_in_extension to a token-subsequence marker (_contains_subsequence) so it covers every thinking renderer: - kimi_k25: multi-token </think> (passes self._think_close_ids). - gpt_oss: harmony analysis-channel header <|channel|>analysis<|message|>. - qwen3/qwen35/glm45/glm5/nemotron3 now pass [self._think_end]. Reconcile the per-renderer template thinking-kwargs with thinking_retention: they're byte-equivalent (clear_thinking=False / truncate_history_thinking=False mean keep-all, i.e. thinking_retention="all"), so a model_validator on GLM5/GLM51/Nemotron3/Nemotron3Ultra raises when both are explicitly set to conflicting values. It only fires when BOTH are explicit, so the per-kwarg parity matrix (which sets one field at a time) keeps working. Tests: breadth bridge-decline test now covers Kimi-K2.5 + gpt-oss-20b; new config validator test. minimax has no bridge (already faithful); deepseek_r1 strips unconditionally (no override, edge case). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e keep-history toggles Bug 1 (DefaultRenderer legacy flags slip through): DefaultRendererConfig is extra="allow", so the removed preserve_*_thinking bools landed in model_extra and were forwarded to apply_chat_template silently (the guard only checked thinking_retention). Add a model_validator that rejects them with a migration message, matching every other config's extra="forbid" rejection. Bug 2 (bridge guard ignores keep-history toggles): the guard declined a user-query boundary whenever thinking_retention != "all", ignoring GLM clear_thinking=False / Nemotron truncate_history_thinking=False — which keep all past thinking. Set alone (retention defaulted), that over-declined into a full re-render that re-tokenizes model-sampled thinking bytes. Fold the toggle into the effective retention in the glm5 / nemotron3 bridges so they keep verbatim when the template keeps all thinking. Tests: test_default_renderer_config_rejects_legacy_preserve_flags; test_bridge_keeps_thinking_when_history_kwarg_disables_truncation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…retention is the override Renderers exist to faithfully reproduce each model's chat template (via per-renderer assumptions). The bridge preserves sampled tokens verbatim as a means to that (avoid bool/BPE/XML corruption of model output), not a license to diverge from how the template renders history. - Drop "thinking stripped from non-latest assistants" from the bridge's avoided-failure-modes list — that's intended template behaviour the renderer now reproduces (bridge declines a user-query boundary; caller re-renders faithfully), not token-identity corruption like the other entries. - thinking_retention reframed as the explicit override, honoured end-to-end (render() + bridge); an explicit keep-history kwarg contradicting thinking_retention raises rather than silently OR-resolving. - Roadmap: auto-stripping thinking is intended behaviour, not a use_patched target. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Brings in PR #90 (ungated Llama-3.2 tokenizer mirrors + canonical Llama classified preserve-thinking no-op). Conflict in tests/test_preserve_thinking.py resolved: keep the renamed thinking_retention wording, add the canonical meta-llama no-op entries from main.
…e marker rename Generalizing the bridge guard to thinking_marker_ids replaced `think_end_id=self._think_end` with a global string substitution that also rewrote the parse_glm / parse_qwen35 calls in parse_response (not just the bridge guards). That broke parsing for glm45/glm5/nemotron3/qwen35 — 444 CI failures across test_parse_response[_robustness], test_roundtrip and test_tool_arg_type_preservation, plus 4 ty missing-argument errors. Revert the four parse calls to think_end_id=self._think_end; the bridge guards keep thinking_marker_ids=[self._think_end]. (Local subset runs missed it because test_parse_response* wasn't in the subset.) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
MiniMaxM2Renderer does have a bridge_to_next_turn (an earlier audit wrongly classified it as bridge-less and excluded it), and like the others its render drops past thinking across a user turn while the bridge carried it verbatim. Wire reject_thinking_strip_in_extension (single </think> token; MiniMax always thinks, no enable-thinking toggle) and add MiniMax-M2.5 to the parametrized breadth test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…oundary [codex] Resolve renderer thinking retention at init
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 24b81ee. Configure here.
…ens removal PrimeIntellect-ai#95, dyn-versioning PrimeIntellect-ai#96) + migrate gemma4 (#10) * adopt verifiers-style dynamic versioning (PrimeIntellect-ai#96) * remove fastokens entirely for now (PrimeIntellect-ai#95) * feat(thinking): replace preserve_* bools with thinking_retention, respected by the bridge (PrimeIntellect-ai#88) * migrate gemma4 to thinking_retention (render+bridge, implied=all; debate hot path 1:1, full-render keeps thinking) + fastokens test fix --------- Co-authored-by: hallerite <[email protected]>
Unites all three renderer lineages ahead of the prime-rl 0.8.0 sync: - 4354613 our pin (Gemma 4 incl. 12B, PrimeIntellect-ai#115 vLLM token-serving import fix) - 2a7e77e upstream/main (Laguna M.1 renderer) - af3d508 fork main (kv session liveness fields, #11) All 10 conflicted files resolved to the upstream-sync side. af3d508's own commit touches only renderers/client.py and tests/test_client.py, both of which auto-merged cleanly; every conflict came from 9de2e8d, an independent upstream sync on fork main that is strictly behind this lineage (thinking retention PrimeIntellect-ai#88 is common ancestry — present in all three refs — while overlap_is_content, the Laguna M.1 renderer and the qwen3/qwen35 empty-think token-stability fix exist only here).

What
Replace the old thinking-preservation booleans with a single bridge-policy concept,
thinking_retention, and resolve that policy once at renderer construction time from either an explicit generic override or each renderer's real chat-template knobs.The goal: keep full
render()byte-faithful to the model's chat template, while making incremental RL bridge behavior explicit, predictable, and consistent across every renderer.Key Contract
thinking_retentionis an optional generic bridge policy on the config:None/ unset: derive the effective policy from renderer-specific template kwargs and defaults."tool_cycle": bridge through an in-flight assistant/tool cycle, but decline bridging when the extension opens a new user query."all": bridge across user-query boundaries whenever the bridge is otherwise structurally valid.Each renderer resolves these at
__init__into aself.effective_thinking_retention, one of:"template": never bridge for retention purposes; caller falls back to a full re-render."tool_cycle": bridge unless the new extension introduces a user query."all": retention policy never blocks bridging."template"is internal only. Public configs should omitthinking_retentionfor template-derived behavior, or set"tool_cycle"/"all"to override bridge policy.Two shared helpers own this end-to-end:
resolve_thinking_retention(config, implied)— applied at construction: returns the explicitthinking_retentionif set, else the renderer'simplieddefault.should_rerender_for_thinking_retention(retention, new_messages, *, is_user_query=...)— applied in the bridge:"template"→ always re-render,"all"→ never block,"tool_cycle"→ re-render only at a new user-query boundary. Renderers with a narrower notion of "query boundary" (e.g. Qwen3-VL) pass their ownis_user_querypredicate.What Changed
preserve_all_thinkingandpreserve_thinking_between_tool_calls.tool_cycle/allbridge policy.resolve_thinking_retention) and shared bridge decision logic (should_rerender_for_thinking_retention).self.effective_thinking_retentionin__init__and consultsshould_rerender_for_thinking_retentionin its bridge path, returningNone(→ full re-render) at a new user-query boundary under"tool_cycle".render()output faithful to each Python chat-template implementation; genericthinking_retentiondoes not synthesize or preserve historical thinking during a full render.DefaultRendererrejects explicit genericthinking_retention(and legacypreserve_*keys), because its bridge is opaque and cannot faithfully implement the policy.Factory:
chat_template_kwargscreate_rendererandcreate_renderer_poolgain a keyword-onlychat_template_kwargs:config: the kwargs are merged into the config and re-validated (model_validate), so a kwarg that contradictsthinking_retentionstill raises at construction.Noneconfig: the concrete config is first resolved fromtokenizer.name_or_path, then the kwargs are merged and validated against it.DefaultRenderer— pass an explicit typed config (orDefaultRendererConfig) for opaqueapply_chat_templatekwargs.Renderer Mapping
When
thinking_retentionis unset, each renderer derives its default bridge policy from the knobs its template actually exposes:enable_thinking=False -> all, otherwisetool_cycle.preserve_thinking=True -> all; elseenable_thinking=False -> all; elsetool_cycle.clear_thinking=False -> all; elseenable_thinking=False -> all; elsetool_cycle.enable_thinking=False -> all; otherwisetool_cycle.truncate_history_thinking=False -> all; elseenable_thinking=False -> all; elsetool_cycle.thinking=False -> all; otherwisetool_cycle.auto_drop_analysis=False -> all; otherwisetool_cycle.all— no relevant historical-thinking eviction hazard.template; explicit generictool_cycle/allis still available as a bridge-policy override.tool_cycle; its template has<think>handling but no no-thinking or preserve-thinking kwarg to deriveallfrom.Conflict Handling
Invalid configs fail at typed config construction (
_reject_thinking_retention_conflict) when a real template knob directly contradicts an explicit generic bridge policy:clear_thinking=Falsewiththinking_retention="tool_cycle"is invalid — the template knob means keep all history thinking.clear_thinking=Truewiththinking_retention="all"is invalid — the template knob means drop historical thinking across user turns.Generation-only no-thinking knobs such as
enable_thinking=Falsedo not conflict with an explicit conservativethinking_retention="tool_cycle"; they only influence the implied default whenthinking_retentionis unset.Breaking Changes
Legacy
preserve_*config keys are no longer accepted. Migrate downstream configs as follows:thinking_retention— the renderer derives behavior from template kwargspreserve_thinking_between_tool_calls=Truethinking_retention="tool_cycle"preserve_all_thinking=Truethinking_retention="all"Also: public
thinking_retention="template"is no longer accepted. Use unset /Nonefor template-derived behavior.Validation
pytest tests/test_renderer_config.py -qpytest tests/test_preserve_thinking.py -qpytest tests/test_bridge.py -qpytest tests/test_renderer_config_parity.py -qruff check .ruff format --check .git diff --checkNote
Medium Risk
Breaking config renames and changed bridge decline/extend behavior at user-query boundaries affect multi-turn RL rollouts; full renders are intentionally unchanged but callers must migrate from
preserve_*flags.Overview
Breaking config migration:
preserve_all_thinkingandpreserve_thinking_between_tool_callsare removed in favor of optionalthinking_retention("tool_cycle"|"all"| unset). Unset values derive bridge behavior from each renderer’s real template knobs (e.g.clear_thinking,truncate_history_thinking,preserve_thinking,auto_drop_analysis); conflicting explicit template + retention pairs fail at pydantic construction.DefaultRenderer/DefaultRendererConfigreject explicitthinking_retentionand legacypreserve_*keys.Bridge vs full render: Shared helpers
resolve_thinking_retentionandshould_rerender_for_thinking_retentionresolveeffective_thinking_retentionat construction and make hand-coded renderers returnNonefrombridge_to_next_turnwhen policy requires a full re-render (e.g. new user query under"tool_cycle"). Fullrender()no longer ORs in preserve overrides—historical thinking follows the Python template only; Qwen3.6 gains a typedpreserve_thinkingtemplate field.Factory API:
create_rendererandcreate_renderer_poolaccept keyword-onlychat_template_kwargs, merged and validated after auto-resolution; unknown models with auto + kwargs error instead of silently falling back.Docs & tests: README and
docs/renderer-config.mddocument the contract and per-renderer defaults; bridge/multimodal tests often forcethinking_retention="all"to isolate extension mechanics; preserve-thinking tests shrink to “retention must not change full render.”Reviewed by Cursor Bugbot for commit ea88615. Bugbot is set up for automated code reviews on this repo. Configure here.
Note
Replace
preserve_*flags withthinking_retentionpolicy across all renderers and the bridgepreserve_all_thinkingandpreserve_thinking_between_tool_callsfromBaseRendererConfigand replaces them with a singlethinking_retentionfield ('tool_cycle'|'all'), resolved at instantiation time viaresolve_thinking_retentionin renderers/base.py.self.effective_thinking_retentionin__init__and usesshould_rerender_for_thinking_retentionin its append/extend path to returnNone(triggering a full re-render) when a new user-query boundary is detected under'tool_cycle'policy.Qwen36,GLM5/5.1,GptOss,Nemotron3, etc.) gain after-validators that raiseValueErroron conflicting combinations of template-level knobs andthinking_retention.create_rendererandcreate_renderer_poolgain achat_template_kwargsparameter that is merged into and validated against the resolved concrete config.DefaultRendererConfignow rejects boththinking_retentionand legacypreserve_*flags, sinceDefaultRenderercannot implement a bridge policy.preserve_all_thinkingorpreserve_thinking_between_tool_callswill receive aValueErrorat construction time instead of silently being accepted.Macroscope summarized ea88615.