Sliding-Window Attention
A window bounds what attention reads, but not what a model needs: a rolling cache measured on Gemma-2, how far influence travels through stacked windows, what a plain window does to a model not trained for one, and why a masked window is not yet a speed-up.
A single-token change to the attention mask can make an apparently minor memory optimisation a large model change. In this chapter’s controlled experiment, Llama-3.2-1B scored 2.998 bits per token with its original full attention on the second half of 4,096-token passages. Restrict every layer to the most recent 2,048 tokens and the score rises to 7.072. Keep the passage’s first token visible as well and it falls to 3.354. That one pinned token recovers about 91% of the measured increase in loss caused by the plain window. The experiment measures teacher-forced language-modelling loss under an imposed mask, not long-running streaming generation or retrieval quality.
A sliding window is the most direct way to bound one layer’s KV-cache growth: keep the most recent \(W\) positions, plus any separately retained tokens, and discard older keys and values. But this only bounds the full model’s cache if every relevant layer uses a bounded policy. Gemma-2 alternates local and global layers; in the measured Hugging Face implementation its local-layer cache stopped at 4,095 tokens, while the global layers continued growing. Nor can a runtime generally impose a new window on a full-attention checkpoint without changing what the model computes. The opening experiment shows why, and why attention sinks are an important—but not universal—part of the answer.
We will work from the causal attention mask to the exact pair-count arithmetic, then test how far a change can propagate through stacked local layers. From there we build a fixed-size ring, inspect the hybrid cache of a model designed for local attention, and impose windows on two models that were not. Finally we separate decode cache-read savings from prefill kernel savings. One correction to the starter material is particularly instructive: it compared a causal window against the full attention square instead of against the causal triangle, exaggerating the work saved.
Where this sits
Multi-Head and Multi-Latent Attention reduced the cache by keeping fewer key/value heads. A window reduces it by keeping fewer positions; in a local-attention layer, the two savings multiply. Key-Value Caching, PagedAttention and Prefix Caching studied cache allocation, paging and reuse. Here we ask when a live sequence can discard old KV entries without changing the intended attention function. Attention and Its Computational Cost measured attention as sequence length grows, and FlashAttention and Optimized Kernels examined tiled kernels: together they explain why a sparse mask only speeds up prefill when the implementation avoids work on masked tiles. The results below come from single-layer attention timings and from separate full-model quality experiments, not from one integrated serving run.
The Inference Lab increment is a windowed-attention toolkit: causal and sink-aware masks, pair and memory arithmetic, a fixed-storage RingKV layer, a banded \(O(TW)\) attention reference, a GPT-2 forward path with an imposed mask, and four evidence-producing commands. The ring’s numerical checks compare it with the same masked attention on supplied query/key/value tensors; they do not implement or validate a complete position-encoding and KV-cache pipeline. Long-Context Inference builds on these mechanisms for long contexts.
For the Pi series, carry forward a stricter artefact-identity rule. A model’s attention pattern, local/global layer schedule, sink policy and positional encoding belong to its execution specification alongside the head counts from Multi-Head and Multi-Latent Attention. A manifest should record the configuration actually used, not assume that changing a sliding_window field at runtime preserves checkpoint behaviour. A deployment also needs to record the cache implementation and attention backend if its memory and speed claims are to be reproducible.
What a window computes
For the local causal rule used here, query \(i\) may attend to key \(j\) if \(j \leq i\) and \(i-j < W\). Across \(T\) positions, full causal attention has
At \(T=32{,}768\) and \(W=1{,}024\), full causal attention has 536,887,296 valid pairs and the window has 33,030,656, a ratio of about 16.3×. That is a substantial opportunity for a kernel that avoids irrelevant tiles—not a prediction that elapsed time will improve by 16.3×.
How far information travels
Direct visibility and influence through layers are different. In a stack of \(L\) strictly local, causal attention layers with the same width \(W\), a change at position \(p\) can reach at most \(p+L(W-1)\) through successive attention paths; residual connections do not enlarge this bound. For 32 layers and \(W=4{,}096\), it is \(32\times4{,}095=131{,}040\) positions, consistent with the theoretical long-range path discussed in the Mistral 7B paper. This bound does not apply unchanged to architectures with global layers, explicit global tokens or other cross-position mechanisms, and it is not proof that information remains useful at the farthest reachable position.
The experiment imposes the same local mask in all 12 layers of GPT-2, changes the token at position 100 and measures the maximum absolute logit difference at later positions (CPU, float32). Each table cell is the maximum over its stated distance interval, not an average influence or a measure of retrieval accuracy:
| Distance from changed token | Window 32 (reach 372) | Window 64 (reach 756) | Window 128 (reach 1,524) | Full attention |
|---|---|---|---|---|
| 1 to 31 | 99 | 18 | 34 | 34 |
| 32 to 63 | 6.1 | 48 | 178 | 19 |
| 64 to 128 | 3.17 | 19.76 | 51.75 | 14.34 |
| 129 to 256 | 0.069 | 2.3 | 21 | 7.3 |
| 257 to 371 | 0.00011 | 0.16 | 2.8 | 7.3 |
| Exactly 372 | 0.000046 | 0.00069 | 0.63 | 1.4 |
| 373 to 400 | 0 | 0.0011 | 0.56 | 2.8 |
| 401 to 755 | 0 | 0.0003 | 0.12 | 21 |
| Exactly 756 | 0 | 0 | 0.000031 | 1.38 |
| 757 to 900 | 0 | 0 | 0.00017 | 2.1 |
For a 32-token window, the last measured nonzero change is at distance 372, exactly the theoretical reach. Beyond it, the computation has no path from the changed token to that position, so a change cannot propagate under this mask. Within the reach, the effect becomes very small; the table is not a smooth monotonic decay curve, because each cell reports a maximum over different positions. At \(W=64\), the last nonzero float32 difference was at 754, although 756 is structurally reachable. Numerical zero inside the reach must not be interpreted as proof of no dependence: the contribution can fall beneath floating-point resolution. The small three-layer unit test checks nonzero differences through the reachable positions in one seeded example and zero differences beyond; it does not establish a universal nonzero lower bound for every model and input.
A fixed-size cache
For an attention layer that reads only the latest \(W\) positions, a circular KV buffer can retain exactly that active suffix. A position \(p\) maps to \(p\bmod W\); after its key/value entry leaves the window, the slot can be reused. This is the rolling-buffer idea described by Mistral 7B. Our RingKV variant optionally pins \(S\) initial sink entries in separate slots and rotates the remaining positions through \(W\) slots, allocating \(S+W\) entries in total. The following excerpt is illustrative, not a complete runnable class; the actual module supplies the constructor, grouped-query handling and tensor operations. An engine must also enforce append-before-attend ordering, live-position validity and whatever positional encoding the checkpoint requires:
class RingKV:
def slot(self, position): # sinks (if any) are pinned; the rest rotate
return position if position < self.sinks else self.sinks + (position - self.sinks) % self.window
def append(self, k_new, v_new, position):
s = self.slot(position)
self.k[:, :, s], self.v[:, :, s] = k_new, v_new
self.filled[s] = True
def attend(self, q): # attention over whatever is in the buffer
scores = (q_grouped @ self.k.transpose(-1, -2)) / sqrt(d)
scores = scores.masked_fill(~self.filled, -inf)
return softmax(scores) @ self.v
Cache slots need not be stored chronologically for ordinary content attention: permuting key/value pairs together leaves the softmax-weighted sum unchanged, apart from possible finite-precision reordering. But this statement requires the position-dependent information to be handled correctly. For RoPE, for example, keys may carry rotations computed from their original positions; other schemes may require position-aware biases or re-indexing. The RingKV tests feed precomputed random Q/K/V tensors with no positional transformation, and compare each append-and-attend result with dense window-masked attention for windows of 1, 3, 5 and 30, with and without sinks. Those float64 results agree to \(10^{-10}\) across wraps, and allocated KV payload bytes remain unchanged between short and long streams. They verify slot reuse and masked attention, not the correctness of a whole rotary or ALiBi decoder.
What the library does for a model built this way
Gemma-2-2B provides a model-native counterexample to the idea that every layer must keep the entire prefix. The measured checkpoint has 26 layers: 13 use local attention with a configured 4,096-token window and 13 use global attention; it has four KV heads of width 256. Running full prefills through the locally installed Transformers build and summing the logical K/V tensor payload showed local caches capped at 4,095 positions, while the global caches grew with the supplied prompt. This is an observation of this implementation and version, not a rule that a 4,096-token architectural window universally occupies 4,095 cache slots:
| Prompt tokens | Local layers hold | Global layers hold | Cache bytes | If every layer were global |
|---|---|---|---|---|
| 1,024 | 1,024 | 1,024 | 109,051,904 | 109,051,904 |
| 4,096 | 4,095 | 4,096 | 436,154,368 | 436,207,616 |
| 6,144 | 4,095 | 6,144 | 545,206,272 | 654,311,424 |
| 8,192 | 4,095 | 8,192 | 654,258,176 | 872,415,232 |
The byte formula is \(2h_{kv}d\,b\) per cached token per layer, with \(b=2\) bytes for these fp16 tensors. Counting the local layers at \(\min(T,4095)\) and the global layers at \(T\) reproduces all measured logical KV-tensor payload sizes; it does not include allocator reservation, metadata, temporary activations or fragmentation. At 8,192 tokens—the model’s configured context limit—the hybrid payload is about 654 MB rather than 872 MB if every layer retained all positions, a 25% saving. If the same cache arithmetic were extended to 32,768 and 131,072 positions, it would give about 1.96 versus 3.49 GB and 7.20 versus 13.96 GB. Those latter figures are extrapolations, not evidence that this checkpoint can successfully attend or generate at those lengths. The observed 4,095-slot cap should also not be silently substituted for the architecture’s 4,096-token attention rule.
The other inspected local configurations are not interchangeable with Gemma-2’s measured execution. Mistral-7B-Instruct-v0.3 reports sliding_window: null in the cached config, despite the original Mistral 7B paper describing sliding windows for an earlier model. Qwen3-1.7B has use_sliding_window: false; Phi-3-mini-4k lists sliding_window: 2047, but this experiment did not verify whether that setting was applied during inference. Thus Gemma-2 is the only model for which this chapter measured windowed KV residency, not necessarily the only local model with a window-related configuration.
What a window does to a model not built for one
A serving engine generally cannot change a full-attention checkpoint to a strict window and still claim it is executing the same model. To demonstrate the consequences, I inserted an additional causal window mask into GPT-2 and Llama-3.2-1B, both used here as full-attention models. In some conditions the mask also preserves the first one or four key positions. The reported result is teacher-forced next-token cross-entropy on passages drawn from the book’s test chapters, evaluated only at later positions. It is not generated-text quality, a streaming cache benchmark or a direct measurement of attention weights.
GPT-2: 40 passages of 1,024 tokens, scoring next-token predictions at positions 512–1,023. Bits per token; its full-attention baseline is 4.087:
| Window | No sinks | 1 sink | 4 sinks |
|---|---|---|---|
| 512 | 6.192 | 4.193 | 4.187 |
| 256 | 10.516 | 4.774 | 4.695 |
| 128 | 11.447 | 5.162 | 5.049 |
| 64 | 12.093 | 5.572 | 5.433 |
| 32 | 13.237 | 6.322 | 6.139 |
| 16 | 14.593 | 7.456 | 7.178 |
Llama-3.2-1B-Instruct: eight passages of 4,096 tokens, scoring next-token predictions at positions 2,048–4,095, using fp16 model weights. Bits per token; its full-attention baseline is 2.998:
| Window | No sinks | 1 sink | 4 sinks |
|---|---|---|---|
| 2,048 | 7.072 | 3.354 | 3.213 |
| 1,024 | 7.301 | 3.617 | 3.411 |
| 512 | 7.836 | 3.772 | 3.549 |
| 256 | 8.565 | 3.970 | 3.748 |
| 128 | 9.501 | 4.285 | 4.080 |
The columns distinguish a plain local mask from masks that additionally retain initial keys, but they do not isolate two independent mechanisms. Adding a sink changes the model’s whole attention distribution; any remaining loss under the sink-aware mask cannot be assigned solely to missing semantic information without further interventions.
The observed cliff. For Llama-3.2-1B with a 2,048-token window, loss rises from 2.998 to 7.072 bits per token; retaining only the first key reduces it to 3.354. GPT-2 shows a similar, though differently sized, improvement when initial tokens remain visible. The established attention-sink explanation, investigated by StreamingLLM’s authors, is that certain attention heads give disproportionate mass to early positions even when their contents are not semantically special; deleting those positions alters normalisation and redirects attention. Our loss experiment is consistent with that mechanism, but we did not inspect the attention maps, vary the identity of the preserved token or establish a causal explanation for the cliff. It should not be read as proving that the first token alone carries the passage’s long-range information.
What remains when early tokens are retained. With four sinks and a 2,048-token window, the Llama score is 3.213 versus 2.998 for full attention, an increase of about 0.215 bits per token; at a 128-token window, the increase is about 1.081. For GPT-2, the corresponding increases with four sinks are about 0.100 bits at \(W=512\) and 1.346 bits at \(W=64\). At \(W=2048\), one sink recovers approximately 91% and four recover 95% of the plain-window excess loss for Llama. These percentages describe the tested masks and passages. The residual excess loss is not a pure measurement of forgetting: changes in attention weights and position handling can contribute as well. A retrieval task with the answer deliberately outside the window would test a different question.
There are several limits. Both checkpoints were trained to use full attention; the results should not be carried over to Gemma-2 or a Mistral checkpoint trained with local attention. They were scored within their configured contexts, using a static mask on whole input passages; no long-running decode stream or rolling-cache quality evaluation was performed. The experiment retains the original positions of sink and recent tokens. StreamingLLM instead describes assigning positions within the retained cache and, for RoPE, applying positional rotation appropriately when reusing keys; that machinery is not present in the chapter’s RingKV implementation. Finally, average language-modelling loss cannot establish success on distant-needle retrieval, document understanding or reasoning tasks.
The practical implication is conditional. A pure \(W\)-slot ring is an exact cache design for the strict local-attention rule it implements; it is not automatically a faithful replacement for a full-attention model. Preserving initial sink slots can substantially reduce the loss observed after imposing a new window, but that is an empirical workaround, not permission to change an arbitrary checkpoint’s attention specification. The RingKV class demonstrates the storage mechanics; integrating it with a real checkpoint also requires correct positional transformations, attention masks, cache updates and stop/boundary handling.
Where the time goes
An attention window limits which KV entries may contribute to a result. Whether that reduces elapsed time depends on the cache representation, memory access pattern and kernel backend. The following measurements isolate attention operations; they do not include a transformer’s weight projections, scheduler or network service.
Decode: bounded cache-read length. The harness generates random query/key/value tensors for a single attention call: batch 16, 32 query heads, eight KV heads, head width 128, fp16. It compares full-length cached K/V tensors with freshly generated tensors whose sequence axis is capped at 4,096. Timings are the best of three synchronized runs of the grouped-SDPA attention formulation from Multi-Head and Multi-Latent Attention. The benchmark does not append new tokens into RingKV during timing or demonstrate a complete rolling decode loop:
| Context | Full cache | Cache bounded at 4,096 |
|---|---|---|
| 1,024 | 0.34 ms, 67 MB | 0.34 ms, 67 MB |
| 4,096 | 0.97 ms, 268 MB | 1.00 ms, 268 MB |
| 8,192 | 2.07 ms, 537 MB | 0.96 ms, 268 MB |
| 16,384 | 3.79 ms, 1,074 MB | 0.99 ms, 268 MB |
| 32,768 | 12.5 ms, 2,147 MB | 0.98 ms, 268 MB |
After the retained length reaches 4,096, the isolated attention call stays close to 1 ms while the full-cache call grows: at a 32,768-token context the bounded call is 12.8× faster (12.53 versus 0.98 ms) and its supplied K/V tensors contain 8× fewer bytes. This is direct evidence that reading fewer cached positions helps this implementation at long context. It is not an end-to-end inference speed-up, an assessment of generation quality, or a test that all ring-buffer bookkeeping is free. The 8× payload ratio also agrees with the basic rolling-cache arithmetic discussed by the Mistral authors; it is not a reproduced production-server result.
Prefill: avoiding masked work. The harness times one attention layer on random fp16 tensors with eight heads of width 128 and a window of 1,024. It compares (1) PyTorch scaled_dot_product_attention with is_causal=True, (2) the same API with a dense Boolean window mask, and (3) the unfused banded_window_attention implementation, which forms local blocks of \(W\) queries and up to \(2W\) keys. The harness does not pin or log the SDPA backend, so the term fused in the original draft was not verified for every call. The table preserves the recorded best-of-three timings:
| Tokens | Valid pairs: full causal / window | SDPA causal | SDPA with window mask | Banded (unfused) |
|---|---|---|---|---|
| 2,048 | 2.1 M / 1.6 M | 0.65 ms | 1.49 ms | 5.81 ms |
| 4,096 | 8.4 M / 3.7 M | 2.17 ms | 5.70 ms | 15.6 ms |
| 8,192 | 33.6 M / 7.9 M | 13.1 ms | 34.0 ms | 27.2 ms |
| 16,384 | 134 M / 16.3 M | 50.7 ms | 133.8 ms | 53.5 ms |
| 32,768 | 537 M / 33.0 M | 182.5 ms | Not run | 104.4 ms |
On this installation, the masked SDPA call is slower than causal SDPA: about 2.3× at 2,048 tokens and 2.6× at 16,384. A plausible explanation is a different or less efficient backend selected for an explicit Boolean mask, but the harness did not identify the backend or profile its executed operations. We therefore cannot assert that a particular fused kernel computes and discards every masked pair. The banded implementation is also slower than causal SDPA through 16,384 tokens, then faster at 32,768 (104.4 versus 182.5 ms, a 1.75× measured ratio). Its valid-pair count is roughly 16× smaller at that point, but it materialises intermediate scores and processes padded tile regions, so theoretical sparsity does not translate directly into time. Numerical agreement against a float32 dense reference was checked only at 2,048 and 4,096 tokens (maximum absolute differences about 0.0019 and 0.0015 for the fp16 implementation); the longer timing cases were not similarly checked. The Mistral 7B authors report their own FlashAttention/xFormers modifications yielding about 2× speed-up at 16K tokens with \(W=4096\), which we have not reproduced. The lesson is to benchmark the actual kernel: local attention offers \(O(TW)\) useful-pair work, but a window mask alone is not a speed guarantee.
DeepInfer’s bounded replay
The pinned DeepInfer README mentions “SWA bounded replay”: its authors describe limiting decoder-prefill recomputation to a retained suffix that covers the sliding window plus the maximum backtracking length. This is a statement about how much work must be replayed after a backtrack, not documentation of a rolling KV-cache implementation. The pinned release explicitly does not include a KV-cache system; it does not specify a window size or prove how a particular model’s outputs behave under this feature. We did not execute or benchmark DeepInfer here. It belongs in the chapter as a carefully scoped serving-design connection, not as supporting evidence for the ring or GPU speed results.
What the numbers do not show
- Two full-attention checkpoints with imposed masks. The loss cliff and sink recovery are findings about GPT-2 and Llama-3.2-1B, not about models trained with windows.
- Teacher-forced next-token loss, not task quality. No distant-answer retrieval, reasoning evaluation or open-ended generation was run.
- Position handling is not integrated. The
RingKVtests use prepared Q/K/V tensors, not real RoPE key rotation, position re-indexing or ALiBi biases. - A small, mutable corpus. The quality tests use 40 GPT-2 passages and eight Llama passages extracted from the manuscript and source code in the book’s test chapters. Editing those files changes the experiment’s input unless a snapshot is retained.
- Attention-only GPU timing. The decode benchmark does not time ring updates, projections, sampling or scheduling. The prefill benchmark does not log which SDPA backend executes.
- Limited numeric parity coverage for long prefill. The CPU tests establish correctness for small float64 cases; GPU-vs-dense checks were recorded for the 2,048- and 4,096-token prefill cases, not the full 32,768-token case.
- Unoptimised banded attention. The measured crossover is for this Python/PyTorch implementation. A specialised window-aware fused kernel may behave differently; no such kernel was qualified here.
- No integrated paged, prefix or hybrid serving cache. The ring is not integrated with PagedAttention–Continuous Batching–Prefix Caching, and the interaction of sliding windows with prefix caching or global layers remains untested.
- Gemma-2 outside its context limit. Values beyond 8,192 tokens are calculations from the cache formula, not model-execution results.
Inference Lab increment
The Lab now has:
window_mask,attention_pairsandreach: causal-local rules, exact pair counts and structural influence bounds.bounded_cache_tokensandhybrid_cache_bytes: payload accounting, with a library-specificwindow-1option used to match the measured Gemma-2 cache.RingKV: a storage-and-attention reference with optional pinned sinks, compared against dense masked attention using prepared Q/K/V tensors across wraparound.banded_window_attention: an unfused \(O(TW)\) reference, tested against masked dense attention on small inputs and timed separately on the GPU.gpt2_logits: the The Transformer as a Computation GPT-2 computation under full, local and sink-aware attention masks.cache,quality,receptiveandscaling: the commands that produce the cache, loss, influence and timing evidence. Run inputs and library versions must be preserved to reproduce their output.
The principle is a window bounds which positions a local layer may read, but it does not tell us which information the checkpoint needs. The architecture determines where a bounded cache is legal; initial sink tokens may be important for some models that were not trained with a window, and global layers still require their own cache policy. Reading fewer positions can accelerate decode, but the experiment has demonstrated that only for an isolated attention call. Prefill benefits require an implementation that avoids enough masked work to offset its own overhead. Correctness, memory capacity, latency and downstream task quality must therefore be checked separately.
What you should now be able to do
- Derive full-causal and sliding-window pair counts, then distinguish valid pairs from kernels’ actual computation.
- Compute the maximum influence distance \(L(W-1)\) for strictly local causal layers and explain why finite-precision zero inside the reach is not proof of disconnection.
- Implement a ring with optional pinned sink slots and compare its output with the same window-masked reference across wraparound; state what additional tests real positional encodings require.
- Account separately for global-layer and local-layer KV bytes in a hybrid model, including any implementation-specific off-by-one storage behaviour.
- Explain what the loss experiment says about adding a new window to a full-attention checkpoint, and why the attention-sink mechanism itself requires further evidence.
- Interpret the decode and prefill timing tables without treating single-layer speed-ups as serving throughput or assuming that an untracked SDPA backend is fused.
Key terms
- Sliding-window attention: a causal rule restricting each query to at most \(W\) recent key positions, subject to any separately specified global or sink positions.
- Valid attention pairs: the query–key combinations allowed by a mask, distinct from the work a kernel actually executes.
- Structural reach: the maximum influence distance through \(L\) strictly local causal layers, \(L(W-1)\); a bound, not a quality guarantee.
- Rolling KV buffer: fixed storage that reuses slots after their keys and values leave the active window.
- Attention sink: an early position receiving disproportionate attention in some language models; retaining its KV state may improve streaming loss.
- Hybrid attention: a model combining local and global attention layers, which need not have the same cache growth.
- Banded attention: computing near-diagonal query/key blocks to avoid most distant pairs.
- SDPA backend: the implementation selected by PyTorch’s scaled-dot-product-attention dispatch; selection may affect both timing and supported masks.
- Bounded replay: recomputing a limited suffix of work, distinct from maintaining a bounded resident KV cache.
Reader exercises
- Implement a sink-aware rolling cache on top of PagedAttention’s page tables. Specify when pages become reclaimable and test that the sink slots are never evicted by the ring.
- Extend
RingKVto handle RoPE position transforms as StreamingLLM describes. Compare it with a full masked reference before and after multiple wraps. - Replace the teacher-forced loss metric with a controlled distant-answer retrieval task. How does answer accuracy differ between a plain window, a sink-aware window and full attention?
- Inspect Llama-3.2-1B’s attention maps after the mask intervention. Are the early keys given high attention mass, and does the pattern survive if the first token is replaced?
- Pin or profile the actual SDPA backend for causal and explicit-window-mask prefills. Which kernel runs, and how much memory or compute traffic does it perform?
- Build or qualify a fused local-attention prefill kernel; repeat the table including numeric parity at 8K, 16K and 32K.
- Run a model-native hybrid-cache experiment for Gemma-2 using its global/local layer schedule, including decode beyond the initial prefill where supported.
- Integrate sliding-window cache policy with Prefix Caching’s prefix reuse. Which cached states remain valid, and which cannot be reused after local eviction or changes to global-layer context?
References
- Longformer: The Long-Document Transformer — Beltagy, Peters and Cohan, 2020; local windows plus selected global positions, an architectural comparison rather than a model tested here.
- Mistral 7B — Jiang et al., 2023; model-native local attention, theoretical cross-layer reach, rotating KV buffers and the authors’ reported optimised-kernel results.
- Efficient Streaming Language Models with Attention Sinks — Xiao et al., ICLR 2024; explains the sink phenomenon, pinning initial KV entries and cache-position handling. The paper’s streaming experiments are not replicated here.
- Gemma 2: Improving Open Language Models at a Practical Size — Gemma Team, 2024; alternating local/global attention and a 4,096-token local window.
- PyTorch:
scaled_dot_product_attention— API and backend-selection constraints. Documentation may change; the actual backend in this chapter’s runs was not recorded. - DeepInfer, pinned at
774ce244— first-party note on SWA bounded replay; not evidence of a KV-cache implementation or an independently reproduced performance result.
Evidence in this chapter
| Claim | Evidence category and boundary |
|---|---|
| Full causal attention has \(T(T+1)/2\) valid pairs; a \(W\)-window has \(\sum_i\min(W,i+1)\) | Exact arithmetic; unit-tested. Valid pairs are not elapsed kernel work. |
| Influence through \(L\) strictly local layers cannot travel beyond \(L(W-1)\) positions | Structural bound; tested on a small model and illustrated by GPT-2 output differences. |
| GPT-2 at \(W=32\) shows no nonzero logit changes beyond distance 372 | Recorded float32 experiment; zero inside the bound can be numerical, while exclusion beyond it is structural. |
RingKV matches the same dense local/sink mask across wraparound |
Book test on prepared float64 Q/K/V; no integrated RoPE/ALiBi correctness evidence. |
| Gemma-2’s local-layer K/V tensors cap at 4,095 positions in the tested implementation | Measured logical tensor bytes, not total allocator memory or a universal cache-size convention. |
| Llama with an imposed 2,048-token window rises from 2.998 to 7.072 bits/token; one sink reduces it to 3.354 | Book result, teacher-forced evaluation of one full-attention checkpoint. |
| Early-token attention-sink behaviour explains the loss cliff | A mechanism supported by StreamingLLM’s authors; this lab measured loss, not attention weights or token-identity interventions. |
| The bounded-KV attention call at 32,768 tokens is 12.8× faster and supplies eight times fewer K/V bytes | Book result for random tensors and an isolated attention call; no ring-update or end-to-end timing. |
| SDPA with an explicit window mask was 2.3–2.6× slower; unfused banding beat causal SDPA at 32K | Book timing results; exact backend unknown. Longest banded run lacks a GPU-vs-dense parity check. |
| Mistral reports optimised window kernels and 8× cache reduction at 32K/4K | Authors’ reported results, not independently reproduced. |
| DeepInfer describes SWA bounded replay | Pinned first-party README; no windowed cache or execution benchmark reproduced. |
| Quality of a model trained with windows, position-reindexed streaming, retrieval quality and serving throughput | Not measured. |