Skip to content

ChatSession: keep the cached transcript canonical on continuation turns - #414

Closed
fdagostino wants to merge 3 commits into
ml-explore:mainfrom
fdagostino:pr/upstream-continuation-turns
Closed

fdagostino wants to merge 3 commits into
ml-explore:mainfrom
fdagostino:pr/upstream-continuation-turns

Conversation

@fdagostino

@fdagostino fdagostino commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem

ChatSession keeps prior turns in the KV cache as raw tokens, and two behaviors interact so that continuation turns can append to a malformed transcript:

  1. A truncated generation leaves a dangling model turn in the cache. A caller that stops consuming mid-stream (e.g. voice barge-in) — or a generation capped by maxTokens — leaves the cached turn cut off mid-sentence, with no turn terminator. (A normally completed turn is fine: the sampled stop token is fed through the model before the generate loop recognizes it, so it is already in the cache.)
  2. Templates that begin with {{ bos_token }} re-emit <bos> on every render (Gemma's chat template does), so every continuation prompt injects a spurious <bos> mid-transcript.

Chat templates only render the messages they are given, so nothing ever repairs this: after an interruption the effective transcript the model sees is

…truncated repl<bos><|turn>user
next message…

instead of the canonical

…truncated repl<turn|>
<|turn>user
next message…

In practice the duplicate <bos> alone is often invisible on short text-only chats, but after an interruption the malformed transcript can push Gemma 4 into emitting its <|channel>thought channel or degenerate output (reproduced with mlx-community/gemma-4-12B-it-4bit). With the repair in place, post-interruption turns stay clean — validated on-device in a voice-assistant app with real barge-in.

Fix

The split follows the layering @aleroot suggested in review: the session determines the semantics, the model side owns the template mechanics. Callers never see or set template syntax.

  • New ModelConfiguration.ContinuationPolicy (truncatedTurnClosure, stripsRepeatedBOS) — model-side knowledge, declared alongside the template knowledge that already lives there (extraEOSTokens, toolCallFormat). The Gemma 3 / Gemma 4 registrations declare it ("<end_of_turn>\n" / "<turn|>\n").
  • ChatSession only determines: is this pass a continuation (live KV-cache offset, so the tool-dispatch restart is covered), and did the previous turn complete or truncate (tracked GenerateStopReason, pessimistically reset at pass start). It then applies the model's policy: the turn closure only for truncated turns (completed turns already carry their terminator in the cache), the BOS strip only when the first prompt token equals the tokenizer's BOS.
  • No policy ⇒ no repair: models that don't declare a ContinuationPolicy get zero behavior change, which also resolves the earlier concern about the BOS-strip default.
  • Tokenizer.bosTokenId convenience, mirroring the existing eosTokenId.

The token-level repair itself runs in one place (repairContinuation), after processor.prepare, handling both token-tensor shapes (rank-1 text / rank-2 VLM) and preserving a nil mask.

Testing

  • Deterministic unit tests for repairContinuation (rank-1/rank-2, BOS edge cases, closure prepending, mask handling) plus policy-plumbing tests (default configuration has no policy; Gemma registrations carry the right closures).
  • xcodebuild build-for-testing + MLXLMTests via xcrun xctest (same as CI) pass on this branch.
  • Deterministic A/B at temperature 0 on Gemma 4 12B: without repair, continuation turns show <bos> duplication and post-interruption thought-channel leakage; with repair, transcripts are canonical and the leakage disappears. Validated on-device (iPad, voice barge-in scenario).

The KV cache stores prior turns as raw tokens and always ends mid
model-turn: the stop token is sampled but never fed through the model,
and a cancelled generation (barge-in) stops anywhere. Chat templates
only render the messages they are given, so nothing ever closes the
dangling model turn, and templates that begin with {{ bos_token }}
re-emit <bos> on every render — every continuation turn was appended
as `…reply<bos><|turn>user…`, a malformed transcript that degrades
multimodal turns and can push Gemma 4 into its thought channel after
an interruption.

- New `continuationTurnClosure`: when set (e.g. "<turn|>\n" for
  Gemma 4), prepends the model-turn closure to each continuation
  prompt, healing normal and cancellation-truncated turns alike.
- New `stripsContinuationBOS` (default true): drops the duplicate
  leading BOS from continuation prompts.
- `Tokenizer.bosTokenId` convenience, mirroring `eosTokenId`.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Comment thread Libraries/MLXLMCommon/ChatSession.swift Outdated
isContinuation
? repairContinuation(
preparedInput, tokenizer: tokenizer,
closure: continuationTurnClosure,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Does this double-close normally completed turns? TokenIterator.next() calls step(previous: previousY) before yielding previousY, and step feeds that token into the model/KV cache. Therefore a generated EOS token is already cached before generateLoopTask recognizes it as a stop token. Prepending <end_of_turn> / <turn|> here would add a second terminator on every normal completed response...

closure: String?, stripBOS: Bool
) -> LMInput {
var tokens = input.text.tokens
guard tokens.ndim == 2, tokens.dim(1) > 0 else { return input }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This makes the repair a no-op for the default LLMUserInputProcessor, which returns LMInput(tokens: MLXArray(promptTokens)) with rank-1 tokens. Standard text LLM sessions therefore receive neither BOS stripping nor the closure.

Comment thread Libraries/MLXLMCommon/ChatSession.swift Outdated
closure: continuationTurnClosure,
stripBOS: stripsContinuationBOS)
: preparedInput
isContinuation = false

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This remains false across the toolDispatch continue restart path, even though the same KV cache is non-empty. As a result, the prompt containing the automatic tool result bypasses repairContinuation.

@aleroot

aleroot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

I was looking into this issue as well, as I have encountered it with Gemma 12B, but I do not think this implementation is ready to merge yet: it makes assumptions about cache boundaries and token tensor shape that do not hold across the existing processor/session paths, and it may double-append a turn terminator after normal EOS completion.

In addition I strongly suggest to add unit tests as this is a tricky are to play with...

…epair tool-dispatch restarts

- The turn closure is now prepended only when the previous generation
  did not finish with a stop token: a completed turn already has its
  terminator in the KV cache (the iterator feeds each sampled token
  through the model before the loop recognizes it as a stop), so the
  unconditional closure would have duplicated it. The session tracks
  the last pass's GenerateStopReason, pessimistically reset at pass
  start so a generation that dies unreported counts as truncated.
- repairContinuation normalizes rank-1 token tensors (the default
  text-only processor shape) to [1, N] and restores the rank on the
  way out, so standard LLM sessions get the repair too; a nil mask
  stays nil instead of being fabricated.
- The continuation check is derived from the live KV cache offset on
  every restart iteration, so the tool-dispatch restart path (same
  cache, new prompt) is repaired as well.
- 8 new deterministic unit tests for repairContinuation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@fdagostino

Copy link
Copy Markdown
Contributor Author

You were right on all three counts — thanks, this was exactly the review it needed. (1) Confirmed: the sampled stop token is fed through the model before the loop recognizes it, so a completed turn is already closed in the cache and the unconditional closure duplicated the terminator. In f81ce34 the session tracks the last pass's stopReason and the closure now applies only to truncated turns (cancelled / length-capped / unreported) — which was the actual barge-in bug. The PR description's rationale was wrong on this point; I've corrected it and the doc comments accordingly. (2) Fixed: repairContinuation normalizes rank-1 token tensors and restores rank on the way out (and no longer fabricates a mask when the input had none). (3) Fixed: the continuation check is derived from the live cache offset on each restart iteration, so the tool-dispatch path is repaired too. Added 8 deterministic unit tests for the repair. Happy to flip the stripsContinuationBOS default to false if strict compatibility is preferred.

Comment thread Libraries/MLXLMCommon/ChatSession.swift Outdated
/// cached transcript stays canonical (`…repl<turn|>\n<|turn>user…`)
/// without duplicating the terminator of completed turns. Off (nil) by
/// default.
public var continuationTurnClosure: String?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think there is still an architectural issue with these additions to ChatSession.
continuationTurnClosure exposes model-specific serialization details to callers. Applications must identify the model and hard-code values such as "<turn|>\n" or "<end_of_turn>\n". This couples a generic session API to concrete chat-template protocols and requires downstream changes whenever a model or template variant uses different framing.
ChatSession should only determine that it is continuing after a truncated turn. It could pass that semantic context to UserInputProcessor, for example .continuation(previousTurn: .truncated), and let the processor/tokenizer integration handle the exact terminator tokens and BOS behavior. That layer already owns the conversion from chat messages to model-specific LMInput, including masks and multimodal alignment.
Could we replace continuationTurnClosure and stripsContinuationBOS with a continuation-aware processor API, or with a policy automatically provided by ModelContext? This would keep ChatSession model-agnostic and prevent callers from needing to understand each model’s internal chat-template syntax.

@fdagostino

Copy link
Copy Markdown
Contributor Author

You're right on all three counts — thank you, this was exactly the review it needed. Addressed in f81ce34, and the PR description is updated accordingly:

  1. Double terminator: correct — the sampled stop token is fed through the model before the loop recognizes it, so a completed turn already carries its terminator in the cache (the original description had this backwards). The closure is now gated on the previous pass's GenerateStopReason: only turns that ended cancelled, length-capped, or unreported get closed. The reason is reset pessimistically at pass start, so a generation that dies mid-stream is treated as truncated.
  2. Rank-1 no-op: fixed — repairContinuation normalizes rank-1 [N] to [1, N] and restores the rank on the way out, so default text-only sessions get the repair too. It also preserves a nil mask instead of fabricating one.
  3. toolDispatch bypass: fixed — the continuation check is derived from the live KV cache offset on every pass of the restart loop instead of a one-shot flag, so the tool-result restart is repaired as well.

Also added 8 deterministic unit tests for repairContinuation (rank-1/rank-2 shapes, BOS edge cases, closure prepending, mask handling).

…ionPolicy

Replaces the caller-facing continuationTurnClosure / stripsContinuationBOS
knobs on ChatSession with ModelConfiguration.ContinuationPolicy
(truncatedTurnClosure, stripsRepeatedBOS), declared by the Gemma 3 /
Gemma 4 registrations alongside the template knowledge that already
lives there (extraEOSTokens, toolCallFormat).

ChatSession now only determines the semantics — is this pass a
continuation (live KV-cache offset), did the previous turn complete or
truncate (tracked GenerateStopReason) — and applies the model's policy.
Callers never see or set template syntax, and models without a policy
get no repair at all, so the default is zero behavior change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@fdagostino

Copy link
Copy Markdown
Contributor Author

Agreed — the knobs were the wrong layer, thanks for pushing on this. Reworked in 281a7b6: continuationTurnClosure and stripsContinuationBOS are gone from ChatSession.

The template-specific mechanics now live on the model side as ModelConfiguration.ContinuationPolicy (truncatedTurnClosure, stripsRepeatedBOS), next to the template knowledge that already lives there (extraEOSTokens, toolCallFormat); the Gemma 3 / Gemma 4 registrations declare it. ChatSession only determines the semantics — continuation or not (live KV-cache offset), previous turn truncated or completed (tracked stop reason) — and applies whatever the model declares. Callers never see template syntax, and no policy ⇒ no repair, which also settles the earlier BOS-strip default concern: the out-of-the-box behavior is unchanged for every model that doesn't declare a policy.

On the two shapes you suggested: I went with the ModelContext/configuration-provided policy rather than a continuation-aware UserInputProcessor API because the repair is token-level and identical across models once the two template facts are known — pushing it into the processors would replicate the same logic across every implementation (or grow the protocol for all of them). Happy to move it into the processor layer instead if you think that's where it belongs long-term (it would compose well with processors owning turn serialization more broadly, per the structured tool-turns discussion).

Comment on lines 860 to +861
if case .terminated = continuation.yield(value) {
break
consumerTerminated = true

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a bit subtle. I had to read it a few times and have claude analyze it to probe it before I was fully understanding it :-)

In the case where the caller of ChatSession terminates the loop early, the yield of the token will indicate the outgoing stream is terminated. We set consumerTerminated and go to the top of the loop. Simultaneously the continuation.onTermination would fire and cancel this task.

One thing I didn't realize, and why removing the break is safe: the await item in genStream will return nil if the calling task is cancelled. The loop will either give us one more token (potentially the EOT) or it will break from the task cancel before we get it. Either way, the loop breaking will cause the token generation loop to shut down.

But, I think this logic is a bit hard to understand -- I can barely keep all the 3 tasks in my head and the iterator state after staring at this code for a bit. I also think that it may be racy: the generation task may have committed the EOT to the KVCache AND the task cancellation caused this to return nil so we missed the info.

I think.

So, what if the genTask wasn't Task<Void, Never>, but Task<Info, Never>. We are already awaiting the task completion (because we have to guarantee the borrow of the KVCache is complete). The task knows if it reached the end of turn or not and we can return it like that.

Anything dealing with the stream is racy. We could 1) yield a token/info into the Evaluate -> ChatSession stream but not consume it because of the outer task cancel or 2) break before yielding in the Evaluate loop:

            tokenLoop: while let token = iterator.next() {
                // Check for cancellation on every loop iteration.
                if Task.isCancelled {
                    stopReason = .cancelled
                    break
                }

In either case the generate loop knows the last token it committed to the KVCache, but ChatSession does not — the stream may never deliver it. When that lost token was the EOT, ChatSession wrongly concludes the turn was truncated and prepends a redundant terminator.

In all cases the generate loop does know what token got committed to the KVCache and the ChatSession does always await the generate task completion. That is a safe way to indicate to the caller what happened, even if we don't know what tokens were consumed by any of the upper layers.

The returned info could be the stopReason, but more importantly, I think it needs to indicate explicitly if the EOT was committed to the KVCache. The computation of the stop reason with regard to the EOT is a little bit complicated (handlers, includeStopToken, etc.).

That would let us go back to the more direct approach for this loop and I think resolve the race. What do you think?

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Needs merge conflicts resolved and see my comment on the loop in ChatSession. Overall looking good.

@fdagostino

Copy link
Copy Markdown
Contributor Author

Closing this: #472 solved the underlying problem, and solved it better than this PR did.

When I opened this, ChatSession appended only the newly rendered messages to a warm cache, so a continuation re-emitted <bos> and could leave the previous model turn unterminated. This PR patched that after the fact, by splicing tokens — stripping the duplicate BOS and prepending a model-specific closure.

Since then, #472 made the session render the full transcript every turn and reconcile it against a token ledger through PromptCacheReusePolicy. That makes both defects structurally impossible rather than repaired:

  • ExtendCachedPrefixRule requires promptTokens.starts(with: cachedTokens), so <bos> sits inside the common prefix and is never fed a second time.
  • A truncated turn's terminator arrives on its own inside the appended suffix, because the next full render contains it. A cancelled turn sets shouldRecord == false, invalidates the ledger, and falls through to .rebuild.

I verified this against current main by exercising the policy directly with the three scenarios this PR was built around — duplicate BOS, length-capped turn, cancelled turn. None of them reproduce.

That also settles both review points here, without the costs you each flagged:

  • @aleroot — your objection that continuationTurnClosure leaked model-specific framing ("<end_of_turn>\n") into a generic session API. The terminator now comes from the template itself, which is what you were asking for.
  • @davidkoski — your concern about inferring the outcome from a stream that may never deliver the last token. The generation task now returns the tokens actually committed to the KV cache, so the session no longer has to guess.

Thanks both for the reviews, and sorry for leaving this sitting in a conflicted state.

@fdagostino fdagostino closed this Sep 12, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…e#414)

* ci: route Swift LM main and manual test runs through Darkbloom

* ci: use the proven artifact uploader for Swift LM test products

* ci: balance Swift LM tests across four shards

Replan all 7,718 tests using the per-test maximum durations of successful runs 43408681875 and 43509674529. Keep every group, strict setting, extra pass and timeout unchanged while reducing the all-or-nothing Mac reservation from thirteen jobs to seven.

* ci: route Swift LM verification and fork diff through Darkbloom

* ci: render the Swift LM fork diff on Darkbloom before publishing

* ci: render fork diff from the selected Pages workflow commit

* ci: package the Pages artifact on the hosted publisher

* ci: keep strict audio decoder checks on a hosted runner

Keep the seven exact audio identities on xcode-27 after the unchanged base reproduced native PCM bit differences. Preserve assertions, all other test identities, three extra passes and coverage aggregation. Use the shared products only at their recorded workspace and Xcode paths, and preserve the hosted exception when replanning four native shards.

* ci: bridge the verified hosted Xcode path for audio tests

Keep the original product guard. Verify Xcode 27.2 build 27B52 and both allowed paths, create the missing canonical app alias atomically without overwrite, and use the recorded developer directory for downstream audio execution.

* ci: isolate Python startup in the hosted Xcode bridge

* ci: recognize verified preinstalled Xcode aliases without overwriting them
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ion) into the cumulative SDK

Only .github/test-shards.json conflicted. Resolution = ml-explore#414's replanned map
(4 native shards + the hosted audio shard, hosted_tests, rest run in shard
4) byte for byte, plus what this branch had added to the old map, each once:
- groups native-reasoning-budget (ml-explore#411) and gemma-quoted-number-enabled
  (ml-explore#408, extra pass with DARKBLOOM_GEMMA_SCHEMA_COERCION=1), unchanged;
- a run for each group (shards 1 and 2) and one units run in shard 3 for
  CBv2FreeSpanTests + QwenFreeSpanHistoryTests (ml-explore#413, was its own shard) and
  CBv2GrammarNonFiniteTests + CBv2GrammarQwen4Tests (ml-explore#409, was the rest run);
- estimated_seconds of those three shards raised accordingly.
Every other ml-explore#414 file is main's version; no Swift file differs from the
cumulative head eaed116. Checked: test_shards.py load_map/resolve_runs
(36 groups each used once, one rest run, no unit listed twice; each new
suite selected by exactly one main run); test_shards_test.py 27/27 OK.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…uting) into structured/glm-native-token-constraints
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…ml-explore#414) into O5

test-shards.json: ml-explore#417's map (ml-explore#414's four native shards and hosted
audio shard, with ml-explore#416's two groups) taken as is, plus ml-explore#407's
gemma-reopened-thought-enabled group and one extra run beside
gemma-quoted-number-enabled in shard 2 (+15 s estimate, as for that
run). The seven hosted audio tests are unchanged. Every other file
merges cleanly; against ml-explore#417's head this adds exactly ml-explore#407's lines,
the reviewed test case and the reference text.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants