Learn
Architecture

What is context length (e.g., 32K context) in an LLM?

The short answer

Context length is the maximum number of tokens a model can consider in a single request, counting both the prompt and the generated output. A 32K model can read roughly 24,000 words and still answer. The limit exists because attention cost grows with the square of sequence length and the key-value cache grows linearly.

On this page

What the number actually measures

Context length is a token budget, not a word count and not a memory. A 32K window means the model can hold 32,768 tokens at once, and that budget covers everything: system prompt, tool definitions, conversation history, retrieved documents, the user's message, and the tokens the model itself generates. If you fill 31,000 tokens with a document, you have about 1,700 left for the answer.

Because tokenization varies, the same window holds different amounts of text depending on language and format. English prose averages about four characters per token, so 32K tokens is roughly 24,000 words or 50 pages. Source code is denser - closer to three characters per token - and minified JSON or base64 can be two, so a 32K window might hold only 10,000 words' worth of a data dump.

Two numbers are usually quoted and they are not the same. The training context is what the model was trained on; the served context is what the inference stack will accept, which may be larger (via RoPE scaling or a modified cache) or smaller (because memory ran out). A model card saying 128K tells you the first number, and often nothing about the second.

The three costs of a longer window

Attention compute is quadratic in sequence length. For each layer, the score matrix and the value averaging cost roughly 4 * n^2 * d FLOPs, so doubling the context quadruples attention work. The feed-forward network stays linear at about 16 * n * d^2 per layer. At 4K tokens with d_model 4,096 the two are within a factor of four; by 32K attention is roughly sixteen times the feed-forward cost, and by 128K it dominates the entire forward pass.

Key-value cache memory is linear. Doubling context doubles the bytes you must keep resident per conversation, which is why long-context serving is a capacity problem rather than a compute problem. A 32-layer model with 8 key-value heads of width 128 needs 128 KiB per token in fp16; 32K tokens is 4 GiB per user, and ten concurrent users need 40 GiB before a single weight is loaded.

Prefill latency is linear in tokens but large in absolute terms. Processing 100K tokens through a 7B model costs about 1.4e15 FLOPs, which is a few seconds on a modern GPU even at good utilisation. That delay lands before the first output token, so long prompts feel slow in a way that short prompts never do - and caching a shared prefix is often the single biggest latency win available.

Trained, advertised, effective

Three different limits get conflated in marketing. The trained context is the length the model saw during pretraining, typically 4K-8K for models from 2023 and 8K-32K for more recent ones. The advertised context is what the vendor's API accepts, achieved by scaling RoPE and fine-tuning on longer documents. The effective context is the length at which the model still performs your task accurately.

The gap between advertised and effective is large and well documented. RULER and similar benchmarks show many models that claim 128K losing a large share of their short-context accuracy well before that, with multi-fact tasks degrading long before single-needle retrieval does. The needle test is easy because it requires finding one sentence; real work requires combining several facts, tracking definitions and noticing contradictions.

There is also a positional bias. Accuracy is highest for content at the start and end of a long prompt and lowest in the middle - the "lost in the middle" effect. This is consistent across model families and survives most context extensions, which means how you order a long prompt matters as much as how long it is.

How models get longer windows

The mechanical part is position encoding. RoPE can be rescaled - positions divided (interpolation), base increased (NTK-aware), or frequencies scaled per dimension (YaRN) - so that a model trained at 4K produces sensible attention at 128K. These methods need a short fine-tune, typically a few hundred to a few thousand steps, to recover quality.

The data part is harder and less discussed. Most pretraining corpora are dominated by short documents, so a model trained on them has simply never seen the patterns that appear at 100K tokens: long-range coreference, documents with many sections, codebases with definitions far apart. Long-context continued pretraining upsamples long documents and is what separates a model that tolerates a long window from one that uses it.

The architectural part is about cost. Sliding-window attention, where each layer sees only the last N tokens, makes long context affordable but limits recall to the window unless some layers are global. Hybrid stacks interleave local and global layers, and state-space layers can replace most attention entirely. Each of these trades exact recall at distance for a linear or near-linear cost curve.

What degrades first

  • Multi-fact aggregation: finding five scattered numbers and combining them fails well before single-fact retrieval does.
  • Ordering and counting: "which of these events came first" and "how many times" degrade early because they need every position.
  • Instruction adherence: rules stated once at the top of a 60K prompt get ignored as the prompt grows.
  • Contradiction detection: models tend to answer from the most recent or most salient mention rather than noticing a conflict.
  • Code editing: locating a function 80K tokens in is retrieval; editing it correctly requires holding the surrounding module.
  • Output quality: long generations drift in tone and format even when the input is short, because the model's own output becomes context.

More context is not more knowledge

There is a tempting but wrong inference from large windows: that a model with 128K context knows more. Knowledge lives in the weights, learned during pretraining. The context window is working memory - it changes what the model can consult right now, not what it has learned. Handing a model a document it has never seen is genuinely useful; handing it the same document on every request costs money and adds nothing after the first read.

The practical implication is that context and retrieval are complements, not substitutes. Retrieval decides what is worth putting in working memory, and it scales to corpora far larger than any window. The window then does the part retrieval cannot: letting the model reason across the selected passages at once, resolving references between them, and following instructions that apply to the whole set.

There is also a signal-to-noise effect. Every irrelevant token competes for attention weight, and models are demonstrably worse at finding the relevant passage when it sits among 90K tokens of noise than among 5K. Filtering and reranking are quality interventions, not just cost optimisations.

Capacity maths you can do on a napkin

Given a model, compute bytes per token: 2 x layers x kv_heads x head_dim x bytes. For a 32-layer, 8-KV-head, 128-dim model in fp16 that is 128 KiB. Multiply by context length and concurrency to get total cache. On an 80 GB GPU with 16 GB of weights, you have roughly 60 GB for cache and activations, which is about 480K token-slots - 15 users at 32K, or 3 users at 128K.

Prefill cost per token is roughly 2N FLOPs, so a 70B model at 100K tokens is 1.4e16 FLOPs of prefill, several seconds on one GPU. Batch it and the cost per user falls; make it interactive and every user pays the full latency. This is the arithmetic behind long-context pricing tiers, which commonly double above a threshold such as 200K tokens.

The conclusion for product design is that context and concurrency trade against each other directly. Supporting 128K conversations is not four times harder than 32K; at fixed memory it is four times fewer users on the same hardware, and the latency curve bends upward at the same time.

Conversations grow whether you plan for it or not

A chat session accumulates context with every turn. Twenty turns of a support conversation with tool results can exceed 20K tokens, so a system that worked in testing hits the limit on the third day of real use. The usual fix is to summarise older turns once the history passes a threshold - keep the system prompt, a rolling summary of everything before the last few turns, and the recent messages verbatim.

Summarisation loses detail, so pair it with structured memory. Extract durable facts (account tier, confirmed constraints, decisions made, open questions) into a small state object that is always included, and let the prose summary handle the rest. This keeps a long conversation coherent at a fraction of the token cost and makes behaviour far more predictable than unconstrained history replay.

Track history size as a metric. If you do not know the distribution of prompt tokens per request, you do not know your cost, your latency, or how close you are to truncating the one request that matters.

Designing around the limit

Most production systems should not send everything. Retrieval-augmented generation selects the handful of chunks that matter, which keeps the prompt short, cheap and - crucially - more accurate, because the model is not asked to find a needle in a haystack it was never trained to search. Chunk sizes of 500-1,500 tokens with modest overlap work well, and reranking the top 50 candidates down to the best 5 usually beats doubling the chunk count.

When the input is genuinely one long document, hierarchical processing helps: summarise sections, then summarise the summaries. It loses detail but is predictable and cheap. Map-reduce over chunks with per-chunk extraction, followed by a synthesis pass over the extracted facts, usually outperforms a single 200K-token prompt on extraction tasks and costs less.

Prompt ordering is free performance. Put standing instructions and the question near the end, keep retrieved evidence before the question, and avoid burying the critical document in the middle. If the model supports cached prefixes, put the stable part - system prompt, tool schemas, few-shot examples - first so it can be cached across requests.

How to evaluate it for your task

Build a small evaluation set from your own data at four lengths - 2K, 8K, 32K, and your target - and measure exact-match or judged quality at each. Include a multi-fact task and a task where the answer requires ignoring a plausible distractor. Plot quality against length; the point where it falls below your acceptance threshold is your real context length for that task.

Then measure latency and cost at the same lengths. Time to first token, tokens per second, and dollars per successful answer. A model with a slightly worse quality curve but half the prefill cost may win once retries are counted.

Re-run the evaluation whenever the serving stack changes. Context behaviour is sensitive to RoPE configuration, attention kernel implementation and batching strategy; an upgrade that doubles throughput can quietly move the effective context down.

Common mistakes

  • Assuming the context window is memory. It is a per-request budget, reset every call; the model remembers nothing between requests.
  • Forgetting that the output counts against the window, then getting a truncated answer with no error.
  • Estimating tokens from characters with a generic 4:1 ratio, which is off by 30% or more for code and non-Latin scripts.
  • Sending a whole repository or contract because the window allows it, when retrieval would be cheaper and more accurate.
  • Testing long context with a single needle and concluding the model handles 128K.
  • Ignoring prefill latency: a 100K-token prompt adds seconds before the first token, every time, unless cached.
  • Buying a larger window to avoid building chunking, then discovering accuracy is worse than the short-prompt baseline.

The practical rule

Use the smallest context that solves the task, and treat the advertised window as headroom for edge cases rather than a design target. Short prompts are cheaper, faster, easier to evaluate and usually more accurate, because every extra token is a chance for the model to attend to the wrong thing.

When you do need a long window, budget explicitly: reserve output tokens first, then system and tools, then retrieval, and keep 10-20% in reserve for retries and formatting. Models do not fail politely at the limit; they truncate, drift or hallucinate, and the failure often looks like a quality problem rather than a capacity one.

Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.