Decode with a sliding-window KV cache stored as a ring buffer
With sliding-window attention a token only looks at the last W positions, so the KV cache never needs more than W slots. Real implementations keep a fixed buffer and overwrite the oldest slot, a ring buffer, instead of shifting memory every step.
Write ring_cache_decode(q, k, v, window). q, k, v have shape (T, d). Process tokens one at a time, t = 0..T-1:
1. slot = t % window. Write k[t] and v[t] into that slot of key/value buffers of shape (window, d), initialised to zeros. Record pos[slot] = t (pos starts as all -1).
2. Attend q[t] over the filled slots only (slots with pos >= 0): scores = K_slot @ q[t] / sqrt(d), softmax, weighted sum of the V slots.
Return (out, kbuf, pos): out has shape (T, d), kbuf is the final key buffer, pos is the final list of absolute positions per slot (-1 for never-used slots).
Token t must see exactly positions max(0, t - window + 1) .. t.
def ring_cache_decode(q, k, v, window)Understand the idea
With sliding-window attention a token only looks at the last W positions, so the KV cache never needs more than W slots. Rather than shifting the whole buffer every step, a ring buffer writes each new token into slot t % W, overwriting exactly the token that just fell out of the window. Worked example: W = 3. Tokens 0, 1, 2 fill slots 0, 1, 2, so pos = [0, 1, 2]. Token 3 goes to slot 0, pos = [3, 1, 2]. Token 4 goes to slot 1, pos = [3, 4, 2], and token 4 attends to positions 2, 3, 4, which is max(0, 4 - 3 + 1) to 4. At t = 1, only slots 0 and 1 are filled; slot 2 still has pos -1 and must be skipped. Rule: write k[t], v[t] at slot t % W and set pos[slot] = t; then score q[t] against every slot with pos >= 0, divide by sqrt(d), softmax and take the weighted sum of the matching values. Attending to empty zero slots during the first window is the common bug. Used by sliding-window models such as Mistral 7B.