Skip to content

feat(thinking): replace preserve_* bools with thinking_retention, respected by the bridge - #88

Merged
eligotts merged 24 commits into
mainfrom
refactor/thinking-retention
Jun 26, 2026
Merged

eligotts merged 24 commits into
mainfrom
refactor/thinking-retention

Conversation

@hallerite

@hallerite hallerite commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

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_retention is an optional generic bridge policy on the config:

thinking_retention: Literal["tool_cycle", "all"] | None = None
  • 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 a self.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 omit thinking_retention for 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 explicit thinking_retention if set, else the renderer's implied default.
  • 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 own is_user_query predicate.

What Changed

  • Removed the legacy config booleans preserve_all_thinking and preserve_thinking_between_tool_calls.
  • Removed runtime token-lookback heuristics for thinking retention.
  • Removed per-renderer supported-retention lists; all typed renderers can accept an explicit tool_cycle / all bridge policy.
  • Added shared init-time resolution (resolve_thinking_retention) and shared bridge decision logic (should_rerender_for_thinking_retention).
  • Each renderer now computes self.effective_thinking_retention in __init__ and consults should_rerender_for_thinking_retention in its bridge path, returning None (→ full re-render) at a new user-query boundary under "tool_cycle".
  • Kept full render() output faithful to each Python chat-template implementation; generic thinking_retention does not synthesize or preserve historical thinking during a full render.
  • DefaultRenderer rejects explicit generic thinking_retention (and legacy preserve_* keys), because its bridge is opaque and cannot faithfully implement the policy.

Factory: chat_template_kwargs

create_renderer and create_renderer_pool gain a keyword-only chat_template_kwargs:

create_renderer(tokenizer, config=None, *, chat_template_kwargs=None)
create_renderer_pool(tokenizer_name_or_path, config=None, *, size=16, chat_template_kwargs=None)
  • With an explicit typed config: the kwargs are merged into the config and re-validated (model_validate), so a kwarg that contradicts thinking_retention still raises at construction.
  • With auto / None config: the concrete config is first resolved from tokenizer.name_or_path, then the kwargs are merged and validated against it.
  • Auto config + kwargs for an unknown model now raises instead of silently falling back to DefaultRenderer — pass an explicit typed config (or DefaultRendererConfig) for opaque apply_chat_template kwargs.

Renderer Mapping

When thinking_retention is unset, each renderer derives its default bridge policy from the knobs its template actually exposes:

  • Qwen3: enable_thinking=False -> all, otherwise tool_cycle.
  • Qwen3.5 / Qwen3.6: preserve_thinking=True -> all; else enable_thinking=False -> all; else tool_cycle.
  • GLM-5 / GLM-5.1: clear_thinking=False -> all; else enable_thinking=False -> all; else tool_cycle.
  • GLM-4.5: enable_thinking=False -> all; otherwise tool_cycle.
  • Nemotron-3 / Ultra: truncate_history_thinking=False -> all; else enable_thinking=False -> all; else tool_cycle.
  • Kimi K2.5 / K2.6: thinking=False -> all; otherwise tool_cycle.
  • GPT-OSS / Harmony: auto_drop_analysis=False -> all; otherwise tool_cycle.
  • DeepSeek V3, Qwen3-VL, Kimi K2, Laguna XS.2, Llama 3: default to all — no relevant historical-thinking eviction hazard.
  • DeepSeek R1: defaults to internal template; explicit generic tool_cycle / all is still available as a bridge-policy override.
  • MiniMax M2: defaults to tool_cycle; its template has <think> handling but no no-thinking or preserve-thinking kwarg to derive all from.

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=False with thinking_retention="tool_cycle" is invalid — the template knob means keep all history thinking.
  • clear_thinking=True with thinking_retention="all" is invalid — the template knob means drop historical thinking across user turns.

Generation-only no-thinking knobs such as enable_thinking=False do not conflict with an explicit conservative thinking_retention="tool_cycle"; they only influence the implied default when thinking_retention is unset.

Breaking Changes

Legacy preserve_* config keys are no longer accepted. Migrate downstream configs as follows:

Old New
unset omit thinking_retention — the renderer derives behavior from template kwargs
preserve_thinking_between_tool_calls=True thinking_retention="tool_cycle"
preserve_all_thinking=True thinking_retention="all"

Also: public thinking_retention="template" is no longer accepted. Use unset / None for template-derived behavior.

Validation

  • pytest tests/test_renderer_config.py -q
  • pytest tests/test_preserve_thinking.py -q
  • pytest tests/test_bridge.py -q
  • pytest tests/test_renderer_config_parity.py -q
  • ruff check .
  • ruff format --check .
  • git diff --check

Note

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_thinking and preserve_thinking_between_tool_calls are removed in favor of optional thinking_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 / DefaultRendererConfig reject explicit thinking_retention and legacy preserve_* keys.

Bridge vs full render: Shared helpers resolve_thinking_retention and should_rerender_for_thinking_retention resolve effective_thinking_retention at construction and make hand-coded renderers return None from bridge_to_next_turn when policy requires a full re-render (e.g. new user query under "tool_cycle"). Full render() no longer ORs in preserve overrides—historical thinking follows the Python template only; Qwen3.6 gains a typed preserve_thinking template field.

Factory API: create_renderer and create_renderer_pool accept keyword-only chat_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.md document the contract and per-renderer defaults; bridge/multimodal tests often force thinking_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 with thinking_retention policy across all renderers and the bridge

  • Removes preserve_all_thinking and preserve_thinking_between_tool_calls from BaseRendererConfig and replaces them with a single thinking_retention field ('tool_cycle' | 'all'), resolved at instantiation time via resolve_thinking_retention in renderers/base.py.
  • Each renderer now computes self.effective_thinking_retention in __init__ and uses should_rerender_for_thinking_retention in its append/extend path to return None (triggering a full re-render) when a new user-query boundary is detected under 'tool_cycle' policy.
  • Per-renderer config classes (Qwen36, GLM5/5.1, GptOss, Nemotron3, etc.) gain after-validators that raise ValueError on conflicting combinations of template-level knobs and thinking_retention.
  • create_renderer and create_renderer_pool gain a chat_template_kwargs parameter that is merged into and validated against the resolved concrete config.
  • DefaultRendererConfig now rejects both thinking_retention and legacy preserve_* flags, since DefaultRenderer cannot implement a bridge policy.
  • Risk: existing code passing preserve_all_thinking or preserve_thinking_between_tool_calls will receive a ValueError at construction time instead of silently being accepted.

Macroscope summarized ea88615.

@hallerite
hallerite force-pushed the refactor/thinking-retention branch from ce78cae to 5d18ccf Compare June 18, 2026 04:53
Comment thread renderers/default.py Resolved
@macroscopeapp

macroscopeapp Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Approvability

Verdict: 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]>
@hallerite
hallerite force-pushed the refactor/thinking-retention branch from 5d18ccf to d163ef3 Compare June 18, 2026 05:18
@hallerite hallerite changed the title refactor(config): replace preserve_*_thinking bools with thinking_retention feat(thinking): replace preserve_* bools with thinking_retention, respected by the bridge Jun 19, 2026
…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]>
@hallerite
hallerite force-pushed the refactor/thinking-retention branch from 44117ee to efece49 Compare June 19, 2026 20:56
…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]>
Comment thread renderers/base.py Resolved
hallerite and others added 4 commits June 19, 2026 21:48
…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.
Comment thread renderers/glm5.py Resolved
…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]>
Comment thread renderers/minimax_m2.py Resolved
hallerite and others added 10 commits June 22, 2026 21:46
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
Comment thread renderers/qwen3.py Resolved
Comment thread renderers/qwen3_vl.py Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

❌ 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.

Comment thread renderers/qwen35.py Resolved
@eligotts
eligotts merged commit a5efbb9 into main Jun 26, 2026
11 checks passed
@eligotts
eligotts deleted the refactor/thinking-retention branch June 26, 2026 22:14
joanvelja added a commit to joanvelja/renderers that referenced this pull request Jun 27, 2026
…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]>
joanvelja added a commit to joanvelja/renderers that referenced this pull request Aug 10, 2026
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants