Skip to content

Fix TurboKV dropping compressed history from attention - #65

Merged
solderzzc merged 2 commits into
mainfrom
fix/turbokv-history-offset
Sep 25, 2026
Merged

solderzzc merged 2 commits into
mainfrom
fix/turbokv-history-offset

Conversation

@solderzzc

Copy link
Copy Markdown
Member

Proposed changes

Since #63, once a --turbo-kv prompt passes 2048 tokens, each eviction in KVCacheSimple.update sets compressedOffset to 0 and offset to the hot-window size (256). Two things break:

  • AttentionUtils only prepends the decoded polar history when compressedOffset > 0, so attention sees only the last ~256 tokens.
  • offset restarts near 256, so RoPE positions and masks are wrong.

This PR keeps offset as the logical token count and makes compressedOffset count the tokens stored in polarKeys, as its doc comment already says. Buffer indices become local (offset - compressedOffset). trim no longer cuts into compressed history, and toQuantized reads the full state.

This fixes SharpAI/SwiftLM#175. The issue reproduces on both M5 and M6, so it is not chip-specific.

Test plan

  • New test testTurboKVAttentionSeesCompressedHistory: fails without the fix (offset is 256, expected 1024), passes with it
  • KVCacheTests pass, including testTurboKVMultiRoundEvictionPreservesAllTokens
  • SwiftLM, Qwen3.8-27B-4bit --vision --turbo-kv, temperature 0, numbered-lines prompt: 315 / 500 / 600 / 700 lines now answered correctly (before: "1,000" / "14" / "1,000" / "1,000")
  • Same test on M6, no --ctx-size, 3 runs each: 315 / 500 / 700 lines go from 0/3 to 3/3. The wrong answers before the fix match the M5 exactly.

Performance note

With this fix, TurboKV is correct but slower than running without it. It now attends over the full compressed history instead of only the last 256 tokens. M6 wall time per request, TurboKV on vs off: 39 vs 26 s (315 lines), 58 vs 47 s (500), 97 vs 72 s (700), about +35% at 11.8K tokens. Speeding up the history decode is left for a follow-up.

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: Code, tests, and this description were drafted with Claude Code. I reviewed the diff.

Since #63, every TurboKV eviction in KVCacheSimple set `compressedOffset`
to 0 and `offset` to the hot-window size. Two things broke once a prompt
passed 2048 tokens:

- AttentionUtils only prepends the decoded polar history when
  `compressedOffset > 0`, so attention saw only the ~256-token hot window.
- `offset` restarted near 256, so RoPE positions and masks were wrong.

`offset` now stays the logical token count and `compressedOffset` counts
the tokens in polarKeys, as its doc comment says. Buffer indices are
local (`offset - compressedOffset`). trim no longer cuts into compressed
history, and toQuantized reads the full state.

Qwen3.8-27B-4bit --turbo-kv, numbered-lines prompt, temperature 0:
315/500/700 lines went from "1,000"/"14"/"1,000" to correct.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@solderzzc

Copy link
Copy Markdown
Member Author

Cross-review (M6 session, AI-assisted: Claude Code with the code-review skill; approved by the repo owner in conversation)

Verdict: the change is correct and fixes ml-explore#175 (SharpAI/SwiftLM). One low-severity follow-up in a caller outside the diff. Fine to merge now and handle that separately.

Checked

  • update(): previous is now the local index (offset - compressedOffset) everywhere it touches the buffer: resize check, ..<previous copy, write range previous ..< end, coldEnd = end - hot, the hot-window rebuild, and the returned ..<localCount slice. New compressed chunks still append to the existing polarKeys, so eviction after eviction preserves order.
  • offset stays the logical token count, so RoPE (ropeOffset) and masks no longer restart near 256 after an eviction. That was the "There are 14 lines" failure.
  • attentionWithCacheUpdate now prepends decoded history whenever polarKeys exists. The old compressedOffset > 0 gate was the bug.
  • state get/set, copy() (via state), trim() (limited to the fp16 tail) and toQuantized() (via state once anything is compressed) are consistent with the new meaning. Moving the TurboKV reset above the empty-state early return is right.

Low-severity follow-up, outside the diff: Libraries/MLXLLM/Models/Gemma4Text.swift:1384

Gemma4AssistantModel.callMTP bounds its sharedKV slice with min(c.offset, k.dim(2)). With this PR, after an eviction offset is the logical count (e.g. ~5,000), while keys holds only hot + one zero-filled spare step. So validLen = k.dim(2), and the assistant cross-attends to up to step all-zero K/V rows, still without the compressed history. Before this PR offset equalled the hot-window length, so the slice was exact.

  • Scope: only --mtp + --turbo-kv on Gemma 4 past 2,048 tokens.
  • Effect: worse drafts, so lower acceptance and speed. Output stays correct, because the target verifies every draft.
  • Fix: bound with the live local count, c.offset - c.compressedOffset.

Verified on a Mac mini M6 (32 GB)

SwiftLM main 804616e with this branch (a783930) vs 460ff81. Qwen3.8-27B-4bit, --turbo-kv with no --ctx-size (so KVCacheSimple), temperature 0. Numbered-lines prompt, 3 runs per cell:

lines (tokens) before after
315 (5,266) 0/3: "There are 1,314 lines." 3/3
500 (8,411) 0/3: "There are 14 lines." 3/3
700 (11,811) 0/3: "There are 1,000 lines." 3/3

Without --turbo-kv, both builds are 12/12. Cost with the fix: TurboKV requests are ~35% slower than without it at 11.8K tokens (97 s vs 72 s).

After a TurboKV eviction, `offset` counts all tokens, but the KVCacheSimple
buffer only holds `offset - compressedOffset` of them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@solderzzc

Copy link
Copy Markdown
Member Author

Thanks for the review. The Gemma4Text.swift:1384 point was introduced by this PR: offset is now logical, so min(c.offset, k.dim(2)) would include zero padding after an eviction. Fixed in 6a24b29 (c.offset - c.compressedOffset). The Gemma4 and KVCache suites pass. I'll merge once CI is green.

@solderzzc
solderzzc merged commit 7cc37a0 into main Sep 25, 2026
5 of 6 checks passed
@solderzzc
solderzzc deleted the fix/turbokv-history-offset branch November 4, 2026 05:33
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.

--turbo-kv loses context history after 2K tokens (attention sees only the last 256 tokens)

2 participants