The sequence computation
What a transformer computes
Interpreting a sequence requires more than identifying its individual elements. In a sentence, nearby descriptions can change what a verb implies. A model therefore needs a contextual representation: a numerical state that depends on an element and the information available at its position. Attention builds such states by combining information across positions with weights that depend on the input.
For text, the starting elements are tokens, sequence units identified by integers. A token need not be a whole word; Tokenization explains how text becomes these IDs. A transformer converts the IDs into vectors, repeatedly transforms those vectors, and passes the resulting states to an output component. A language model produces scores for possible next tokens. Other models use contextual states for classification or locating an answer inside a passage.
A forward pass applies the model's operations to supplied inputs. During ordinary inference, its fitted parameters stay fixed while the intermediate states change with the input. Changing a passage can therefore change a prediction without retraining. This distinction will recur throughout the chapter: parameters specify learned transformations; the current sequence supplies the information those transformations process.
The arrays and their parameters
A vector is an ordered array of numerical coordinates. An embedding table stores one learned vector per vocabulary entry. If the vocabulary contains entries and each vector has coordinates, the table has shape . A token ID selects a row; the magnitude of the ID has no feature meaning. Stacking the selected vectors for sequence positions produces a matrix of shape .
| Sequence position | Token ID | Selected vector |
|---|---|---|
| 0 | 2 | [1, −1] |
| 1 | 7 | [0, 2] |
| 2 | 2 | [1, −1] |
Repeated IDs initially select identical rows. Their later states can differ once position and context enter. The table contains parameters, fitted numbers shared across inputs; the selected and transformed arrays are activations, intermediate values computed for this input. Their learned coordinates are not manually assigned labels such as tense or importance. Parameters and modeling assumptions explains the shared-parameter distinction; Vectors and coordinate spaces develops representation geometry.
A linear projection forms new coordinates from weighted sums of existing ones. A dot product multiplies corresponding coordinates and sums them: [1, −1] · [2, 3] = 2 − 3 = −1. In , an input and weight matrix yield an output; adds a learned offset. The same transformation applies separately to every row. It changes features without exchanging information between positions. Here weights use the mathematical convention; libraries may store them transposed.
Why attention emerged
Early neural translation systems made the information-access problem concrete. An encoder processes a source sequence; a decoder produces a target sequence. In a recurrent network, a numerical state passes from one position to the next. A decoder could receive a fixed-dimensional summary of the source, but that made the summary responsible for preserving everything subsequent predictions might need.
From source summaries to pretrained contextual states
September 2014Sequence to Sequence LearningTwo recurrent networks encode a source into a fixed-dimensional summary and generate a target from it.
Contributors: Ilya Sutskever, Oriol Vinyals and Quoc Le, Google.
What changed: Their five-model ensemble exceeded the reported non-neural English–French translation baseline; reversing source order helped. Fixed-summary models achieved useful results, including on long sentences. This work and learned alignment developed concurrently.
September 2014 preprintBahdanau attentionEach target prediction forms its own weighted summary of contextual source states.
Contributors: Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio.
What changed: Learned alignment supplied adaptive source access within recurrent translation. The September 2014 preprint preceded ICLR 2015 publication; the two 2014 approaches developed concurrently.
June 2017TransformerReplaced recurrence with attention, parallelizing supplied sequence positions.
Contributors: Ashish Vaswani and colleagues.
What changed: Demonstrated strong translation results.
June 2018GPTGenerative pretraining makes a causal Transformer a reusable starting point for language-understanding tasks.
Contributors: Alec Radford and colleagues, OpenAI.
What changed: The reported improvements followed task-specific training on labeled examples.
October 2018 preprintBERTBidirectional pretraining builds token states from both left and right context.
Contributors: Jacob Devlin and colleagues, Google.
What changed: Bidirectional Encoder Representations from Transformers introduced reusable contextual states. Conference publication followed in 2019.
The useful thread is adaptive information access. Attention first complemented recurrence, then became the central interaction mechanism of a different architecture. Its matching rule, permitted sources and output use remain separate design choices.
Attention and sequence structure
Supplying sequence order
Array positions are visible to your program, but they do not automatically become features in its numerical transformations. With unrestricted attention and no positional signals, rearranging the input rows rearranges their output representations correspondingly. This is permutation equivariance. It does not mean the output array remains unchanged. The statement also does not cover arbitrarily rearranging tokens while holding a causal visibility pattern fixed.
One solution adds a position vector to each token vector. An absolute position is an index within the sequence. GPT-2 uses a learned position table distinct from its token table: position selects a row from one, token identity selects a row from the other, and their coordinates are added.
| Input order | State at position 0 | State at position 1 |
|---|---|---|
| A, B | E[A] + P[0] | E[B] + P[1] |
| B, A | E[B] + P[0] | E[A] + P[1] |
Position vectors can also be fixed: the original Transformer added sine/cosine patterns at different frequencies. GPT-2 instead learned them. Both supply position; neither addition determines permitted attention connections.
Matching and transmitted content
Attention separates deciding where to read from deciding what to transmit. A query scores candidate information. A key is the representation compared with that query. A value supplies content to the resulting mixture. Keys and values stay paired by source position, but serve different roles.
Self-attention projects the same sequence states separately into Q, K and V. Projection parameters are shared across inputs; these activations depend on the input. Omitting optional biases:
Different projections make permitted query–key comparisons directed: q_i · k_j need not equal q_j · k_i. The names denote numerical roles, not questions or database identifiers.
Matching functions were already a design choice in recurrent attention. Effective Approaches to Attention-based Neural Machine Translation, by Minh-Thang Luong, Hieu Pham and Christopher Manning at Stanford in September 2015, compared dot-product and learned compatibility functions, alongside global and local source access. Its improvements also involved feeding attention-informed states into subsequent decoding. Transformer attention adopts a particular matching-and-aggregation construction from this broader design space.
Computing the attention update
Each query–key dot product produces a compatibility score. Softmax exponentiates a row of scores and divides each result by their sum, yielding positive weights totaling one. Those weights multiply the corresponding value vectors, which are summed into one output vector per query. Attention therefore produces a mixture, rather than selecting only the highest-scoring source.
Dividing scores by , the square root of query/key width, counters variance growth under independent, zero-mean, unit-variance coordinates, avoiding sharply concentrated softmax weights with little sensitivity during learning.
| Array | Shape |
|---|---|
| Queries Q; keys K | L × d_k; s × d_k |
| Scores S; weights A | L × s |
| Values V; output O | s × d_v; L × d_v |
For a numerical example, take scaled scores [0, 0] and values [2, 0] and [0, 4]. Exponentiation gives [1, 1]; normalization gives [0.5, 0.5]. The output is 0.5[2, 0] + 0.5[0, 4] = [1, 2]. Increasing one score redistributes weight across the row. The weights allocate content; they do not express confidence that the content is true.
Scores allocate weight; values supply content
Change a scaled score to redistribute attention. Change a value coordinate to alter the content being mixed.
Restricting information access
An attention mask specifies permitted query–source pairs. In causal self-attention, a position may read itself and earlier positions, but cannot read later ones. Its state can then predict the next token without seeing that target. A small learned attention weight is not a prohibition: the architecture must exclude the forbidden connection.
Padding adds artificial fillers when batching unequal sequence lengths. A padding mask excludes those source positions; a causal mask excludes future connections. Combine the exclusions when both apply. Source masking does not itself discard padded query outputs or their losses. Boolean conventions also differ: True means allowed in PyTorch's scaled-dot-product attention interface, but excluded in MultiheadAttention's Boolean masks.
Causal visibility with a padded source
ExampleThe current position remains visible, while future inputs and padding are excluded for different reasons.
Allowed pairs include the diagonal
Green regions are allowed; orange regions are future sources; purple is padding. Text labels distinguish every region.
- 1. Allowed at query 0
- 2. Allowed at query 1
- 3. Allowed at query 2
- 4. Future at query 0
- 5. Future at query 1
- 6. Excluded padding
Read coordinates and regions as data
X: -0.75–3.75 position; Y: -0.75–2.75 position, increasing down. Equal scale on both axes.
(-0.45, -0.45); (0.45, -0.45); (0.45, 0.45); (-0.45, 0.45)
(-0.45, 0.55); (1.45, 0.55); (1.45, 1.45); (-0.45, 1.45)
(-0.45, 1.55); (2.45, 1.55); (2.45, 2.45); (-0.45, 2.45)
(0.55, -0.45); (2.45, -0.45); (2.45, 0.45); (0.55, 0.45)
(1.55, 0.55); (2.45, 0.55); (2.45, 1.45); (1.55, 1.45)
(2.55, -0.45); (3.45, -0.45); (3.45, 2.45); (2.55, 2.45)
Allowed: (0, 0)
Allowed: (0.5, 1)
Allowed: (1, 2)
Future: (1.5, 0)
Future: (2, 1)
Padding: (3, 1)
Keep three decisions separate: position describes placement, attention masking controls access, and loss selection determines which predictions receive a training penalty. Removing a prediction from the loss does not stop another position from reading its input. Separate visibility from scoring develops this distinction.
Relative position in matching
Position can affect compatibility directly. Relative position describes the displacement between query and source indices. In T5, a learned scalar bias selected by that displacement is added to the attention score before softmax. Offsets are grouped into buckets, so multiple distances can share a bias. This differs from adding a vector to the initial token state: the positional term modifies a relationship between two positions.
Rotary Position Embedding, or RoPE, rotates pairs of projected query/key coordinates. Jianlin Su and colleagues introduced it in RoFormer in April 2021. For column vectors q and k, let R_m rotate a coordinate pair according to position m:
A shared position shift preserves matching
ExampleBoth vectors rotate while their angle and dot product remain unchanged.
m=0, n=1
Relative displacement: 1.
- 1. Rotated query
- 2. Rotated key
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)
Q: (1.05, -0.15)
K: (0.65, 1)
m=1, n=2
Same relative displacement.
- 1. Rotated query
- 2. Rotated key
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)
Q: (0.15, 1.1)
K: (-1, 0.75)
These mechanisms enter at different locations: absolute vectors alter initial states, scalar biases alter scores, and RoPE alters the vectors being compared. They still feed a weighted-value computation. Numerical precision matters in that path: Daniel Han describes a reduced-precision implementation in which distinct large position indices collapsed to the same value, losing positional distinctions. A mathematically suitable representation still needs faithful numerical execution.
Building contextual states
Several mixtures in one layer
Each attention head separately projects Q/K/V and computes weights. Concatenating h mixtures of shape gives ; learned projection restores width d. Conventionally, .
The same sequence positions participate in every head. What varies is their projected representation and resulting allocation of attention. Heads therefore offer multiple learned interaction patterns within one layer; they are not separate complete language models. In Ishan Anand's spreadsheet demonstration, one head shows an interpretable pronoun–antecedent pattern, while others lack such an obvious reading. A head receives no guaranteed linguistic job title.
The study Are Sixteen Heads Really Better than One? removed heads from trained translation and BERT models. Many removals had little effect, while some encoder–decoder attention layers relied substantially on multiple heads. Head count alone therefore does not establish how many indispensable functions a model learned. Pruning a trained model also differs from training a smaller model from the outset.
The complete block
Attention supplies an update, but a block also needs to preserve and transform the state receiving it. A residual connection adds a branch's result to its input: . Matching dimensions make this elementwise addition possible. The identity path lets the branch learn a correction to an existing representation. It neither guarantees a small correction nor skips execution of the branch. Deep Residual Learning established this construction in deep image networks.
Layer normalization, or LayerNorm, controls feature scale separately at each position: it subtracts the vector's coordinate mean, divides by its standard deviation with a numerical safeguard, then applies learned scale and bias. Pre-normalization places this operation before each transformed branch; post-normalization places it after residual addition. One pre-normalization block is:
A feed-forward network, or FFN, transforms each position independently using shared parameters. A common version, also called a multilayer perceptron or MLP, applies two affine transformations separated by a nonlinear activation. The intervening nonlinearity prevents the pair from collapsing into one affine transformation. In nanoGPT, feature width expands from d to 4d and returns to d. Attention mixes positions; this network processes features at each position.
Two updates to the carried state
Normalization belongs to each transformed branch; residual additions preserve a direct path.
Read the diagram as text
- Input X: n × d.
- LayerNorm. Attention branch
- Multi-head attention. Across positions
- Add → U: n × d.
- LayerNorm. FFN branch
- Feed-forward network. Within each position
- Add → Y: n × d.
- Input X: n × d → LayerNorm: Branch input.
- LayerNorm → Multi-head attention: Normalized states.
- Multi-head attention → Add → U: n × d: Attention update.
- Input X: n × d → Add → U: n × d: Identity path.
- Add → U: n × d → LayerNorm: Branch input.
- LayerNorm → Feed-forward network: Normalized states.
- Feed-forward network → Add → Y: n × d: Feature update.
- Add → U: n × d → Add → Y: n × d: Identity path.
Normalization variants change the branch computation. Root mean square normalization, or RMSNorm, divides by a scale derived from the average squared coordinate and applies learned gains; unlike LayerNorm, it does not subtract the mean. LLaMA, documented by Hugo Touvron and colleagues at Meta AI in February 2023, combines input normalization using RMSNorm with RoPE. This is a concrete block variant, not evidence that either choice alone explains its performance.
When reading code, locate both addition points and inspect what each branch receives. Training an LLM from Scratch, Locally makes the central change explicit: replacing X with an attention result differs from adding that result to X.
Context across layers
Stacking blocks composes learned transformations. Later queries, keys and values come from states that earlier blocks have already contextualized. Blocks repeat an operation pattern, but normally have distinct parameters. GPT-2 Small, for example, uses twelve separately parameterized blocks; depth does not mean repeatedly applying one shared set of weights.
Consider a permitted dependency: position 0 contributes to position 1 in one layer, then position 1 contributes to position 2 in the next. The second interaction can transmit information originating at position 0. Under a causal mask, each edge travels from an equal or earlier source position, so composing edges cannot create access to a future token. Feature transformations and residual additions process what those interactions deliver.
The accumulated per-position state is often called the residual stream. For the same token at the same position in two different prefixes, its initial lookup vector can remain identical while subsequent states differ. This input sensitivity under fixed parameters enables prompting and in-context learning. A token state is also distinct from a deliberately constructed whole-item embedding.
Depth and generation count are separate dimensions. Passing through another block refines representations within one forward pass; it does not append another token. An inspection technique called a logit lens applies the model's output mapping to intermediate states, turning them into scores for candidate vocabulary tokens. This reveals how candidate rankings change across layers, but does not establish a universal sequence of linguistic stages or a complete causal explanation.
Three architecture families
| Family | Information access | Typical readout |
|---|---|---|
| Encoder-only | Supplied context on both sides | Classification or passage boundaries |
| Decoder-only | Current position and preceding prefix | Next-token scores |
| Encoder–decoder | Encoded source plus causal target prefix | Conditional target generation |
Cross-attention matches target queries to source keys/values: target-by-source weights. The original decoder orders masked self-attention → cross-attention → FFN, each followed by residual addition and LayerNorm.
A decoder-only model such as early GPT removes the need for a separate source encoder and cross-attention path. Its causal blocks build representations for predicting successive tokens. The original GPT work also used these representations for supervised downstream tasks, showing that a causal architecture was useful beyond producing free-running continuations.
BERT builds states from both left and right context. Its added classification token, CLS, supplies a final state for classification; another output head predicts answer boundaries in a passage. Pretraining predicts selected corrupted tokens, so this visibility need not expose unchanged answers. Compared with a left-context-only model, BERT improved the reported development-task results, but the experiment changed both visibility and objective. Changing a trained model's mask alone would not reproduce it.
Architecture identifies the information path, not every interface convention. Models sharing a family can require different chat templates, normalization operations and positional handling. A reusable runtime must preserve the computation expected by each checkpoint.
Prediction, training and generation
Reading out vocabulary scores
An output head maps contextual states to task predictions. For next-token generation, the language-model head reads the state at the last input position, after the final block and normalization, and projects it to one score per vocabulary entry. These unnormalized scores are logits. The state supplies features for this scoring operation; choosing a token from the scores is a separate step.
| Location | Normalized axis | Meaning |
|---|---|---|
| Attention | Permitted source positions | Coefficients for a value mixture |
| Language head | Vocabulary entries | Probabilities for the next token |
Some models tie the output weights to the input embedding table. In GPT-2's JavaScript walkthrough, the final state is dotted with each embedding row. This is often called unembedding, but it does not invert the preceding contextual transformations. The demonstration selects the largest logit; softmax would preserve that ranking.
These probabilities describe possible next tokens under the model. They do not certify that a statement assembled from those tokens is factually supported.
Predicting recorded successors
During training, a recorded sequence supplies reference predecessors and correct successors. Teacher forcing means conditioning a prediction on those recorded predecessors rather than on the model's earlier sampled choices. A loss penalizes predictions against their targets. The model can calculate many such predictions together because their reference inputs are already known.
| Position | Input | Permitted prefix | Target |
|---|---|---|---|
| 0 | A | A | B |
| 1 | B | A, B | C |
| 2 | C | A, B, C | D |
B is both position 0's target and position 1's input. That is safe because position 0 cannot read position 1, directly or through later layers. Target shifting establishes which answer belongs to each prediction; causal masking separately enforces the information boundary. Omitting either can produce the wrong training problem.
Positions can be processed together within a layer, while the next layer still depends on the preceding layer's results. Loss computation and parameter updates are subsequent operations. A token omitted from loss can still supply context—for example, instruction tuning can score response tokens while retaining the prompt as input. Build targets from text explains objective construction beyond this alignment.
Producing an unknown continuation
Autoregressive generation repeatedly predicts from an existing prefix, selects a token, and appends it. Greedy selection chooses a maximum-probability token; sampling draws according to a selection distribution. The chosen token becomes part of the next input, so later predictions depend on earlier selections.
For a symbolic example, a model receives [A, B] and a selection yields C. The next prediction receives [A, B, C]; suppose its selection yields D. The second input could not be assembled before C was chosen. Training instead already has the reference C. Both processes use the same kind of forward computation, but only training performs a parameter update.
Generation ends when a stopping condition is met, such as an end-of-sequence token, a configured stop string or an output-length limit. A length cutoff can interrupt an unfinished answer; stopping does not certify completeness or correctness. Selection and stopping covers decoding controls, while Reconstructing generated text explains converting IDs back into text.
A key–value cache retains per-layer K and V activations. Under causal attention, appending tokens cannot change earlier states, so their projections can be reused when the prefix, parameters and positional treatment remain compatible. Processing the newly appended token computes its Q/K/V, adds its K/V to the cache, and uses its query to read retained history. Caching avoids recomputing earlier states; ordinary full-history attention still does work over the retained sources. See What the KV cache retains.
Architectural reach and limits
Reach, work and storage
Dense attention compares every query with every permitted source. For N positions, unrestricted attention has N² pairs; diagonal-inclusive causal attention has N(N+1)/2. Both grow quadratically. At fixed feature widths, projections and per-position feed-forward work instead grow linearly with position count. These are operation counts, not predictions of complete-model latency.
| Positions | Unrestricted | Causal |
|---|---|---|
| 4 | 16 | 10 |
| 8 | 64 | 36 |
Longformer combines local windows, restricting reads to neighbors, with global positions that read and are readable everywhere. Layers expand the receptive field—inputs influencing a state. Fixed window width and global-position count give linear interaction growth, without reproducing dense attention. This bidirectional pattern needs modification for causal decoding.
FlashAttention preserves dense attention while avoiding storage of the complete score matrix. Its exact algorithm retains quadratic arithmetic, with linear additional memory at fixed head width; floating-point results can differ. Restricting connections and changing storage are therefore different interventions.
If a fixed checkpoint must preserve dense outputs and arithmetic is affordable, removing connections changes the computation you intended to preserve. An implementation that avoids large intermediates addresses the storage problem directly. Online state and tiled attention explains that mechanism. Execution limits and Road to 5 Million Tokens connect sequence growth to practical bottlenecks.
When longer context helps
A context window describes a supported sequence allowance. Counting complete requests explains what consumes it. Allocating additional cache slots does not extend a model's positional support. Conversely, a windowed layer can retain only recent states while processing a longer overall sequence. Storage capacity and sequence support answer different questions.
Length extrapolation evaluates beyond training lengths without further adaptation. Attention with Linear Biases, or ALiBi, adds a distance penalty with a fixed slope per head before softmax. Its controlled WikiText-103 experiments showed stronger extrapolation than the compared positional methods. The measure was perplexity—next-token predictive fit—not arbitrary answer accuracy. A position formula being computable at an unseen index does not establish reliable use there.
Position Interpolation instead rescales positions into a pretrained RoPE model's original range and then fine-tunes it. Its historical LLaMA experiments extended a 2,048-token window to as much as 32,768, evaluating language modeling, retrieval and summarization. This was adaptation, not unchanged-checkpoint extrapolation; some original-window benchmarks degraded. Extending the accepted range and retaining earlier capabilities both need assessment.
Even within an accepted window, available evidence can be used unevenly. Lost in the Middle moved relevant information within multi-document question-answering and key-value retrieval inputs. Several tested models performed better with evidence near the beginning or end than in the middle, with results depending on model and task. The controlled variable was evidence placement; this was not proof of a universal position curve or of literal deletion of middle tokens.
RULER extends single-item retrieval tests to variable-chain tracing, aggregation and question answering with distractors. In its evaluated models, success at simple retrieval could coexist with deterioration on harder long-context tasks. Effective context length therefore needs a task, scoring rule and performance threshold. Test the operations your application requires, with workload coverage and input arrangement treated explicitly.
Interpreting attention patterns
An attention map displays mixing coefficients for one input, head and layer. Contribution also depends on the values and output projection. For a scalar example of transformed contributions, weights [0.9, 0.1] multiplying values [0.01, 10] yield contributions [0.009, 1]. The smaller weight contributes more. Attention is Not Only a Weight found analogous distinctions in BERT: some heavily attended special tokens and punctuation had comparatively small transformed-vector contributions. Neither contribution size nor coefficient size alone establishes the final prediction's cause.
Attention is not Explanation, by Sarthak Jain and Byron Wallace in 2019, challenged direct interpretation of attention weights. In recurrent-model experiments, weights aligned inconsistently with gradient or token-removal measures, and substantially different attention distributions could preserve nearly identical predictions. These results concern the studied models and tests; they do not directly measure modern Transformer stacks.
Attention is not not Explanation, Sarah Wiegreffe and Yuval Pinter's 2019 response, examined uniform baselines, variation across initializations and transferred attention distributions. Their recurrent-model results supported testing whether an interpretation is useful in a particular setting rather than accepting a universal verdict. The disagreement helps distinguish a visible pattern from a carefully specified explanation claim.
An ablation removes or disables a component and measures the resulting behavior. Head-removal experiments test dependence under that intervention and on those inputs. They do not assign an immutable purpose to the head.
For implementation diagnosis, controlled dependencies can be more decisive than a heatmap. With identical parameters, earlier tokens and positions, changing only a future token should not change an earlier causal prediction beyond numerical tolerance when randomness is disabled. An observed change justifies investigating an unintended information path. Comparing intermediate outputs layer by layer can locate where implementations first diverge; changing the sampling rule or which targets receive loss does not repair that forward-pass dependency.
Open questions
Reliable length transfer remains difficult because positional adaptation and task competence can change separately. Progress would preserve short-input capabilities while improving retrieval and multi-step use of longer inputs under controlled comparisons.
Which sparse connections preserve necessary dependencies across workloads? Pair counts alone cannot establish usefulness.
Faithful explanations must connect intermediate mixtures to downstream behavior despite interacting components. Progress would produce interpretations that predict controlled intervention outcomes on new inputs, with explicit limits on their scope.

















