Skip to content

kv-cache : fix iSWA seq_pos_max answering from the SWA cache only - #29480

Open
charan-rathore wants to merge 2 commits into
ggml-org:masterfrom
charan-rathore:fix/iswa-seq-pos-max
Open

charan-rathore wants to merge 2 commits into
ggml-org:masterfrom
charan-rathore:fix/iswa-seq-pos-max

Conversation

@charan-rathore

@charan-rathore charan-rathore commented Sep 26, 2026 •

Copy link
Copy Markdown

Overview

llama_kv_cache_iswa::seq_pos_max answered from the SWA cache alone. After a partial seq_rm below the sliding window (e.g. keeping only the last few tokens of a long prompt), the SWA cache becomes empty while the base cache still holds cells, so seq_pos_max returned -1 for a sequence that is not empty. Callers that derive positions from it (llama_batch_get_one via llama_batch_allocr) then restart at position 0 and silently overwrite live base-cache cells - the KV corruption reported in #29045.

The base cache is a superset of the SWA cache, so the fix reports the maximum across both caches:

return std::max(kv_base->seq_pos_max(seq_id), kv_swa->seq_pos_max(seq_id));

This restores the documented contract that -1 means "the sequence is empty". seq_pos_min already reports the minimum across both caches and is unchanged.

Additional information

Fixes #29045. The fix direction matches what @juliusbangert proposed in the issue thread; the repro was confirmed on current master by @mitoyosh.

Validation: CPU-only build (-DLLAMA_CURL=OFF); test-batch-alloc (the llama_batch_allocr consumer of seq_pos_max) passes - 50 tests, 327 assertions, 0 failures. The repo has no dedicated iSWA unit-test harness, so no new regression test is included; the issue body has the minimal runtime repro. Happy to add a targeted test if a maintainer points at the preferred harness.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES. Instinct assisted with identifying, implementing, testing, and submitting this fix, and drafted the commit message and PR description under my direction. I take responsibility for the submitted change under the project's AI usage policy.

llama_kv_cache_iswa::seq_pos_max answered from kv_swa alone. After a
partial seq_rm below the sliding window (e.g. keeping only the last few
tokens of a long prompt), the SWA cache becomes empty while the base
cache still holds cells, so seq_pos_max returned -1 for a sequence that
is not empty. Callers that derive positions from seq_pos_max
(llama_batch_get_one via llama_batch_allocr) then restarted at position
0 and silently overwrote live base-cache cells, corrupting the KV state.

Take the maximum across both caches so -1 keeps meaning "the sequence
is empty", matching the contract of llama_kv_cache::seq_pos_max.

Fixes ggml-org#29045
@ggml-gh-bot

ggml-gh-bot Bot commented Sep 26, 2026

Copy link
Copy Markdown

Hi @charan-rathore, thanks for your contribution!

Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:

  • PR Template not respected: Please respect the template when creating a new pull request. Make sure to fill out all required sections.

Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below.

@ggml-gh-bot ggml-gh-bot Bot added the draft PR will be changed to draft by github-actions bot label Sep 26, 2026
@github-actions
github-actions Bot marked this pull request as draft September 26, 2026 13:10
@github-actions github-actions Bot removed the draft PR will be changed to draft by github-actions bot label Sep 26, 2026
@charan-rathore
charan-rathore marked this pull request as ready for review September 26, 2026 13:42
@juliusbangert

juliusbangert commented Sep 28, 2026 •

Copy link
Copy Markdown

Thanks for looking into this @charan-rathore, and thanks @mitoyosh for confirming it.
Just a bit of background from our end... we found this issue on iOS with Gemma 4 E2B using llama.rn, where nextToken() decodes with llama_batch_get_one and gets positions from seq_pos_max. We are currently using a patch package that builds the batch with explicit positions. Once this gets synced I can run our KV-reuse test on device, and let you know..

@charan-rathore

Copy link
Copy Markdown
Author

Thanks, Julius. That iOS path is helpful context, especially the nextToken() use of llama_batch_get_one. The PR is still under review, so I can't promise when it will be synced, but an on-device KV-reuse result when it is available would be useful.

@jhen0409

jhen0409 commented Oct 5, 2026

Copy link
Copy Markdown
Member

I haven't studied this in detail yet, but this PR and #19225 seem to be in a similar direction.

For #29045 (with llama.rn), it doesn't seem to have completely solved the problem. Cache reuse can be handled externally, like in tools/server/server-context.cpp.

@charan-rathore

Copy link
Copy Markdown
Author

Thanks for looking. I read #19225 and the discussion there. It switched seq_pos_min and seq_pos_max to the base cache, and ggerganov closed it because these functions intentionally work with the SWA cache. This PR is narrower: seq_pos_min is untouched, and seq_pos_max still reads the SWA cache but takes the max with the base cache, so it only changes the case where the SWA cache is empty and the base cache is not (it returned -1 for a non-empty sequence). I have not tested whether that still conflicts with the intended behavior.

You are right that it does not solve the whole llama.rn problem. It only restores that -1 means an empty sequence for batches without positions, and I have only run test-batch-alloc, no iSWA-specific test. If the maintainers consider this by design and prefer callers to pass explicit positions or handle reuse in server-context.cpp, I am fine with closing it.

@ggerganov ggerganov self-assigned this Oct 5, 2026
@ggerganov

Copy link
Copy Markdown
Member

The problem with this change is that if a SWA checkpoint is not restored and the inference continues from the new max pos, it will be subtly incorrect (because of the missing SWA data). I think we have to add some assertion in addition to the proposed change in order to prevent that from silently happening.

@charan-rathore

Copy link
Copy Markdown
Author

Thanks, that makes sense. If the SWA cache is empty and the base cache is not, continuing from the base max position would leave the SWA layers attending to missing data without any signal.

I can see two places for a check, and I would like to pick the one you prefer before I push anything:

  1. In llama_kv_cache_iswa::seq_pos_max, when the SWA cache is empty and the base cache is not, abort with a message that the SWA state was not restored, instead of returning the base max. That makes the PR a pure diagnostic, and callers must restore a checkpoint or pass explicit positions.
  2. In llama_batch_allocr::init, where the auto-derived start position is compared with mem->seq_pos_max, assert that the SWA and base positions agree.

I have not built or run either variant yet, and I have only run test-batch-alloc so far. If you think this is better handled in the caller (server-context) instead, I am fine with closing the PR. Prepared with AI assistance; I am responsible for the change.

@ggerganov

Copy link
Copy Markdown
Member

In llama_kv_cache_iswa::seq_pos_max, when the SWA cache is empty and the base cache is not, abort with a message that the SWA state was not restored, instead of returning the base max. That makes the PR a pure diagnostic, and callers must restore a checkpoint or pass explicit positions.

Try this first. But I am not sure it is going to work. It depends if we call seq_pos_max anywhere before restoring the checkpoint - I am not sure.

@charan-rathore

Copy link
Copy Markdown
Author

Pushed d0158f4: llama_kv_cache_iswa::seq_pos_max now answers from the SWA cache as before, and asserts (GGML_ASSERT with an "SWA state was not restored" message) when the SWA cache is empty but the base cache is not. I dropped the max() change, so the PR is now only the assertion.

On your question about call order: I only read the code, I did not run a model. tools/server/server-context.cpp calls llama_memory_seq_pos_min and then llama_memory_seq_pos_max for every slot when deciding on a checkpoint (around line 3613), before it checks pos_min < 0. So in the state this PR is about (SWA empty after a partial seq_rm, base not), the server would hit this assertion there instead of getting -1, unless the checkpoint was restored first. The same calls exist in common/speculative.cpp and llama_batch_allocr. So I think the assertion is likely to abort the server in that state, which may be what you want, but it also may be too strict for those query-only callers.

What I ran: build of libllama and test-batch-alloc, which passes (0 failures). I have not run any iSWA model or the server, so the assertion itself is untested at runtime. Prepared with AI assistance; I am responsible for the change. Happy to close or change it if you would rather keep the query side-effect free.

@ggerganov ggerganov removed their assignment Oct 5, 2026
@ggerganov

Copy link
Copy Markdown
Member

Yes, the assertion has to be in a different place. But it would be easier if I take a look at this myself instead of navigating you, or if someone else takes over. The idea is now clear.

@charan-rathore

Copy link
Copy Markdown
Author

Thanks for the guidance and for taking the time on this. Happy for you or anyone else to take it over from here, and fine to close this PR if you prefer. I will not push anything more to it.

This branch has not been deployed

No deployments
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.

iSWA: seq_pos_max answers from the sliding cache, so a batch without positions lands at 0 after a partial seq_rm and leaks base-cache cells

5 participants