Repository navigation
ChatSession: keep the cached transcript canonical on continuation turns - #414
fdagostino wants to merge 3 commits into
Conversation
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>
| isContinuation | ||
| ? repairContinuation( | ||
| preparedInput, tokenizer: tokenizer, | ||
| closure: continuationTurnClosure, |
There was a problem hiding this comment.
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 } |
There was a problem hiding this comment.
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.
| closure: continuationTurnClosure, | ||
| stripBOS: stripsContinuationBOS) | ||
| : preparedInput | ||
| isContinuation = false |
There was a problem hiding this comment.
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.
|
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>
|
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 |
| /// cached transcript stays canonical (`…repl<turn|>\n<|turn>user…`) | ||
| /// without duplicating the terminator of completed turns. Off (nil) by | ||
| /// default. | ||
| public var continuationTurnClosure: String? |
There was a problem hiding this comment.
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.
|
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:
Also added 8 deterministic unit tests for |
…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>
|
Agreed — the knobs were the wrong layer, thanks for pushing on this. Reworked in 281a7b6: The template-specific mechanics now live on the model side as On the two shapes you suggested: I went with the ModelContext/configuration-provided policy rather than a continuation-aware |
| if case .terminated = continuation.yield(value) { | ||
| break | ||
| consumerTerminated = true |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Needs merge conflicts resolved and see my comment on the loop in ChatSession. Overall looking good.
|
Closing this: #472 solved the underlying problem, and solved it better than this PR did. When I opened this, Since then, #472 made the session render the full transcript every turn and reconcile it against a token ledger through
I verified this against current That also settles both review points here, without the costs you each flagged:
Thanks both for the reviews, and sorry for leaving this sitting in a conflicted state. |
…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
…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.
…uting) into structured/glm-native-token-constraints
…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.
Problem
ChatSessionkeeps prior turns in the KV cache as raw tokens, and two behaviors interact so that continuation turns can append to a malformed transcript: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.){{ 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
instead of the canonical
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>thoughtchannel or degenerate output (reproduced withmlx-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.
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").ChatSessiononly 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 (trackedGenerateStopReason, 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.ContinuationPolicyget zero behavior change, which also resolves the earlier concern about the BOS-strip default.Tokenizer.bosTokenIdconvenience, mirroring the existingeosTokenId.The token-level repair itself runs in one place (
repairContinuation), afterprocessor.prepare, handling both token-tensor shapes (rank-1 text / rank-2 VLM) and preserving anilmask.Testing
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+MLXLMTestsviaxcrun xctest(same as CI) pass on this branch.<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).