Long-Context Inference
A context length is five claims, not one: that the model accepts the tokens, behaves at those positions, fits in memory, answers in time, and uses what it is given. Each measured on a model that advertises 128K, on a card that can hold a quarter of it.
Llama-3.2-1B advertises a context of 131,072 tokens. On the book’s 12 GiB RTX 2060, the recorded PyTorch build allocated an additional 4.89 GiB at peak when prefilling only 4,096 tokens with its default attention path—up from 1.31 GiB at 2,048. A separate, deliberately excluded 8,192-token probe reported 18.91 GiB of peak extra allocation and lasted 145.9 seconds in an oversubscribed Windows environment. A model configured to accept 128K tokens is not thereby a model that can serve 128K tokens on this machine. These are allocation and timing observations, not a direct trace of operating-system page transfers.
“Supports a context of 128K” hides at least five separate questions. Acceptance: will the tokenizer, configuration and API allow the input? Positional correctness: does the checkpoint, with its intended positional scheme, behave usefully there? Memory: can the weights, KV cache, prefill intermediates and outputs coexist on the available device? Latency: can prefill and generation finish within the application’s budget? Usefulness: can the model actually find and combine relevant evidence in that context? A configuration answers at most part of the first question. This chapter puts distinct evidence beside each claim, using cached model configurations, local GPU measurements, positional interventions and a controlled retrieval task. The results must not be collapsed into a single “maximum context” number.
Where this sits
Key-Value Caching derived KV-cache size; PagedAttention and Prefix Caching managed it; Multi-Head and Multi-Latent Attention reduced it with shared key/value heads; and Sliding-Window Attention bounded it with windows. Here the prompt grows without those restrictions. Attention and Its Computational Cost and FlashAttention and Optimized Kernels explain why materialising attention scores differs from memory-efficient attention, while Prefill and Decode introduced chunked prefill. The Multi-Head and Multi-Latent Attention warning about choosing a grouped-attention implementation is directly relevant: an architectural saving means little if the selected runtime path materialises much larger intermediates.
The Inference Lab increment is a long-context evaluation harness: config-based KV and FLOP accounting, a temporary PyTorch SDPA attention override, chunked prefill, position-bucket language-model loss, GPU peak-allocation and latency measurements, a seeded needle-at-depth test, and truncation/cache-reuse helpers. The model experiments use local checkpoints and one GPU; they do not constitute a general benchmark of production serving. Model Architecture Versus Runtime Architecture will separate model-intrinsic behaviour from runtime-dependent behaviour.
For the Pi series, this suggests an evidence-bearing context capability record rather than an advertisement: the exact model and positional configuration, tokenizer, maximum tested input, usable GPU memory, prefill and decode implementations, observed latency, and task-level retrieval or reasoning checks. A result from one layer, one prompt length or one kernel should never silently become a claim about the entire system.
Claim one: it accepts the tokens
The first number comes from a model’s configuration, not from a test of its training distribution or an API’s ability to complete a request. The following are configured maximum positions, position-encoding settings read from local config.json files, and ideal fp16 KV tensor payload at that maximum. The arithmetic assumes all attention layers cache their full context and ignores weights, activation peaks, cache metadata, fragmentation, logits and batching. For a model with local windows, this is deliberately an all-global upper-bound scenario, not the actual hybrid allocation.
| Model | Configured maximum positions | Positional scheme | Ideal fp16 KV payload at that length |
|---|---|---|---|
| GPT-2 | 1,024 | learned absolute positions | 0.04 GiB |
| TinyLlama-1.1B | 2,048 | plain | 0.04 GiB |
| Phi-3-mini-4k | 4,096 | plain | 1.50 GiB |
| Gemma-2-2B | 8,192 | plain | 0.81 GiB (counting every layer at full length) |
| Mistral-7B-Instruct-v0.3 | 32,768 | plain | 4.00 GiB |
| Llama-3.2-1B | 131,072 | llama3, factor 32, from 8,192 |
4.00 GiB |
| Llama-3.2-3B | 131,072 | llama3, factor 32, from 8,192 |
14.0 GiB |
| Llama-3.1-8B | 131,072 | llama3, factor 8, from 8,192 |
16.0 GiB |
Llama-3.2-3B’s configured 131,072 positions imply 14.0 GiB of fp16 KV payload, already greater than the entire nominal 12 GiB device; its roughly 6.43 GB of fp16 parameters must also be resident or streamed. The 4 GiB-of-KV hypothetical budget in cmd_limits holds at most 37,449 tokens for this model, before allocation overheads and prefill intermediates. That is not a measured maximum runnable context, nor does a configured limit establish that the model was trained on uniformly sampled sequences up to that length. A real admission limit must account for the hardware, memory reserved for execution and the active serving configuration.
Claim two: it behaves at those positions
Rotary position embeddings (RoPE) rotate query and key components so their dot products depend on relative position. Evaluating a RoPE checkpoint outside the position regime it encountered during training may change attention behaviour. Position Interpolation rescales positions into an earlier range and fine-tunes the model; YaRN and LongRoPE develop other extension procedures, with their published efficiency and length claims belonging to their authors. Those papers do not say that changing a configuration flag alone reproduces their trained checkpoints. The local experiment below isolates the consequence of changing RoPE settings without further training. Because positions, base frequency and scaling convention change the transform applied by fixed weights, the full positional configuration belongs to the model artefact’s identity. The available tests measure loss, not proof of semantic reliability at every advertised position.
TinyLlama, configured for 2,048 positions. Six 4,096-token book passages were scored with a growing cache in 1,024-token chunks. Values below are mean token negative log-likelihood (nats), grouped by predicted-token position. The linear and dynamic variants are interventions on the same pretrained weights, without extension fine-tuning; “trained to 2,048” here refers to the model’s configured original context, not an independently audited training-data distribution.
| Positions | Default RoPE | Linear scaling × 2, no training | “Dynamic” scaling × 2, no training |
|---|---|---|---|
| 0–512 | 2.92 | 3.62 | 2.92 |
| 512–1,024 | 2.56 | 3.39 | 2.56 |
| 1,024–2,048 | 2.42 | 3.45 | 2.42 |
| 2,048–3,072 | 7.20 | 3.54 | 7.86 |
| 3,072–4,095 | 8.43 | 3.57 | 7.18 |
Beyond position 2,048, the default TinyLlama loss rose to 7.20 and then 8.43 nats per token in these passages. Linear scaling by two kept the measured outer buckets near 3.5 nats but worsened the buckets within the original range by roughly 0.7–1.0 nats. The tested dynamic variant was unchanged within the original range and remained poor beyond it (7.86 and 7.18 nats). These are particular cache-based calls to this library build, not a verdict on properly fine-tuned dynamic-scaling methods. No scaling variant was trained or evaluated on held-out general-language tasks; the experiment demonstrates that changing positional arithmetic can trade one positional regime’s loss for another’s.
Llama-3.2-1B, with and without the checkpoint’s shipped RoPE configuration. The local config specifies rope_type: llama3, scaling factor 32 and original maximum 8,192. Two 16,384-token book passages were evaluated twice with the same weights: once under the shipped configuration and once under plain RoPE with the same base. The numbers are token negative log-likelihood in nats, not task accuracy. The experiment does not independently establish the length distribution used in training.
| Positions | As shipped | Scaling removed |
|---|---|---|
| 0–1,024 | 3.29 | 3.30 |
| 1,024–2,048 | 3.15 | 3.19 |
| 2,048–4,096 | 2.48 | 2.54 |
| 4,096–8,192 | 2.76 | 2.94 |
| 8,192–12,288 | 2.84 | 3.65 |
| 12,288–16,383 | 2.73 | 5.68 |
With the shipped setting, mean loss stayed around 2.7–2.8 nats from positions 4,096 to 16,383 in these two passages. Replacing that setting with plain RoPE increased the final bucket from 2.73 to 5.68 nats, with a smaller gap at earlier positions. This is strong local evidence that the model’s RoPE configuration affects the computed function and matters at longer positions. It is not evidence that every task succeeds at 16K, let alone that 131,072 tokens are useful. A serving manifest should bind the checkpoint to its complete positional settings; neither omitting shipped scaling nor adding an untrained extension should be presented as an implementation-only optimisation.
Claim three: it fits
The formula for KV bytes predicts persistent cache tensor payload, not the peak allocation while the model is building it. The two can differ by orders of magnitude when attention scores, repeated keys/values, intermediate activations or the full-vocabulary logits are materialised. For this chapter we therefore record both the calculated KV payload and PyTorch’s measured peak additional allocated bytes above the pre-run baseline.
Peak allocation for Llama-3.2-1B on the recorded GPU and PyTorch build, in GiB. Important: the table’s implementation columns are torch.cuda.max_memory_allocated() - baseline allocated, so they include allocations for the newly built KV cache; they are not “beyond weights and cache.” The separate Cache column is the ideal calculated KV payload and must not be added to the measured peak-extra value. “Fused” names the custom SDPA attention override used in the experiment; the underlying PyTorch kernel backend was not pinned or profiled.
| Tokens | Cache | Default attention, one shot | Default, chunked by 1,024 | Fused attention, one shot | Fused, chunked by 2,048 |
|---|---|---|---|---|---|
| 1,024 | 0.03 | 0.38 | 0.37 | 0.09 | 0.09 |
| 2,048 | 0.06 | 1.31 | 0.37 | 0.19 | 0.19 |
| 4,096 | 0.12 | 4.89 | 0.37 | 0.38 | 0.26 |
| 8,192 | 0.25 | (≈ 19, probe) | 0.37 | 0.75 | 0.40 |
| 16,384 | 0.50 | — | 0.69 | 1.50 | 0.76 |
| 32,768 | 1.00 | — | 1.36 | 3.01 | 1.48 |
For the default one-shot path, peak-extra allocation increased from 0.38 to 1.31 to 4.89 GiB as the token count doubled from 1K to 2K to 4K, consistent with a large quadratic intermediate. The attribution to materialised attention scores is supported by the scaling and the source path, not verified with a kernel-level memory trace. One-shot default runs above 4K were skipped in the final sweep because they were predicted to exceed the card’s budget; the approximately 18.91 GiB result at 8K came from a separate oversubscribed probe. Chunking by 1,024 held peak extra allocation near 0.37 GiB through 8K, not indefinitely: it rose to 0.69 GiB at 16K and 1.36 GiB at 32K as the cache itself grew. The custom SDPA override reduced the recorded peak and could be combined with chunking, but its prefill implementation temporarily repeats key/value heads. Small-model CPU tests found its logits within 1e-4 of the default and checked chunked continuation; they do not guarantee equivalence across every model, mask, cache type and PyTorch backend. These are useful implementation results, not proof of a universally linear-memory or fixed-memory server.
The experiment changes the likely limiting mechanism. Under the tested default attention path, the observed prefill allocation is much larger than the calculated KV payload even at 4K. Under the tested override and chunking, the KV cache becomes a more visible part of the overall memory demand. But at 128K the 1B checkpoint alone would require 4 GiB of KV tensors and additional working memory; neither a 128K prefill nor sustained 128K serving was run here. The practical context limit must be measured for the entire implementation, not inferred either from cache arithmetic alone or by extrapolating an allocation curve from 4K.
There are also two separable memory hazards: producing logits at positions the application will never read, and letting an allocation exceed the device’s physical memory budget. Neither is captured by KV bytes per token.
Output logits. A language-model forward pass can produce one vocabulary-sized logit vector for every input position. With Llama-3.2-1B’s 128,256-entry vocabulary and fp16 outputs, that tensor alone is about 0.98 GiB at 4,096 tokens and 31.3 GiB at 131,072 tokens. The local benchmark found that requesting all logits rather than only the final position raised its measured peak-extra allocation from 0.19 to 0.56 GiB at 2K, and from 0.38 to 1.12 GiB at 4K. The peak difference need not equal the full tensor’s theoretical byte size because peak live allocations depend on implementation and lifetime. For a pure prefill whose next action is token generation, requesting only final-position logits removes avoidable work; for per-token loss evaluation, the experiment deliberately needs the logits at many positions.
Oversubscription and contention. In excluded Windows/GPU probes, allocations larger than physical VRAM were reported without an immediate CUDA out-of-memory error and were accompanied by severe slowdowns: one 32K prefill took 25.5 seconds while another program occupied about 5.4 GB, versus 6.58 seconds in a less-contended run. The observations are consistent with WDDM-managed memory oversubscription; they do not directly trace each page transfer or isolate paging from scheduling contention. The final long-context commands check reported free GPU memory and skip runs predicted to be unsafe, but a pre-run check is not a reservation: concurrent processes may still change the available capacity. Record resident VRAM, other processes, skips and failed probes alongside any latency claim.
Claim four: it answers in time
Measured prefill-to-final-logits latency, in seconds, for Llama-3.2-1B under the custom SDPA override (best of three trials). This is an in-process, single-request GPU measurement without request queuing, network transport or output streaming—not a deployed service’s time to first delivered token. The FLOP-share column is an analytical estimate, not a profiler measurement.
| Tokens | One-shot prefill | Prefill in 4,096-token chunks | Modelled attention FLOP fraction |
|---|---|---|---|
| 1,024 | 0.093 s | 0.093 s | 3% |
| 4,096 | 0.40 s | 0.40 s | 10% |
| 8,192 | 0.92 s | 1.12 s | 18% |
| 16,384 | 2.34 s | 3.18 s | 30% |
| 32,768 | 6.58 s | 9.91 s | 46% |
| 49,152 | not run | 20.2 s | 57% |
An approximate prefill operation model separates dense parameter work from causal attention:
A single fitted throughput of about 28 TFLOP/s, based on short inputs, predicted 5.39 seconds for the 32K prefill versus 6.58 seconds observed (about 18% low). A two-coefficient model fit to the 4K, 8K and 16K one-shot runs estimated 30.0 TFLOP/s for the dense term and 17.8 TFLOP/s for attention, then predicted 6.65 seconds at 32K. This held-out 32K point came from the separate memory-measurement sweep, not the latency command’s one-shot series, which skipped one-shot runs above 16K. Three fit points for two coefficients leave only one residual degree of freedom, and there is just one cross-run check. These effective throughputs are fit parameters, not independently profiled hardware or kernel FLOP rates; neither their relative values nor the near-match at 32K proves a specific bottleneck.
Chunking took 9.91 seconds for 32K in the latency sweep, while the separate one-shot memory sweep recorded 6.58 seconds. The current override repeats the shared key/value heads during multi-token attention; repeated per-chunk allocations and launches are possible contributors to the extra time, but they were not isolated. Chunking is therefore a peak-memory/latency trade-off in these measurements, not a universally faster prefill strategy. Compare equivalent execution conditions, and profile materialisation and kernel choice, before assigning the cause.
Decode must be evaluated separately. For batch-one Llama-3.2-1B, the accounting model adds approximately 2.472 GB of fp16 weights to the growing KV tensor payload and divides by the Memory Bandwidth and Compute Bottlenecks measured 304 GB/s memory-bandwidth figure. That yields a read-bandwidth lower-bound calculation, not a prediction that each weight is transferred exactly once from DRAM or that every kernel saturates that bandwidth. The measured full-model step is a warmed, synchronous call on a populated cache; the benchmark reuses the same next-token input and crops the cache back to its original length between trials. The resulting latencies are for the same execution shape, not a sampled generation workload.
| Cached tokens | 1K | 4K | 8K | 16K | 32K | 49K |
|---|---|---|---|---|---|---|
| Step, ms | 14.7 | 17.3 | 23.0 | 33.1 | 56.6 | 85.2 |
| Bytes alone, ms | 8.2 | 8.6 | 9.0 | 9.9 | 11.7 | 13.4 |
From 1K to 49K cached tokens, the best recorded batch-one step grew from 14.7 to 85.2 ms. The summary’s fitted slope is about 1.47 ms per additional thousand cached tokens, versus roughly 0.108 ms per thousand for added KV bytes at the nominal bandwidth—a roughly 13.6× slope difference, not a literal measured “13× bytes” event. The isolated, batch-one SDPA attention kernel took 2.02 ms at 32K for one layer, compared with a 0.22 ms KV-byte floor. Eight-way split-KV reduced that isolated kernel to 0.984 ms and agreed numerically with the reference to the tolerance recorded in results.json. The proposed cause—insufficient parallelism over the long key dimension—is plausible but unverified, because no selected-kernel trace or occupancy profile was saved. Multiplying the isolated 32K kernel’s 2.02 ms by 16 layers gives about 32.3 ms, which is 77% of the 41.95 ms total-model increase between 1K and 32K. That is only a suggestive comparison of unlike quantities, not a measured decomposition of the increase: the proper attribution would subtract corresponding isolated 1K kernel time and include projection, launch and cache-management changes. The split-KV code was not integrated into the model; no end-to-end speed-up or 77% recoverable fraction has been demonstrated.
These results show that a simple KV-byte floor substantially understates batch-one long-context latency on this implementation. It is reasonable to investigate launch structure, key-dimension parallelism, kernel backend and occupancy rather than assume memory bytes alone explain the curve. But “kernel limited rather than bandwidth limited” is not a proven hardware classification without profiling. Multi-Head and Multi-Latent Attention’s larger-batch attention measurements suggest one avenue for improvement; they do not establish the batch-throughput and queueing trade-offs of a complete long-context service.
Claim five: it uses what it is given
A model may successfully ingest a passage, allocate its cache and generate a reply without relying on the information that matters. Two tests here examine next-token predictive benefit and single-fact retrieval. Neither alone establishes multi-hop reasoning or robust use of the full advertised 128K context.
Does distant text improve next-token prediction? Two 32,768-token passages drawn from the book’s early chapters were divided into eight 4,096-token segments. For the same target positions in the latter half of each segment, I compared negative log-likelihood when earlier segments remained available in the cache against a reset-cache evaluation of that segment alone. Segment zero served as a same-context control. Over the remaining segments the reported mean improvement was 0.329 nats per token, ranging from 0.061 to 0.497 across segment comparisons, equivalent to a perplexity ratio of about 1.39. This supports the narrow finding that earlier text helped predict these tokens. It does not say which earlier tokens caused the benefit, whether the model recovered specific facts, or whether the gain transfers to unrelated documents. Only two passages were tested, and the manuscript’s repetitive structure is a material limitation.
Can it retrieve a planted fact? The needle harness inserts a short sentence containing a numerical fact into book-text filler and appends a question using the model’s chat template. It sweeps five nominal context lengths (2K, 4K, 8K, 16K, 32K), five insertion depths (0%, 25%, 50%, 75%, 100%) and 12 fixed fact/question pairs, yielding 300 tested prompts, each with greedy decoding capped at 12 generated tokens. The generator reserves space for its wrapper and question; recorded per-prompt token counts should be checked before interpreting nominal length or exact position. Success means the expected number appears as a standalone number anywhere in the decoded answer; the matcher does not verify that the model attributed it correctly or avoided contradictory numbers. Two no-needle control sets, at 2K and 8K only, produced 0/12 matches each. Those controls show that the model did not produce the target numbers in those 24 cases; they do not prove that every answer is unguessable or exclude contamination at other lengths. Correct matches per 12 trials are:
| Length | Depth 0% | 25% | 50% | 75% | 100% |
|---|---|---|---|---|---|
| 2K | 12 | 9 | 10 | 7 | 11 |
| 4K | 12 | 10 | 11 | 11 | 12 |
| 8K | 12 | 10 | 8 | 9 | 12 |
| 16K | 11 | 8 | 6 | 9 | 12 |
| 32K | 11 | 7 | 12 | 8 | 12 |
The clearest descriptive pattern is position sensitivity. Across the five nominal lengths, the two endpoint depths were correct 117/120 (97.5%), while the three interior depths were correct 135/180 (75.0%). The original analysis calculated Fisher’s exact-test \(p \approx 3 \times 10^{-8}\) by treating those 300 prompt outcomes as independent. That independence assumption is inappropriate as a full uncertainty model here: the same twelve facts, templates and related book material recur across lengths and depths. Keep the Fisher result as an exploratory, naive contingency-table statistic, not a validated generalisation probability. Report the per-fact and per-length differences and use fact-blocked or independently sampled replications to quantify uncertainty. The shape resembles Liu et al.’s published Lost in the Middle findings, but their tasks and models differ. Length does not have an established monotone effect in this grid: pooled matches were 49, 56, 51, 46 and 50 of 60 from 2K to 32K. That does not establish equal performance at 2K and 32K; twelve repeated facts per cell, shared filler and a single model give limited power to distinguish these conditions.
Failures also varied by fact. In the recorded classification of 48 mismatches, 27 produced a bare incorrect number, 13 restated the planted sentence with an incorrect number, and eight returned no number. Three fact/question pairs were matched in every cell, while the bell-number and lighthouse-step examples were harder. This is an output-matching taxonomy, not a diagnosis of why the model failed. A wrong number could reflect failure to find the sentence, failure to copy it correctly, a prompt interpretation problem, truncation, or another mechanism; the present test cannot separate them. A larger model or a multi-fact task might behave differently, and neither was run. Review full answers—not just regex matches—before treating this benchmark as a reliable retrieval-quality measure.
Truncating, and what a cache survives
When an input exceeds a runtime limit, the truncation rule changes both the model’s input and the validity of cached states. truncate_keep_prefix preserves a designated initial token prefix and the most recent suffix, deleting the intervening older tokens; it operates on token IDs, not on chat messages or semantic turns, so the caller must preserve message boundaries and important instructions itself. For full causal attention, the conservative reusable state is the longest unchanged token prefix with unchanged position/attention semantics. Later KV entries in the original prompt were computed with a different preceding context; retaining them after a middle deletion is not an exact continuation in general. The unit test demonstrates the policy’s token arithmetic: a 100-token sequence truncated to 40 with ten reserved initial tokens has a common prefix of ten tokens. This is a policy-level test, not a model-level experiment proving the cost of stale KV states. Extra cache reuse may be possible under specialised local-attention or validated approximate schemes, but it must not be silently treated as exact.
Prefix Caching’s prefix-identity rule therefore applies only after accounting for tokenisation, positional configuration, cache layout and any context transformation. Same surviving content is not enough if the retained suffix moved to new positions or the prefix before it changed. For a production system, record how truncation was chosen, which KV blocks were invalidated, and whether any reuse was explicitly approximate.
What the numbers do not show
- Model scope. Long-context measurements focus on Llama-3.2-1B and TinyLlama; cached 3B/8B configurations were read but those checkpoints were not evaluated at long length.
- Configured versus demonstrated context.
max_position_embeddingsis a config limit, not an audit of the training distribution, deployed API admission rules or model quality at the upper bound. No complete 128K generation run was demonstrated. - Source corpus drift. The
book_idshelper assembles text directly from changing manuscript files. A later revision of What Is Inference?–Sliding-Window Attention changes inputs and can invalidate comparability; pin exact source hashes and tokenised prompt manifests before rerunning. - Benchmark isolation. The GPU was shared. A free-memory check does not reserve memory, and the discarded oversubscribed probes must not be combined with clean latency runs.
- Attention backend. The SDPA override is a local implementation with CPU small-model equivalence tests; the effective GPU backend, allocator trace, kernel occupancy and other model families were not qualified.
- Memory accounting. PyTorch’s reported peak-extra allocations already include newly allocated KV tensors. Estimated full-context cache payload does not include fragmentation, logits, or model working memory.
- Task scope. The loss test used two book passages; the needle grid reused twelve facts across 25 cells. Regex matching and no-needle controls do not assess explanation, multi-fact reasoning or out-of-distribution retrieval.
- Inference and statistics. FLOP throughputs were fitted rather than profiled; the 77% kernel attribution is not an isolated contribution; the naive Fisher result assumes independent trials that the test design does not provide.
- Not evaluated. Fine-tuned RoPE extension methods, long-context reasoning, the effect of approximate cache reuse, networked serving and end-to-end split-KV integration.
Inference Lab increment
The implementation exposes the following reusable components. Their presence is an implementation inventory, not evidence that they have been qualified for production serving:
kv_bytes,max_context_for_budget,prefill_flops,attention_crossover_tokens,decode_bytes_per_step: tensor-payload and cost-model arithmetic, with explicit assumptions.fused_attention: a temporary replacement of the installed library’ssdpaattention registration, using repeated KV heads on multi-token prefill and grouped queries for single-token decode; actual backend dispatch is not pinned.prefill_chunked,token_nll: growing-cache processing, last-position logits for prefill, and token-level language-model loss when intermediate logits are needed.insert_at_depth,contains_answer, twelve planted facts and a chat-templated prompt builder: a numerical-matching retrieval harness, with its independence and grading limitations.truncate_keep_prefix,reusable_prefix_length: token-ID truncation and exact common-prefix counting, without a validated model-level stale-cache reuse experiment.limits,latency,positions,use,decode_kernel,needle: executable experiment commands that should be accompanied by device/environment metadata and immutable corpus/prompt hashes.
The operational rule this chapter adds is: a long context must be qualified along five independent axes—admission, positional behaviour, peak memory, latency and task usefulness. Cache-payload arithmetic is necessary but not sufficient for peak VRAM; efficient prefill memory does not imply efficient decode; and a correct retrieval result at one depth does not certify all depths or more complex tasks. Attach each advertised limit to a versioned model, runtime, hardware budget and evidence report. Otherwise, the word “supported” remains ambiguous.
What you should now be able to do
- Distinguish a model’s configured position limit from a tested, memory-safe, task-useful serving context.
- Derive ideal KV payload and FLOP proxies while explaining the additional allocations that determine actual peak GPU memory.
- Test a checkpoint’s shipped RoPE parameters against a controlled intervention without claiming that untrained scaling reproduces published extension methods.
- Reproduce the default-versus-SDPA-override and one-shot-versus-chunked prefill comparisons, recording peak allocation, reserved memory and backend choice separately.
- Measure isolated decode attention and complete decode steps without converting an unpaired kernel timing into a causal attribution or an end-to-end speed-up.
- Design needle tests with no-needle controls, per-fact results, a validated output grader, and uncertainty estimates that respect repeated prompts.
- Apply prefix-preserving truncation and identify exactly which cache states remain valid under unchanged token, position and model semantics.
Key terms
- Configured context limit: maximum sequence length recorded in a model/config or admitted by an interface; neither number guarantees useful inference.
- Long-context qualification: separate checks for acceptance, positional correctness, working memory, latency and use of relevant information.
- RoPE scaling: changing rotary-frequency or position mappings; the complete checkpoint-specific settings determine the computed function.
- Position Interpolation: a positional downscaling and fine-tuning method for context extension; not equivalent to an untrained configuration toggle.
- Chunked prefill: populating the KV cache in smaller forward passes, trading peak working memory against additional execution costs.
- Peak extra allocated memory: highest PyTorch allocated GPU bytes during the call minus the pre-run baseline; includes newly allocated cache tensors.
- Logits to keep: how many final token positions need output-vocabulary logits in a prefill call.
- Needle in a haystack: a planted-fact retrieval test with controlled position and input length, requiring careful grading.
- Lost in the middle: a tendency for retrieval accuracy to decline when relevant evidence lies inside rather than near an input’s ends.
- Reusable prefix: maximal unchanged token prefix whose positional and model semantics also remain unchanged, permitting exact KV reuse.
Reader exercises
- Run the needle grid on Llama-3.2-3B only after a new memory-admission check; compare endpoints and interior depths using the same frozen prompt set.
- Integrate eight-way split-KV attention into the actual model, then measure 1K and 32K decode latency with profiler traces. What fraction of the incremental latency falls, rather than merely comparing a 32K kernel time with total growth?
- Fine-tune a TinyLlama checkpoint with linear positional scaling and a recorded training budget, then re-evaluate the original-range and extended-range losses on a held-out corpus.
- Extend the planted-fact task to two interdependent facts at different depths. Require a structured answer that proves both facts were used, with manual grading of a sample.
- Try approximate KV reuse after a middle truncation as a separately labelled approximation, comparing logits, loss, latency and any model safety checks against full recomputation.
- Compare long-prompt retrieval with embedding-based paragraph retrieval followed by a 1K prompt, reporting retrieval misses, answer quality, prompt construction and total time.
- Repeat the peak-allocation table on a 3B model, recording PyTorch allocated and reserved memory, system memory pressure, backend dispatch and skips.
- Freeze and hash all manuscript sources and tokenised prompts. Repeat the twelve needle facts across multiple independent filler samples and estimate uncertainty clustered by fact instead of treating the 300 generated answers as independent.
- Refit the two-component prefill model using several runs per length and multiple held-out lengths; compare its errors with a one-parameter model and inspect whether the fitted throughputs remain stable.
References
The following references explain the model-design and behavioural questions; none validates the book’s local GPU timings or needle counts. Published results are attributed to their authors and should not be conflated with the measurements in research/ch23/results.json.
- RoFormer: Enhanced Transformer with Rotary Position Embedding — Su et al., 2021; rotary embeddings and relative-position structure.
- Extending Context Window of Large Language Models via Positional Interpolation — Chen et al., 2023; positional interpolation with extension fine-tuning.
- YaRN: Efficient Context Window Extension of Large Language Models — Peng et al., 2023; a distinct extension and training procedure, not evaluated locally.
- LongRoPE: Extending LLM Context Window Beyond 2 Million Tokens — Ding et al., ICML 2024; multi-stage, non-uniform positional extension (authors’ reported results, not reproduced).
- Lost in the Middle: How Language Models Use Long Contexts — Liu et al., TACL 2024; position-sensitive retrieval on different models and tasks. Read against the local needle grid with its repeated-fact limitation.
Evidence in this chapter
| Claim | Evidence status and limit |
|---|---|
| RoPE, Position Interpolation, YaRN and LongRoPE provide methods for positional treatment and extension | Primary research, authors’ experimental claims; no published extension method fine-tuned or reproduced here |
| Configured model maxima range from 1K to 131,072; Llama-3.2-3B implies 14 GiB of fp16 KV at 128K | Config-derived arithmetic; not actual training-length verification or a runnable-context test |
| TinyLlama default loss rises beyond 2K; untrained linear scaling trades short-range loss for lower measured long-range loss | Local experiment, six book passages; no extension fine-tuning |
Llama-3.2-1B loss is worse after removing its shipped llama3 RoPE configuration |
Local same-weight intervention, two 16K passages; not full-context task reliability |
| Default 1B prefill has 0.38/1.31/4.89 GiB peak-extra allocation at 1K/2K/4K | PyTorch allocated-memory counter including newly built KV; high-length default calls were skipped after an excluded oversubscription probe |
| Chunked/default and SDPA-override prefill reduce peak allocated memory in these runs | Local, one GPU/build; no kernel trace or general backend portability qualification |
| Requesting only final-position logits reduces peak allocated memory | Local 2K/4K runs; theoretical output tensor size and peak difference are not identical quantities |
| A 32K two-coefficient prefill model predicts 6.65 s versus 6.58 s | Fit at 4K/8K/16K; held-out observation from a different sweep, one cross-run check |
| Batch-one decode timing rises sharply with context; isolated split-KV speeds up one attention layer | Local benchmark; the claimed 77% growth contribution is not a causally measured decomposition; no integrated split-KV serving result |
| Earlier book text reduces token prediction loss by about 0.329 nats | Two passages; same subject and repeated structure; no general-task conclusion |
| Needle accuracy is 117/120 at endpoints and 135/180 at interior depths | Local 300-prompt grid with 12 reused facts; naive Fisher p≈3e-8 assumes independence and is exploratory |
| No-needle controls returned 0/12 at 2K and 8K | Local negative-control samples, not proof of unguessability at all lengths |
| Multi-fact reasoning, model sizes above 1B, 128K full-context serving, long-run cache-reuse correctness | Not measured |
Implementation status
- Manuscript target:
content/books/inference/23-chapter.md. - Runnable examples:
examples/ch23/long_context.py(original starter) andexamples/ch23/long_context_lab.py(the measured harness: arithmetic, temporary SDPA registration, chunked prefill, RoPE interventions and retrieval). - Tests:
tests/test_ch23_long_context.pyandtests/test_ch23_long_context_lab.py. The latter validates arithmetic, token truncation, prompt insertion, numerical agreement of the override and chunked prefill, restoration of the original attention registration, and a RoPE intervention on a small random CPU model; it does not exercise full-length GPU RoPE or production admission. - Recorded experimental evidence:
research/ch23/sources.md,research/ch23/results.jsonandresearch/evidence-register.md. - Source-of-truth caveat: local experiments tokenise current book source files at run time. Freeze their commit, hashes, dependencies, prompts, model revisions and seeds before accepting future comparisons.
- Repository test command:
python -m unittest discover -s tests -v(listed for verification; this editorial pass did not execute it).
This chapter is published with draft = false in its front matter but remains experimentally qualified rather than a final serving benchmark. Its robust result is methodological: accepting a long prompt, preserving the checkpoint’s positional behaviour, fitting the computation, reaching acceptable latency and retrieving evidence are distinct obligations. The chapter does not validate a complete 128K run, models above 1B parameters at long context, fine-tuned context extension, end-to-end split-KV serving or multi-fact reasoning. Model Architecture Versus Runtime Architecture can now use these evidence boundaries to distinguish the responsibilities of the model artefact from those of the runtime.