Skip to content

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 #29045

Closed as not planned

Description

@juliusbangert

Name and Version

b11010 (vendored in llama.rn 0.13.0-rc.4); first seen on b10256. llama-kv-cache-iswa.cpp seq_pos_max and the derivation in llama-batch.cpp are unchanged between them.

Operating systems

Mac

Which llama.cpp modules do you know to be affected?

libllama (core library)

Command line

Problem description & steps to reproduce

This is the llama.cpp end of a problem I tracked down in a downstream wrapper (llama.rn, issue linked below). I think the wrapper is doing something llama.cpp tells it not to (llama_batch_get_one after a partial seq_rm), so I'm mainly asking whether seq_pos_max for iSWA is returning what you intend, because the consequence is a silent KV leak rather than an error.

What happens

llama-kv-cache-iswa.cpp:

llama_pos llama_kv_cache_iswa::seq_pos_min(llama_seq_id seq_id) const {
    // the base cache is a superset of the SWA cache, so we can just check the SWA cache
    return kv_swa->seq_pos_min(seq_id);
}

llama_pos llama_kv_cache_iswa::seq_pos_max(llama_seq_id seq_id) const {
    return kv_swa->seq_pos_max(seq_id);
}

The superset argument holds for seq_pos_min in the normal flow, but after seq_rm(seq, p0, -1) with p0 below the sliding window the two caches disagree: the base cache still holds positions 0…p0−1, the sliding cache holds nothing for that sequence (its cells for those positions were purged as the sequence grew), and seq_pos_max returns −1 while the base cache's answer would be p0−1.

A caller that then decodes a batch without positions gets, in llama_batch_allocr::init:

p0[s] = memory->seq_pos_max(s) + 1;   // = 0

so the new tokens are written at positions 0, 1, 2, … on top of the base cache's existing cells 0…p0−1. No error: the consecutive-positions check is skipped when seq_pos_max is −1. Each such turn adds min(n_new, p0) duplicate base cells that sit below anything a later seq_rm(seq, n_past, -1) reaches. They accumulate until find_slot fails ("failed to find a memory slot"), which then persists until a full clear. The turn is also computed at the wrong positions.

Measured on Gemma 4 E2B (12 sliding + 3 global KV layers, n_swa 512, sliding cache 1,024 cells, base 6,144): with saveSession's file size as the cell count (it writes every non-empty cell), a sequence of deep-divergence turns went +277 → +699 → +1,099 → +1,542 → +1,954 → +2,808 → +3,559 cells above the live sequence, then both caches full, then the failure.

Why I'm raising it here rather than only downstream

llama.h already says of llama_batch_get_one: "this is a helper function to facilitate transition to the new batch API — avoid using it", and llama-server never relies on derived positions (it always uses common_batch_add with explicit positions and has its own pos_min guard against reusing a prefix past the window, server-context.cpp, referencing #13194). So the wrapper is at fault for using the helper, and I've fixed it there with explicit positions plus a port of the server's guard.

But two things seem worth a look on this side:

  1. seq_pos_max for iSWA. If the base cache is the superset, kv_base->seq_pos_max(seq_id) is the true maximum of the sequence and would give the derived-positions path the right answer (p0) in this situation. Is answering from the sliding cache deliberate — e.g. so seq_pos_max agrees with seq_pos_min about what the sliding layers can actually attend to?
  2. No error on the collision. llama_batch_allocr::init validates consecutive positions only when seq_pos_max ≥ 0. When the derived start is 0 but the base cache already holds cells at those positions, a check against kv_base (or against any cache in the iSWA pair) would turn a silent leak into a decode error, which is much easier to find. The probeStateCache-style TODO in the wrapper existed for months without anyone connecting it to this.

Version

b11010 (vendored in llama.rn 0.13.0-rc.4); first seen on b10256. llama-kv-cache-iswa.cpp seq_pos_max and the derivation in llama-batch.cpp are unchanged between them.

Minimal reproduction

Any iSWA model, default swa_full = false, one sequence, plain llama_decode with llama_batch_get_one:

  1. Decode ~1,500 tokens (prompt or prompt + generation).
  2. llama_memory_seq_rm(mem, 0, 400, -1).
  3. llama_memory_seq_pos_max(mem, 0) → −1 (expected 399 from the base cache's point of view).
  4. Decode 500 more tokens with llama_batch_get_one → no error; llama_state_save_file grows by ~400 base cells more than the token count explains.
  5. Repeat 2–4 with fresh tokens until find_slot fails.

Downstream issue with the wrapper-side fix and before/after numbers: mybigday/llama.rn#396.

First Bad Commit

No response

Relevant log output

Logs
decode: failed to find a memory slot for batch of size 402
decode: failed to find a memory slot for batch of size 512

Activity

  1. mitoyosh commented on Sep 18, 2026

    @mitoyosh

    Reproduced on master 930e2fa (CPU build) with gemma-3-1b-it-Q4_K_M (n_swa=512, 5:1 sliding:global), n_ctx=4096, swa_full=false, via a small C program against libllama. A few data points that may help decide whether this is intended:

    The -1 contradicts llama.h. After decoding 1500 tokens and llama_memory_seq_rm(mem, 0, 400, -1) (which returns true):

    after seq_rm(0, 400, -1)   pos_min=-1  pos_max=-1   llama_state_seq_get_size = 1,643,328
    

    The base cache still holds 400 cells — 1,643,328 bytes is the same 400-cell block the loop below adds per round. llama.h documents llama_memory_seq_pos_max as returning -1 "if the sequence is empty", and it is not empty. llama_kv_cache_iswa::seq_pos_max() returns kv_swa->seq_pos_max() alone; the two caches agree on the max at every other moment, so this is the one state where the choice of cache matters.

    A position-less decode then writes over the base cells silently. llama_batch_get_one + llama_decode after that seq_rm: rc=0, positions assigned from 0, so the base cache now has two sets of cells at 0..399. No error because the consecutive-position check in llama-batch.cpp is skipped when seq_pos_max() is -1.

    Whether it grows without bound depends on the round size. Loop = seq_rm(0, 400, -1) then decode N tokens with pos=NULL, measuring llama_state_seq_get_size after each seq_rm:

    N per round state after each seq_rm outcome
    500 or 1000 1.64 MB → 3.83 MB, then constant bounded: a one-time 400-cell duplicate that no later seq_rm(0, 400, -1) can reach. The SWA cache (size_swa > n_swa) still holds 0..399 after the rm, so seq_pos_max is 399 from round 2 on and positions continue correctly
    1500 1.64 → 3.29 → 4.93 → 6.57 → 8.22 → 9.86 → 11.50 MB unbounded: +1,643,200 B = exactly 400 cells per round; round 7 llama_decode returns 1 (no KV slot)

    So the accumulation needs each seq_rm to empty the SWA cache (round size ≥ p0 + size_swa), which is the shape of "trim old context, then push a long chunk". Below that threshold the cost is one stranded block, not a leak.

    Controls, same 1500-token loop:

    • explicit positions continuing from 400: 1,643,328 after every seq_rm, 10 rounds, no failure.
    • swa_full=true, pos=NULL: seq_pos_max is 399 after the rm, stable, no failure.

    If the intended contract is that callers must pass explicit positions after a partial seq_rm on an iSWA cache, it would help to say so in llama.h next to seq_pos_max; if not, returning std::max(kv_base->seq_pos_max(), kv_swa->seq_pos_max()) (or the base cache's value) would make the documented "-1 means empty" true again — not tested here.

  2. juliusbangert commented on Sep 18, 2026

    @juliusbangert
    Author

    Thanks, that's a much cleaner reproduction than mine, the round-size threshold matches what we saw: our failing turns were exactly the "trim to the system prompt, then push a long reply" shape, so every round emptied the SWA cache. The max(kv_base->seq_pos_max(), kv_swa->seq_pos_max()) version would make the documented "-1 means empty" true again and fix the derived-position path without changing anything for callers that pass positions; happy to test it on iOS/Metal if someone puts it up.

  3. github-actions commented on Nov 3, 2026

    @github-actions
    Contributor

    This issue was closed because it has been inactive for 14 days since being marked as stale.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions