Token identities and contextual representations
A forward pass applies the model’s operations once: token IDs become vectors, transformer blocks update them, and an output head converts the resulting representations into task scores. A contextual representation is a vector influenced by other visible positions. Text generation adds a surrounding selection-and-repeat process.
A token occurrence is a vocabulary ID at a sequence position; Tokenization explains how text becomes these IDs. An embedding table stores one learned vector—a list of numerical coordinates—per vocabulary entry. The ID selects a row. Its magnitude does not measure meaning.
From IDs to task scores
Representations change before the output head scores a task.
Read the diagram as text
- Token IDs.
- Token + position vectors.
- Transformer blocks.
- Final normalization + head.
- Vocabulary scores.
- Token IDs → Token + position vectors: lookup + position.
- Token + position vectors → Transformer blocks: sequence states.
- Transformer blocks → Final normalization + head: contextual states.
- Final normalization + head → Vocabulary scores: projection.
| Object | Shape | Meaning |
|---|---|---|
| Embedding table E | U × d | U vocabulary entries, each with d coordinates. |
| Input IDs | N | N occurrences, including possible repetitions. |
| Sequence matrix X | N × d | Stacked lookup vectors; d is the model width. |
Repeated IDs select the same initial row. Position and surrounding tokens can then produce different hidden states: the intermediate vectors carried through the model. These coordinates need not have individually named human meanings. Broader questions about representation geometry belong in Embeddings and Representation Learning.
Parameters are fitted numerical values; activations are representations computed for the current input. Ordinary inference changes activations without updating parameters. Changing a prompt can therefore change behavior without teaching the checkpoint new weights. Training, fitted state, and inference develops this distinction.
Queries, keys, values and information mixing
Attention forms an input-dependent weighted mixture. A destination’s query scores candidate sources; each source’s key supplies matching features, and its value supplies contributed information. Several sources can contribute simultaneously. The output combines numerical vectors, not token IDs or copied text fragments. These roles are formalized in attention pooling.
Addressing and contributed content
Keys determine weights; values supply the mixture.
Read the diagram as text
- Query.
- Source keys.
- Source values.
- Compatibility scores.
- Normalized weights.
- Mixed output vector.
- Query → Compatibility scores: compare.
- Source keys → Compatibility scores: compare.
- Compatibility scores → Normalized weights: normalize.
- Normalized weights → Mixed output vector: coefficients.
- Source values → Mixed output vector: weighted sum.
| Quantity | Single-head self-attention shape |
|---|---|
| Queries Q; keys K | N × d_k each |
| Values V | N × d_v |
| Scores; weights A | N × N each |
| Output O | N × d_v |
sums coordinatewise products: destination i scores source j. Dividing by moderates score growth with key width.
Softmax exponentiates scores and divides by their row sum, producing nonnegative weights totaling one. Subtracting the row maximum before exponentiation preserves the result while reducing overflow risk. Normalization couples the source scores; attention cannot generally be rearranged into a simple product that bypasses that operation.
For a constructed example, scaled scores [0, 0] give weights [0.5, 0.5]. Values [2, 0] and [0, 4] therefore produce [1, 2]. The result is a mixed value vector, not a vocabulary distribution.
Visibility and attention masks
An attention mask restricts permitted destination–source pairs. A causal mask permits the current input position and earlier positions, excluding later ones. Including the diagonal is correct: the state at position i predicts the token at i+1. Bidirectional attention permits information from both directions.
Padding inserts artificial entries to batch unequal sequence lengths. Excluding padding sources and excluding future sources solve different problems. Teacher forcing, used during training, supplies recorded predecessors rather than generated choices; padding is not one of those meaningful predecessors.
Visibility
ExampleMasks restrict access.
Unrestricted
All sources visible.
Scroll sideways if the figure extends beyond the screen.
- 1. Allowed
Read coordinates and regions as data
X: -0.5–3.5 index; Y: -0.5–3.5 index, increasing down. Equal scale on both axes.
(0, 0); (1, 0); (2, 0); (3, 0); (0, 1); (1, 1); (2, 1); (3, 1); (0, 2); (1, 2); (2, 2); (3, 2); (0, 3); (1, 3); (2, 3); (3, 3)
Causal
Current/earlier sources visible.
Scroll sideways if the figure extends beyond the screen.
- 1. Allowed
Read coordinates and regions as data
X: -0.5–3.5 index; Y: -0.5–3.5 index, increasing down. Equal scale on both axes.
(0, 0); (0, 1); (1, 1); (0, 2); (1, 2); (2, 2); (0, 3); (1, 3); (2, 3); (3, 3)
Causal + padding
Source 3 padded and excluded; query 3 active.
Scroll sideways if the figure extends beyond the screen.
- 1. Allowed
Read coordinates and regions as data
X: -0.5–3.5 index; Y: -0.5–3.5 index, increasing down. Equal scale on both axes.
(0, 0); (0, 1); (1, 1); (0, 2); (1, 2); (2, 2); (0, 3); (1, 3); (2, 3)
| Restriction | Allowed information | Purpose |
|---|---|---|
| Causal visibility | Current and preceding inputs | Prevent future-target access. |
| Padding exclusion | Real source entries | Exclude artificial batching content. |
| Packed-sequence isolation | Sources from the same original sequence | Keep concatenated examples independent. |
In the SDPA convention, Boolean True means allowed. Forbidden scores become negative infinity before softmax. Every illustrated query has an allowed source. Excluding the example’s second source changes its output to [2, 0].
A normalized row can still leak future information if the wrong entries remain visible. Removing a future token’s loss does not remove it from attention. Causality here describes prediction-time access; it establishes neither factual correctness nor a causal effect in the statistical sense.
Order and positional information
Unrestricted self-attention without positional signals is permutation-equivariant: rearranging input rows rearranges the corresponding output rows. If [A, B, C] becomes [C, A, B], the outputs follow that rearrangement. This differs from invariance, where the output stays unchanged. A fixed causal mask breaks this unrestricted symmetry by changing which sources each row can access.
| Mechanism | Where position enters | Representation |
|---|---|---|
| Learned absolute positions | Added to token states | A learned vector indexed by sequence position. |
| Sinusoidal positions | Added to token states | Fixed sine/cosine signals at different frequencies. |
| Relative position bias | Added to attention scores | A learned scalar selected by source–destination offset; T5 groups offsets into buckets. |
| Rotary position embeddings, or RoPE | Applied to projected queries and keys | Position-dependent rotations of coordinate pairs make dot products depend on relative displacement. |
A common positional shift
ExampleRelative orientation survives a common rotation.
Before
Q points right; K points upward and right.
Scroll sideways if the figure extends beyond the screen.
- 1. Query Q
- 2. Key K
Read coordinates and regions as data
X: -1.3–1.3 dimensionless; Y: -1.3–1.3 dimensionless, increasing up. Equal scale on both axes.
(0, 0); (1, 0)
(0, 0); (0.6, 0.8)
Both positions shifted
Both arrows turn counterclockwise together, preserving their separation angle.
Scroll sideways if the figure extends beyond the screen.
- 1. Query Q
- 2. Key K
Read coordinates and regions as data
X: -1.3–1.3 dimensionless; Y: -1.3–1.3 dimensionless, increasing up. Equal scale on both axes.
(0, 0); (0, 1)
(0, 0); (-0.8, 0.6)
A relative offset is the difference between two position indices. T5’s bias assigns some offsets the same bucket, deliberately sharing their positional contribution. RoPE changes vector directions instead. Neither mechanism should be confused with deciding whether a source is visible.
Multiple heads and residual blocks
Each attention head learns separate projections. H mixtures concatenate to ; a learned output projection restores model width.
Multiple heads permit different mixtures, but do not guarantee indispensable specialists. Ablation studies removed many heads with little change on their tested tasks, while some encoder–decoder layers relied more strongly on multiple heads. Removing heads after training also differs from training a smaller-head model.
Pre-normalization residual paths
Normalization changes branch inputs, not the identity path.
Read the diagram as text
- Input x.
- LayerNorm.
- Multi-head attention.
- Add → u.
- LayerNorm.
- Position-wise FFN.
- Add → y.
- Input x → LayerNorm: branch.
- LayerNorm → Multi-head attention: normalized.
- Multi-head attention → Add → u: contribution.
- Input x → Add → u: identity.
- Add → u → LayerNorm: branch.
- LayerNorm → Position-wise FFN: normalized.
- Position-wise FFN → Add → y: contribution.
- Add → u → Add → y: identity.
The residual connection provides an identity path, letting the branch learn a correction rather than the complete mapping. This supports optimization; it does not guarantee later recovery of every input detail. Both paths still participate in computation.
| Operation | Role |
|---|---|
| LayerNorm | Centers and rescales coordinates within each token vector, then applies learned scale and bias. |
| RMSNorm | Rescales using the square root of the mean squared coordinate, with learned gains but no mean subtraction. |
| Position-wise FFN / MLP | Applies learned feature transformations and a nonlinearity separately at each position. |
The feed-forward network, also called a multilayer perceptron or MLP, commonly expands width and projects back: . Affine transformations—weighted combinations plus biases—surround a nonlinearity. Parameters are shared across positions. Attention mixes positions; this network transforms features within each position.
Pre-normalization normalizes branch inputs; post-normalization normalizes after residual addition. Neither arrangement defines every transformer. Stacked blocks repeat the operation pattern with their own learned parameters, progressively revising the sequence’s representations.
Encoders, decoders and cross-attention
An encoder builds representations of a supplied input. A causal decoder builds representations suitable for predicting a continuation. Conditioning means making predictions depend on supplied information. A decoder-only language model consumes its prompt directly; it does not require a separate source encoder.
| Structure | Information path | Output role |
|---|---|---|
| Encoder-only | Bidirectional input representations | An attached head can produce vectors or task scores. |
| Decoder-only | Causal attention over prompt and continuation | Next-token prediction without a separate source encoder. |
| Encoder–decoder | Encoded source conditions a causal target sequence | Source-conditioned generation. |
Two sequences, separate roles
Cross-attention updates destinations using source information.
Read the diagram as text
- Encoded source.
- Target states.
- Masked self-attention.
- Cross-attention.
- FFN.
- Target states → Masked self-attention: target data.
- Masked self-attention → Cross-attention: derive Q.
- Encoded source → Cross-attention: derive K, V.
- Cross-attention → FFN: updated targets.
Cross-attention uses destination queries and separate-source keys/values. L destinations and S sources yield weights and outputs; two targets can attend to five sources.
The input need not be text. A vision transformer projects image patches into token vectors and attaches a classification head. Its transformer produces representations; the input representation and output head determine the task. Architectural decoding is likewise separate from a tokenizer’s conversion of IDs back into text.
Vocabulary readout and autoregressive generation
A language-model head projects a final contextual vector into one logit, or unnormalized score, per vocabulary entry. Final normalization precedes this projection in the illustrated GPT-style architecture. The last input position supplies the distribution for continuing the prefix; the hidden vector itself is not a selected token.
Selected IDs extend the prefix
ExampleThe next distribution depends on the preceding selection.
Compute from [A].
Read the diagram as text
- Fixed model.
- Prefix [A].
- Distribution after [A].
- Selected ID B.
- Prefix [A, B].
- Distribution after [A, B].
- Selected ID C.
- Prefix [A, B, C].
- Fixed model → Distribution after [A]: parameters.
- Prefix [A] → Distribution after [A]: condition.
- Distribution after [A] → Selected ID B: select.
- Prefix [A] → Prefix [A, B]: retain.
- Selected ID B → Prefix [A, B]: append.
- Fixed model → Distribution after [A, B]: parameters.
- Prefix [A, B] → Distribution after [A, B]: condition.
- Distribution after [A, B] → Selected ID C: select.
- Prefix [A, B] → Prefix [A, B, C]: retain.
- Selected ID C → Prefix [A, B, C]: append.
- Predict. Compute from [A]. Active: Fixed model, Prefix [A], Distribution after [A]. New: Fixed model, Prefix [A], Distribution after [A].
- Extend. Select B and append it. Active: Fixed model, Prefix [A], Distribution after [A], Selected ID B, Prefix [A, B]. New: Selected ID B, Prefix [A, B].
- Predict again. The new prefix conditions another distribution. Active: Fixed model, Prefix [A], Distribution after [A], Selected ID B, Prefix [A, B], Distribution after [A, B]. New: Distribution after [A, B].
- Extend again. Select C; retain the earlier prefix. Active: Fixed model, Prefix [A], Distribution after [A], Selected ID B, Prefix [A, B], Distribution after [A, B], Selected ID C, Prefix [A, B, C]. New: Selected ID C, Prefix [A, B, C].
| Normalization | Axis | Result used for |
|---|---|---|
| Attention softmax | Visible source positions | Mixing value vectors. |
| Vocabulary softmax | Vocabulary entries | Selecting the next token. |
Autoregressive generation predicts from the available prefix, selects a token, appends its ID, and predicts again. Later predictions depend on earlier selections. The model’s parameters remain fixed; the sequence and its computed representations change. One forward pass and a complete response are therefore different units of work.
Greedy selection chooses a highest-scoring token; sampling permits alternatives according to a selection distribution. The choice changes subsequent prefixes. LLM Inference covers sampling controls; Decoding and text preservation explains the separate task of reconstructing text from IDs.
- Model-associated ending — An end-of-sequence token, or EOS, can signal termination when configured as a stopping token.
- External ending — A length limit, stop string or other stopping criterion can end generation. A length cutoff may return an incomplete answer; an output budget is an upper bound, not a completion guarantee.
Shifted targets and parallel sequence training
A training target states what should be predicted; loss measures prediction error, as explained in Supervision, baselines, and loss. For next-token training, each position’s target is the following recorded token. Cross-entropy penalizes assigning that target insufficient probability.
| Input position | Input ID | Visible prefix | Target ID |
|---|---|---|---|
| 0 | A | A | B |
| 1 | B | A B | C |
| 2 | C | A B C | D |
Known inputs, restricted dependencies
ExampleRecorded inputs can be available together without revealing targets.
Read the diagram as text
- Recorded A.
- Recorded B.
- Recorded C.
- Prediction targeting B.
- Prediction targeting C.
- Prediction targeting D.
- Recorded A → Prediction targeting B: visible.
- Recorded A → Prediction targeting C: visible.
- Recorded B → Prediction targeting C: visible.
- Recorded A → Prediction targeting D: visible.
- Recorded B → Prediction targeting D: visible.
- Recorded C → Prediction targeting D: visible.
Teacher forcing uses recorded predecessors as decoder inputs. The prediction for C receives recorded B even if the model’s prediction for B was wrong. Generation instead feeds back its own selections. The causal mask, rather than the data loader alone, prevents a training prediction from accessing its answer.
Known inputs let positions be processed together within a layer; successive layers still depend on preceding layers. Generation cannot ordinarily select all future inputs together because those inputs depend on earlier choices. Parallel position evaluation is compatible with causal visibility.
- Visibility controls information — Attention masking determines which inputs can influence a prediction.
- Loss eligibility controls supervision — Instruction tuning can keep a prompt visible while training only against response tokens. Omitting prompt losses does not hide the prompt.
- Learning changes shared transformations — Training adjusts embeddings, attention projections and other fitted components. Their outputs still depend on each input. Corpus choices and training schedules belong in Pretraining and Midtraining.
Connectivity, computational work and storage
A conceptual N × N score matrix need not be stored in full. FlashAttention preserves dense attention while reducing additional storage, retaining quadratic pairwise arithmetic. Floating-point results can differ slightly. Avoiding materialization changes execution; removing source connections changes the attention operation.
Local mixing, later global communication
ExampleRestricted layers can communicate through a later global layer.
Read the diagram as text
- Region A inputs.
- Region B inputs.
- Region A local states.
- Region B local states.
- Later global attention.
- Updated sequence states.
- Region A inputs → Region A local states: local mixing.
- Region B inputs → Region B local states: local mixing.
- Region A local states → Later global attention: region A data.
- Region B local states → Later global attention: region B data.
- Later global attention → Updated sequence states: global mixing.
| Design choice | What changes | What remains |
|---|---|---|
| Avoid full attention-matrix storage | Intermediate storage | Dense source connectivity and quadratic pairwise work. |
| Local attention windows | Direct source connectivity | Distant information needs other paths, such as later shifted windows. |
| More layers | Repeated representation transformations | Each layer still carries its own computation and parameters. |
| Longer sequences | Attention and non-attention allocations | MLPs and loss calculations can also create large buffers. |
Local attention limits nearby mixing; periodic global layers reconnect distant regions. ModernBERT illustrates this combination. Such a pattern can reduce local-layer work while preserving later communication, but a possible multi-layer path does not establish that the model will use it successfully.
Tokenwise projections and MLPs process each position, with work also depending on feature widths. Dense pair count captures only one component. In vision, doubling both image dimensions at fixed patch size yields four times as many patches and sixteen times as many pairs, without implying sixteen times the total latency.
- Reuse preserves earlier causal work — With unchanged prefix, model and compatible position/mask state, appended tokens cannot change earlier causal representations. A KV cache retains their derived keys and values. Processing a newly selected token computes its own Q, K and V; the selected ID is not itself a cached vector.
- Reuse does not remove history access — Ordinary full-context decoding still attends over retained history. Cache layout, prompt processing and serving measurements belong in LLM Inference.
- Checkpoint fidelity constrains substitutions — A replacement computation must match the behavior expected by the fitted checkpoint. A locally attractive numerical change can interact with other differences; reference agreement matters when reproducing a model.
Context access and demonstrated behavior
| Claim | What establishes it | Remaining limitation |
|---|---|---|
| The request fits | The configured model and runtime accept its sequence length. | Allocating more cache slots does not extend positional support. |
| The model encountered these positions during learning | Its training configuration and examples. | Training-length exposure differs from reliable extrapolation beyond that range. |
| The model uses distant information | Task performance at specified lengths, positions and difficulty. | Effective context depends on the task, scoring rule and acceptance threshold. |
A controlled evidence-position test moves the same answer-bearing passage while keeping the desired answer fixed. Vary distractors and length separately. Historical studies found position-sensitive performance in several tested models; this motivates measurement, not a universal beginning-or-end placement rule. Failure analysis and competing explanations covers how to distinguish possible causes.
Simple retrieval can succeed while aggregation or multi-step tracing deteriorates. RULER explicitly separates these task demands. A successful needle-in-a-haystack test—finding one requested item among distractors—therefore supports a narrower claim than reliable reasoning across the entire accepted context.
- Parameters — Fitted transformations stored in the checkpoint.
- Current representations — Activations computed from the present input. Context Engineering concerns what information enters that computation.
- Persistent records — Application history stored outside the invocation. A session log can supply selected slices later; persistence alone does not place every record in current context. Agent Memory develops that lifecycle.
An attention map shows one set of mixing coefficients, not the complete explanation of an answer. Value vectors determine what those coefficients combine. Different weight patterns can sometimes produce the same mixture because their differences cancel against the values. Other heads, residual paths and later transformations further separate one map from final behavior.
A high next-token probability does not establish factual support. If an incorrect token is selected, it joins the prefix and can influence later predictions. Fluent continuation and supported answers require different evidence.
Open questions
Separating positional design from training exposure remains difficult when extending usable context. Both affect long-input behavior, while task difficulty can hide regressions. Progress requires matched training conditions and tests spanning short inputs, distant evidence, distractors and multi-step use—not acceptance of longer sequences alone.
Determining necessary head diversity remains task-dependent. Redundant heads and non-unique attention mixtures complicate explanations of individual roles. Progress would identify interventions whose effects reproduce across prompts and tasks while distinguishing post-training pruning from training fewer heads initially.
Choosing restricted connectivity that preserves distant reasoning remains an architectural tradeoff. Shifted windows create indirect paths, but path existence does not establish useful information transfer. Progress would demonstrate matched-budget accuracy across local tasks and tasks requiring several distant pieces of evidence.















