FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Context Windows

How finite input and output budgets constrain attention state relevance and cost.

Freshness: current•15 min read•Foundation Models and Multimodal AI

Key Learning Outcomes

  • ✓Budget context accurately
  • ✓Prioritize useful context
  • ✓Identify truncation risks
Full Technical Reference Document

Mental model

A context window is a shared, finite memory surface whose effective capacity is constrained not just by nominal token limits, but by quadratic prefill compute, linear KV-cache HBM growth, Rotary Position Embedding (RoPE) frequency bounds, and U-shaped middle-position recall decay. Reliable systems explicitly partition prefix instructions, working history, retrieved evidence, and output headroom.

Pin prefix for KV reuse
Reserve max_tokens headroom
Compact resolved history
Place evidence at edges
Check HBM and RoPE bounds
Conceptual teaching model synthesized from:OpenAI API ReferenceEffective Context Engineering for AI AgentsRoFormer: Enhanced Transformer with Rotary Position EmbeddingRing Attention with Blockwise Transformers for Near-Infinite Context

Theory

Advertised token limits (128K to 2M tokens) reflect maximum positional index bounds, not free capacity or flat recall fidelity. Every token placed in the prompt shares two physical hardware bottlenecks during inference: prefill attention FLOPs scaling at O(s2)O(s^2) across context length ss, and Key-Value (KV) cache HBM residency growing linearly per token across all decoder layers. For a transformer with LL layers, nkvn_{\text{kv}} key-value heads (via Grouped-Query Attention, GQA), head dimension dheadd_{\text{head}}, sequence length ss, and bb bytes per scalar (2 for FP16/BF16, 1 for FP8), KV cache bytes per active sequence are:

MKV=2⋅L⋅nkv⋅dhead⋅s⋅bM_{\text{KV}} = 2 \cdot L \cdot n_{\text{kv}} \cdot d_{\text{head}} \cdot s \cdot b

Consider a 70B-parameter GQA model (L=80L = 80, nkv=8n_{\text{kv}} = 8, dhead=128d_{\text{head}} = 128, BF16 b=2b = 2). Each token consumes Mtok=2×80×8×128×2=327,680 bytesM_{\text{tok}} = 2 \times 80 \times 8 \times 128 \times 2 = 327{,}680\text{ bytes} (320 KiB/token). Serving a single 128,000-token request demands M128K=128,000×320 KiB=40.96 GBM_{\text{128K}} = 128{,}000 \times 320\text{ KiB} = 40.96\text{ GB} of GPU HBM strictly for KV tensors—more than half an 80 GB H100 GPU before loading model weights! Under standard Multi-Head Attention without GQA (nkv=64n_{\text{kv}} = 64), that same 128K request would require 327.7 GB (> 4 H100 GPUs). Scaling beyond single-device memory limits requires sequence parallelism such as Ring Attention, which partitions query/KV blocks across PP devices in a logical ring and overlaps key-value block communication with blockwise self-attention computation. Quantizing KV cache tensors from BF16 to FP8 cuts HBM residency in half (20.48 GB at 128K tokens) while requiring per-layer calibration checks on long-range needle retrieval.

RoPE Extrapolation, YaRN Scaling, and Attention Sinks

Most modern LLMs encode sequence order via Rotary Position Embeddings (RoPE), rotating query and key 2D subspaces at position mm by angles mθim \theta_i where θi=base−2i/d\theta_i = \text{base}^{-2i/d} (base = 10,000 originally). Notice why naive context extrapolation collapses beyond the training ceiling: high-frequency pairs (small ii) complete full 2π2\pi cycles rapidly while low-frequency pairs (large ii) sweep out untested angles past the training length, causing attention weights to explode or turn noisy. Modern long-context models extend contexts using NTK-aware base scaling (raising base from 10,000 to 500,000+ to slow phase rotation) or YaRN (applying wavelength-dependent interpolation across frequency bands paired with attention temperature scaling).

Rotary Position Embedding (RoPE) Visualizer

q_mk_n
Query q (pos m=2)Key k (pos n=6)
Query Position (m)2
Key Position (n)6
2D Channel Pair (i)Pair #0 (θ_i = 1.0000)
Inner Product Invariance: ⟨R_m q, R_n k⟩
Relative Offset (m - n):-4
Inner Product Value:-0.6536
RoPE Formula: θ_i = 10000^(-2(i-1)/d)⟨R_m q, R_n k⟩ depends ONLY on (m - n)

Even inside nominal training lengths, transformer recall follows a U-shaped ("lost-in-the-middle") curve: early tokens (attention sinks, which absorb excess attention mass to stabilize softmax normalization) and the latest suffix tokens receive disproportionately sharp attention compared to documents buried mid-context (30–70% offset).

Trade-offs

Effective context engineering avoids dumping raw transcripts up to the model ceiling and instead treats prompt assembly as deterministic memory management.

Context StrategyRecall FidelityKV HBM & Prefill CostKV Prefix Cache Hit RateIdeal Production Fit
Unbounded Raw AppendDegrades past 32K (lost-in-middle)High (O(s2)O(s^2) prefill + linear KV)Breaks when oldest turns roll offShort single-turn batch jobs only
Sliding Window TruncationLoses early goals & constraintsBoundedZero (shifting byte 0 invalidates prefix)Stateless ephemeral chat widgets
Compaction + Edge PlacementHigh across long multi-turn runsBounded & predictableHigh (immutable prefix stays pinned)Multi-step coding & research agents
Hybrid RAG + Long ContextHigh when top-k fits edge slotsLowest (4K–16K active prompt)Very HighLarge multi-million document stores

Never sacrifice max_tokens output headroom to squeeze extra retrieved chunks into the prompt: an agent that runs out of completion runway mid-JSON or mid-tool-call crashes downstream parsers reliably.

Failure modes and misconceptions

Assuming a 128K or 1M advertised window guarantees uniform recall at every offset. Needle-in-a-haystack benchmarks often measure single-fact surface lookup; multi-hop reasoning and cross-document conflict detection degrade sharply well before nominal context limits, especially in the middle third of the window.

Sliding-window truncation from the front without preserving immutable prefix bytes. Dropping the oldest system prompt or rolling message #1 off index 0 changes every subsequent RoPE relative position and invalidates provider KV prefix caching on every turn—multiplying time-to-first-token and input cost.

Allowing verbose tool payloads (full HTML pages, raw 5,000-row SQL dumps) into conversation history. One uncompacted tool output can silently consume 40% of the window, displacing instructions or causing silent clipping when request length hits provider limits.

Using character count divided by four as a hard safety ceiling. Code, JSON punctuation, UUIDs, and non-Latin scripts routinely tokenize at 1.5–2.5 characters per token, turning a "safe" character estimate into a 400 Bad Request context-length overflow.

Decision scenario

An autonomous debugging agent handles 30-turn troubleshooting sessions against a 128K-token GQA model, where tool outputs (stack traces, kubectl JSON, SQL query plans) average 4,500 tokens per turn. By turn 15, context swells to 70,000 tokens (~22 GB KV cache per concurrent session on 70B FP16), P95 TTFT degrades past 4.2s, and the agent starts forgetting constraints stated on turn 1. Partition the window explicitly: pin immutable system instructions and tool schemas (2,500 tokens) at byte 0 for 90% KV prefix cache hits, reserve 4,096 tokens strictly for max_tokens output, cap retrieved snippets at 16,000 tokens placed at the prompt tail immediately before the user question, and trigger deterministic tool-output compaction whenever working history crosses 24,000 tokens—summarizing resolved turns while preserving active file paths and error codes verbatim.

Learning outcomes

  • Compute KV cache HBM memory per active request (MKV=2⋅L⋅nkv⋅dhead⋅s⋅bM_{\text{KV}} = 2 \cdot L \cdot n_{\text{kv}} \cdot d_{\text{head}} \cdot s \cdot b) and explain how GQA and Ring Attention scale context capacity.
  • Explain why RoPE base frequency scaling (NTK/YaRN) prevents out-of-distribution phase breakdown and why lost-in-the-middle bias affects prompt layout.
  • Implement deterministic token budgeting, max_tokens output reservation, prefix pinning, and sliding history compaction.

Implementation example

This TypeScript context budgeter pins immutable system instructions at index 0, reserves reserveOutputTokens before packing, summarizes overflow history turns deterministically, and trims retrieved passages cleanly.

typescript
export interface ContextChunk { id: string; text: string; tokens: number; pinned?: boolean; }
​
export function buildContextBudget(
maxContextTokens: number,
reserveOutputTokens: number,
systemTokens: number,
historyTurns: ContextChunk[],
evidenceChunks: ContextChunk[],
compactedSummaryTokens = 0,
) {
const usableBudget = maxContextTokens - reserveOutputTokens - systemTokens;
if (usableBudget <= 0) {
throw new Error("System prompt and output headroom exceed maxContextTokens");
}
const evidenceCap = Math.floor(usableBudget * 0.55);
const historyCap = usableBudget - evidenceCap - compactedSummaryTokens;
const keptHistory: ContextChunk[] = [];
let usedHistory = 0;
for (let i = historyTurns.length - 1; i >= 0; i--) {
const turn = historyTurns[i];
if (!turn.pinned && usedHistory + turn.tokens > historyCap) continue;
keptHistory.unshift(turn);
usedHistory += turn.tokens;
}
const keptEvidence: ContextChunk[] = [];
let usedEvidence = 0;
for (const chunk of evidenceChunks) {
if (usedEvidence + chunk.tokens > evidenceCap) break;
keptEvidence.push(chunk);
usedEvidence += chunk.tokens;
}
return { keptHistory, keptEvidence, droppedHistoryCount: historyTurns.length - keptHistory.length };
}
Reflect before revealing the guide

Why does truncating conversation history from index 0 destroy KV prefix caching, and how does GQA reduce KV HBM scaling across long context windows?

Prerequisites & Related Concepts (4)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next