4.2.10Tokenization & Language Modeling

Context window and sequence length

2,142 words10 min readdifficulty · medium1 backlinks

WHAT is it?

WHY the distinction matters: sequence length is your choice per request; context window is the model's hard ceiling. Confusing them causes silent failures where the model "forgets" the start of a long document.


WHY is there a limit at all?

The limit is not arbitrary — it comes from self-attention cost.

Deriving the cost from scratch

Step 1 — count the comparisons. For a sequence of length LL, attention builds an attention matrix AA where entry AijA_{ij} = how much token ii attends to token jj.

Why this step? Because attention is defined as a weighted sum over all positions, so we need a weight for every (query, key) pair.

The number of entries is: #pairs=L×L=L2\#\text{pairs} = L \times L = L^2

Step 2 — compute cost of building AA. Each entry is a dot product of two vectors of dimension dd (the model width). One dot product costs d\sim d multiply-adds. There are L2L^2 entries, so:

Compute    L2d\text{Compute} \;\propto\; L^2 \cdot d

Step 3 — memory. The full attention matrix AA must be stored to apply softmax. It has L2L^2 entries (each a single scalar weight), so: Memory (attention weights)    L2\text{Memory (attention weights)} \;\propto\; L^2 (Separately, the Q/K/V tensors cost only O(Ld)\mathcal{O}(L \cdot d) — linear in LL. The dominant, quadratic term is the L2L^2 attention matrix.)


HOW does a model "know" positions?

If attention just sums over tokens, order is lost ("dog bites man" = "man bites dog"). So we add positional information.

WHY this caps context in older models: classic learned/sinusoidal position tables were built up to a fixed length nctxn_{ctx}. Ask for position nctx+1n_{ctx}+1 and there is simply no encoding for it → the model degrades sharply. Modern tricks (RoPE, ALiBi, interpolation) extend this, but the trained window is still where quality is guaranteed.


Figure — Context window and sequence length

Worked examples


Common mistakes (steel-manned)


Active recall

Recall Quick self-test (hide answers, forecast first)
  • What is the difference between sequence length and context window?
  • Why is attention compute O(L2d)\mathcal{O}(L^2 d) but attention memory O(L2)\mathcal{O}(L^2)?
  • If nctxn_{ctx} goes 1k → 4k, how much more attention compute?
  • Where does prompt end and output budget begin?

Answers: seq length = current input tokens (your choice, \le ceiling); context window = trained max (fixed). Compute has an extra dd from each pairwise dot product; the stored weights are single scalars so memory is just L2L^2 (plus LdL d for Q/K/V). 16×. They share the same window: input+outputnctx\text{input}+\text{output}\le n_{ctx}.

Recall Feynman: explain it to a 12-year-old

Imagine reading a story through a paper tube — you can only see a few words at a time. The context window is how wide your tube is. If the story is longer than the tube, the beginning slides out of view and you forget it. To see more, you'd need a wider tube — but making the tube twice as wide is four times as much work for your eyes, because you now have to compare every word with every other word you can see.


Flashcards

What is the context window of a language model?
The maximum number of tokens the model was built/trained to process at once — a fixed architectural ceiling (nctxn_{ctx}).
What is sequence length vs context window?
Sequence length = tokens in the current input (your per-request choice); context window = the fixed maximum the model supports. Requirement: LnctxL \le n_{ctx}.
Why is self-attention compute O(L2d)\mathcal{O}(L^2 \cdot d)?
Each token attends to every other token (L2L^2 query–key pairs) and each pair costs a dd-dimensional dot product, giving L2dL^2 d.
Why is self-attention memory O(L2)\mathcal{O}(L^2) (not L2dL^2 d)?
The stored attention matrix holds one scalar weight per (query,key) pair — L2L^2 scalars. The dd factor only appears in compute; Q/K/V storage is a separate O(Ld)\mathcal{O}(L d) term.
If context length goes from 2048 to 8192, how much more attention compute?
(8192/2048)2=42=16×(8192/2048)^2 = 4^2 = 16\times.
Does the context window hold only the prompt?
No — prompt tokens AND generated output tokens share the same window: input+outputnctx\text{input} + \text{output} \le n_{ctx}.
Are context windows measured in words?
No, in tokens (subword units); English is ~1.3 tokens/word, more for code/other languages.
What is the "lost in the middle" effect?
Even within the window, models use information at the start and end far better than in the middle.
Why do older models fail past their trained length?
Positional encodings only exist up to nctxn_{ctx}; positions beyond it have no learned/defined encoding, so quality collapses.
Roughly how many tokens is a 6000-word English essay?
About 6000×1.378006000 \times 1.3 \approx 7800 tokens.

Connections

  • Tokenization — the window is counted in tokens, so tokenizer efficiency directly affects how much text fits.
  • Self-Attention — the O(L2)\mathcal{O}(L^2) mechanism that creates the limit.
  • Positional Encoding — RoPE/ALiBi/interpolation determine how far the window can be extended.
  • Transformer Architecture — where model width dd and depth interact with LL.
  • Truncation and Chunking — practical strategies when L>nctxL > n_{ctx}.
  • KV Cache — memory for stored keys/values also grows with sequence length during generation.

Concept Map

must satisfy L <= n_ctx

counts

hard ceiling set at

every token compares all

L^2 dot products of dim d

store scalar weights

combine into

combine into

doubling context quadruples cost

forces

Sequence length L

Context window n_ctx

Tokens

Self-attention

Attention matrix L x L

Compute O of L^2 times d

Memory O of L^2

Quadratic law

Finite context limit

Truncate chunk or summarize

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Socho ek Transformer model ek lambe scroll ko ek paper tube ke through padh raha hai. Jitne tokens us tube ke andar aa sakte hain, wahi context window hai — model ka fixed maximum (nctxn_{ctx}). Aur sequence length (LL) matlab abhi aapne jo actual input diya hai uske tokens. Rule simple hai: LnctxL \le n_{ctx}. Agar aapka document context window se bada ho gaya, toh shuru ka hissa tube se bahar slide ho jayega aur model use "bhool" jayega. Yaad rakho — ye sab tokens me counted hota hai, words me nahi. English me roughly 1.31.3 tokens per word lagao.

Ab sawaal — ye limit hai hi kyun? Iska reason hai self-attention. Har token baaki sabhi tokens ko dekhta hai, toh L×L=L2L \times L = L^2 pairs ban-te hain. Isliye compute O(L2d)\mathcal{O}(L^2 \cdot d) hai (har pair ek dd-dimensional dot product) aur memory O(L2)\mathcal{O}(L^2) (attention matrix me har pair ka bas ek scalar weight store hota hai; dd wala factor sirf compute me aata hai). Q/K/V ka storage alag se O(Ld)\mathcal{O}(L \cdot d) hota hai — linear. Matlab agar context 2× kar do, cost 4× ho jaati hai. Isliye long-context models mehnge hote hain — ye koi arbitrary decision nahi, quadratic maths hai.

Ek practical baat: context window sirf input ke liye nahi hota — prompt + generated output dono usi window me fit hote hain. Agar prompt 6000 tokens le liya aur nctx=8192n_{ctx}=8192 hai, toh output ke liye sirf 2192 tokens bache. Aur ek trap: bade window me bhi model "lost in the middle" ho jaata hai — beech ka content theek se use nahi hota. Isliye important instructions ko shuru ya end me rakho.

Exam aur real projects dono me ye samajhna zaroori hai: token budgeting galat kiya toh model chup-chaap document ka aadha hissa kaat dega aur aapko galat ya adhoora answer milega. Toh hamesha tokens estimate karo, L2L^2 cost yaad rakho, aur window ko input+output dono ke liye plan karo.

Go deeper — visual, from zero

Test yourself — Tokenization & Language Modeling

Connections