Contents
  1. The sequence computation
    1. What a transformer computes
    2. The arrays and their parameters
    3. Why attention emerged
  2. Attention and sequence structure
    1. Supplying sequence order
    2. Matching and transmitted content
    3. Computing the attention update
    4. Restricting information access
    5. Relative position in matching
  3. Building contextual states
    1. Several mixtures in one layer
    2. The complete block
    3. Context across layers
    4. Three architecture families
  4. Prediction, training and generation
    1. Reading out vocabulary scores
    2. Predicting recorded successors
    3. Producing an unknown continuation
  5. Architectural reach and limits
    1. Reach, work and storage
    2. When longer context helps
    3. Interpreting attention patterns
  6. Check understanding
  7. Open questions
  8. Selected talks
  9. References
  10. Talk library
← All topics

Transformers and Attention

A transformer is a model architecture that builds a numerical state for each element of a sequence using information from other elements. These contextual states support tasks such as predicting the next token or locating an answer in a passage. Following how information moves between positions explains why changing the input can change a prediction, and why supplying information does not guarantee that the model uses it correctly.

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 vv entries and each vector has dd coordinates, the table EE has shape v×dv\times d. A token ID selects a row; the magnitude of the ID has no feature meaning. Stacking the selected vectors for nn sequence positions produces a matrix XX of shape n×dn\times d.

For a small example, let the selected rows be E[2] = [1, −1] and E[7] = [0, 2]. The input IDs [2, 7, 2] produce:
Sequence positionToken IDSelected vector
02[1, −1]
17[0, 2]
22[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 Y=XW+bY=XW+b, an n×dn\times d input and d×rd\times r weight matrix yield an n×rn\times r output; bb 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 XWXW 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

  1. September 2014Sequence to Sequence LearningTwo recurrent networks encode a source into a fixed-dimensional summary and generate a target from it.Sources & context

    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.

  2. September 2014 preprintBahdanau attentionEach target prediction forms its own weighted summary of contextual source states.Sources & context

    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.

  3. June 2017TransformerReplaced recurrence with attention, parallelizing supplied sequence positions.Sources & context

    Contributors: Ashish Vaswani and colleagues.

    What changed: Demonstrated strong translation results.

  4. June 2018GPTGenerative pretraining makes a causal Transformer a reusable starting point for language-understanding tasks.Sources & context

    Contributors: Alec Radford and colleagues, OpenAI.

    What changed: The reported improvements followed task-specific training on labeled examples.

  5. October 2018 preprintBERTBidirectional pretraining builds token states from both left and right context.Sources & context

    Contributors: Jacob Devlin and colleagues, Google.

    What changed: Bidirectional Encoder Representations from Transformers introduced reusable contextual states. Conference publication followed in 2019.

Follow the concurrent recurrent approaches of 2014 through attention-centered sequence processing and reusable pretrained representations. Spacing is not to scale.

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.

For symbolic tokens A and B, exchanging their positions changes the pairings:
Input orderState at position 0State at position 1
A, BE[A] + P[0]E[B] + P[1]
B, AE[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:

Q=XWQ,K=XWK,V=XWV.Q=XW_Q,\qquad K=XW_K,\qquad V=XW_V.

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 dk\sqrt{d_k}, 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.

S=QKdk,Aij=eSijr=1seSir,O=AV.S=\frac{QK^\top}{\sqrt{d_k}},\qquad A_{ij}=\frac{e^{S_{ij}}}{\sum_{r=1}^{s}e^{S_{ir}}},\qquad O=AV. Here KK^\top exchanges K's rows and columns. For each query i, softmax normalizes its scores across the s source positions; A_ij is the weight assigned to source j.
Ignoring batch and head axes, let L be the query count, s the source count and d_v the number of coordinates in each value:
ArrayShape
Queries Q; keys KL × d_k; s × d_k
Scores S; weights AL × s
Values V; output Os × 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.

Source 1
Weight 0.5
Source 2
Weight 0.5
Weighted output: [1, 2]
These example scaled scores give equal weights and output [1, 2]. Change a score to redistribute weight, or change a value to alter the output without changing weights. The controls change calculation inputs, not learned parameters.

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.

A=softmaxsources(S+M),Mij={0allowed,excluded.A=\operatorname{softmax}_{\mathrm{sources}}(S+M),\qquad M_{ij}=\begin{cases}0&\text{allowed},\\-\infty&\text{excluded}.\end{cases} Exclusion precedes normalization. In the two-source example, excluding the second source changes weights to [1, 0] and the output to [2, 0]. At least one source must remain allowed per computed row.

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

Example

The 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.

-0.750.3751.52.6253.75-0.750.12511.8752.75Source position (position)Query position (position)Allowed at query 0Allowed at query 1Allowed at query 2Future at query 0Future at query 1Excluded paddingAllowedAllowedAllowedFutureFuturePadding
  • 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.753.75 position; Y: -0.752.75 position, increasing down. Equal scale on both axes.

Allowed at query 0 (polygon)

(-0.45, -0.45); (0.45, -0.45); (0.45, 0.45); (-0.45, 0.45)

Allowed at query 1 (polygon)

(-0.45, 0.55); (1.45, 0.55); (1.45, 1.45); (-0.45, 1.45)

Allowed at query 2 (polygon)

(-0.45, 1.55); (2.45, 1.55); (2.45, 2.45); (-0.45, 2.45)

Future at query 0 (polygon)

(0.55, -0.45); (2.45, -0.45); (2.45, 0.45); (0.55, 0.45)

Future at query 1 (polygon)

(1.55, 0.55); (2.45, 0.55); (2.45, 1.45); (1.55, 1.45)

Excluded padding (polygon)

(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)

Positions 0–2 contain A, B and C; source 3 is padding. Query 1 predicts C but cannot read source 2. Only real query rows are shown.

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:

(Rmq)(Rnk)=qRnmk.(R_mq)^\top(R_nk)=q^\top R_{n-m}k. The positional term depends on displacement. Different coordinate pairs use different rotation frequencies.

A shared position shift preserves matching

Example

Both vectors rotate while their angle and dot product remain unchanged.

m=0, n=1

Relative displacement: 1.

-1.3-0.6500.651.3-1.3-0.6500.651.3First coordinate (dimensionless)Second coordinate (dimensionless)Rotated queryRotated keyQK
  • 1. Rotated query
  • 2. Rotated key
Read coordinates and regions as data

X: -1.31.3 dimensionless; Y: -1.31.3 dimensionless, increasing up. Equal scale on both axes.

Rotated query (polyline)

(0, 0); (1, 0)

Rotated key (polyline)

(0, 0); (0.6, 0.8)

Q: (1.05, -0.15)

K: (0.65, 1)

m=1, n=2

Same relative displacement.

-1.3-0.6500.651.3-1.3-0.6500.651.3First coordinate (dimensionless)Second coordinate (dimensionless)Rotated queryRotated keyQK
  • 1. Rotated query
  • 2. Rotated key
Read coordinates and regions as data

X: -1.31.3 dimensionless; Y: -1.31.3 dimensionless, increasing up. Equal scale on both axes.

Rotated query (polyline)

(0, 0); (0, 1)

Rotated key (polyline)

(0, 0); (-0.8, 0.6)

Q: (0.15, 1.1)

K: (-1, 0.75)

One illustrative coordinate pair: q=(1,0), k=(0.8,−0.6), rotation 90° per position. Shifting m,n together preserves dot product 0.6.

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 n×dvn\times d_v gives n×(hdv)n\times(hd_v); learned projection restores width d. Conventionally, dv=d/hd_v=d/h.

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: y=x+F(x)y=x+F(x). 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:

U=X+Attention(LayerNorm(X)),Y=U+FFN(LayerNorm(U)).U=X+\operatorname{Attention}(\operatorname{LayerNorm}(X)),\qquad Y=U+\operatorname{FFN}(\operatorname{LayerNorm}(U)). X, U and Y retain shape n × d. The residual paths carry the accumulated state around the normalized branches.

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.

A pre-normalization block. Attention exchanges information across positions; LayerNorm and FFN operate per position. Both additions preserve n × d.
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 × dLayerNorm: Branch input.
  • LayerNormMulti-head attention: Normalized states.
  • Multi-head attentionAdd → U: n × d: Attention update.
  • Input X: n × dAdd → U: n × d: Identity path.
  • Add → U: n × dLayerNorm: Branch input.
  • LayerNormFeed-forward network: Normalized states.
  • Feed-forward networkAdd → Y: n × d: Feature update.
  • Add → U: n × dAdd → 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

The same components support different information paths and outputs:
FamilyInformation accessTypical readout
Encoder-onlySupplied context on both sidesClassification or passage boundaries
Decoder-onlyCurrent position and preceding prefixNext-token scores
Encoder–decoderEncoded source plus causal target prefixConditional 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.

z=hWout+b,pj=ezjr=1vezr.z=hW_{\mathrm{out}}+b,\qquad p_j=\frac{e^{z_j}}{\sum_{r=1}^{v}e^{z_r}}. Here h is a final normalized width-d row, W_out has shape d × v, z contains vocabulary logits, and p_j is the next-token probability for vocabulary entry j.
Softmax appears twice, with different meanings:
LocationNormalized axisMeaning
AttentionPermitted source positionsCoefficients for a value mixture
Language headVocabulary entriesProbabilities 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.

For the symbolic recorded sequence [A, B, C, D], inputs [A, B, C] align with targets [B, C, D]:
PositionInputPermitted prefixTarget
0AAB
1BA, BC
2CA, B, CD

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.

At each layer, processing C adds its key and value to retained rows A and B. Its query still attends over the available history. Reuse requires compatible prefix, positions and parameters.

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.

Exact pair counts for two example lengths:
PositionsUnrestrictedCausal
41610
86436

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.

Tiled dense attention retains every permitted pair while changing intermediate storage, with equivalent mathematics up to floating-point differences. Sparse attention changes the connections themselves. The bidirectional grid is a small schematic; running normalization combines all tiles.

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

  1. 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.

  2. Which sparse connections preserve necessary dependencies across workloads? Pair counts alone cannot establish usefulness.

  3. 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.

Follow the curated reading path through the speakers and demonstrations behind this entry.

81 min

AI Engineer Europe 2026 · 2026

Training an LLM from Scratch, Locally

Angelos Perivolaropoulos

Cited in this entry

Connect the block structure to implementation, especially residual addition, normalization and the distinction between model outputs and generation choices.

Watch talk

Explore more talks

The rest of the library, beyond the curated path. Cited talks support this entry; reviewed transcripts were processed in full. Metadata candidates have not been reviewed as sources or verified as topic members.

14 matching talks

Every catalogued talk on this subject: Architecture

TalkSpeakerEventYear
Ishan AnandAI Engineer World's Fair 20242024
Isaac RobinsonAI Engineer Europe 20262026
Daniel HanAI Engineer World's Fair 20242024
Phoebe KlettAI Engineer World's Fair 20242024
Diego CarpenteroAI Engineer Europe 20262026
Filip MakraduliAI Engineer World's Fair 20252025
Mark MoyouAI Engineer World's Fair 20242024
Rémi LoufAI Engineer World's Fair 20242024
Devendra Chaplot, Devendra Singh ChaplotAI Engineer World's Fair 20242024
Nupur SharmaAI Engineer Europe 20262026
Leo PekelisAI Engineer World's Fair 20242024
Gagan Bhat, Isabella Kai HeAI Engineer World's Fair 20262026
Kyle KranenAI Engineer World's Fair 20252025
Skills are the New SDKs

Transcript reviewed

Elvin AghammadzadaAI Engineer World's Fair 20262026

References

Coverage and source review
Processed transcripts
18 processed in full · 4 in the curated path
Automated source review
Passed
Metadata candidates
0 unreviewed; not verified topic membership
Corpus version
1bd8e407b26a07b33815594e1b2db5f41827119a2b3cb6fbf240f9fc571fc767

Automated review checks source support; it is not publication approval.

A synthesis of selected conference talks and technical references. Citations link to the source material; they do not imply that every talk on this subject is included.

  1. Spreadsheets-are-all-you-need: Decoding the Decoder LLM without de code

    The demonstrated attention head distributes attention over available earlier positions, with future positions excluded; some patterns are interpretable, but not every head has an obvious linguistic explanation.

  2. PyTorch MultiheadAttention

    A key-padding mask excludes designated source positions from attention, whereas an attention mask restricts particular query-to-source interactions. PyTorch exposes these separately: key_padding_mask identifies ignored source entries for each batch item, while attn_mask describes permitted or forbidden position pairs. When both Boolean masks are supplied, their exclusions are combined. Excluding padded source positions is distinct from enforcing causal order.

  3. nanoGPT train.py

    The batch builder takes input tokens from data[i:i+block_size] and targets from data[i+1:i+1+block_size]. Each input position therefore aligns with the next recorded token. Constructed example: a stored sequence [A,B,C,D] supplies inputs [A,B,C] and targets [B,C,D]. All preceding input tokens come from the recorded sequence rather than sampled predictions.

  4. RoFormer: Enhanced Transformer with Rotary Position Embedding

    Rotary position embeddings apply position-dependent rotations to projected queries and keys. The construction divides an even-dimensional vector into coordinate pairs and rotates each pair using its positional angle. Comparing a rotated query at position m with a rotated key at position n introduces relative displacement into their dot product: the positional contribution depends on m−n. Position therefore enters query-key compatibility through transformations of the vectors, rather than only through an added token-state vector.

  5. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    Attention lets context influence token representations, while the demonstrated decoder attention matrix prevents influence from future positions.

  6. Training an LLM from Scratch, Locally

    The workshop forward pass combines token and positional embeddings, processes transformer blocks and normalization, then produces LM-head logits and a training loss.

  7. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

    BERT uses a stack of bidirectional Transformer encoder layers: each token representation can incorporate supplied context on both sides. Its motivation includes token-level tasks where right-hand context matters. Predicting selected corrupted tokens supplies a training objective compatible with this visibility; unrestricted access to an unchanged prediction target would permit leakage. Different output heads use the resulting states differently: classification uses the final state of the added CLS token, while extractive question answering predicts answer boundaries within the supplied passage. Bidirectional representation building therefore need not produce an autoregressive continuation.

  8. Optimizing LLMs for Speed and Memory

    Model parameters are numerical weight matrices and vectors loaded from a checkpoint; text inputs are represented separately as sequences of vectors. In ordinary inference, request inputs pass through those weights without a training update. Applied to RAG, instructions, conversation history, the question and retrieved text belong to request context when included in the input. Changing that text changes the computation without rewriting the checkpoint. Request-specific cached attention keys and values are intermediate computation state, not newly learned model parameters.

  9. PyTorch Embedding

    An embedding is an indexed table with learnable shape vocabulary-size by embedding-width. Integer inputs select rows; an input of shape n produces output of shape n by d. A vector here is a list of d numerical coordinates, and stacking token vectors forms a matrix. Repeated indices select the same row before subsequent positional and contextual processing. The integer serves as an address, rather than a feature magnitude.

  10. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    The demonstrated GPT-2 implementation obtains a token embedding by selecting the corresponding row of the learned model_wte matrix.

  11. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    Embeddings are learned with the model's other parameters through prediction training rather than manually assigned semantic coordinates.

  12. Linear — PyTorch documentation

    A linear layer transforms the final feature dimension while preserving preceding dimensions. Its learned weight and optional bias are separate from the supplied input. Writing the documented operation as Y=XW+b, an n-by-d input and d-by-r matrix produce an n-by-r output. Each output coordinate is the sum of corresponding input and weight products, plus bias. That sum is a dot product. The same transformation applies independently to every sequence row; this projection alone does not exchange information between positions.

  13. Sequence to Sequence Learning with Neural Networks

    Ilya Sutskever, Oriol Vinyals and Quoc Le at Google addressed mappings between variable-length sequences using two recurrent networks. Recurrence carries a numerical state from one position to the next. Their encoder reads the source into a fixed-dimensional state; their decoder generates a target conditioned on that state. Their five-model ensemble exceeded the reported non-neural translation baseline on WMT 2014 English-to-French. Reversing source order improved their results, and the paper reports successful handling of long sentences. Fixed-summary models therefore should not be portrayed as uniformly failing before attention arrived.

  14. Neural Machine Translation by Jointly Learning to Align and Translate

    Bahdanau, Cho and Bengio addressed the difficulty of compressing an entire source sentence into one fixed-length vector. Their recurrent encoder instead produces a sequence of contextual source representations. For each translated word, a learned alignment network compares the preceding decoder state with source representations, normalizes the scores, and forms a weighted source summary. Alignment here means a learned correspondence between target and source positions, rather than a manually supplied word mapping. Attention therefore preceded the Transformer and initially complemented recurrent computation.

  15. Attention Is All You Need

    The Transformer replaced recurrent sequence traversal with attention to enable parallel computation across supplied positions and shorten paths between distant positions. Section 4 contrasts constant-length paths through unrestricted self-attention with paths growing with sequence length in recurrent networks; restricting attention to neighborhoods lengthens those paths. Section 3.2.1 also explains score scaling: assuming independent query and key coordinates with zero mean and unit variance, their dot product has variance d_k. Dividing by sqrt(d_k) counteracts this growth, which otherwise can push softmax into regions with very small gradients.

  16. Attention Is All You Need

    Ashish Vaswani and colleagues' 2017 Transformer demonstrated that an encoder-decoder built without recurrent or convolutional sequence processing could achieve strong translation results. Its reported English-to-German scores exceeded the listed recurrent and convolutional comparators, including ensembles. The paper also evaluated English constituency parsing, extending the demonstration beyond translation.

  17. Improving Language Understanding by Generative Pre-Training

    Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever at OpenAI investigated whether one generatively pretrained Transformer could transfer to varied language-understanding tasks with minimal architectural changes. Their system improved the reported best results on nine of twelve studied tasks. Removing pretraining hurt every evaluated task in their ablation. This establishes an early use of the causal Transformer as a reusable representation model, beyond producing continuations.

  18. Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks

    The paper constructs a self-attention block from multi-head attention, residual additions, row-wise feed-forward transformations and LayerNorm, without positional encoding or dropout. It establishes permutation equivariance: rearranging input elements rearranges their output representations correspondingly. This differs from permutation invariance, where rearrangement leaves the output unchanged. Its later pooling operation supplies invariance for set-level outputs.

  19. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    GPT-2 adds learned position vectors to token embeddings; the supplied position table also bounds the positions supported by this implementation.

  20. Attention Pooling by Similarity — Dive into Deep Learning

    Attention compares a query with keys to obtain similarity scores. Normalized scores weight the associated values; summing those weighted values gives the query-dependent output. Keys determine addressing weights, while values supply the combined content. Equation 11.2.2 explicitly separates query, keys, and values. This explains why retaining both keys and values supports subsequent attention computations.

  21. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    Learning extends beyond MLP weights and biases to embeddings, attention parameters, and normalization parameters.

  22. Attention Is All You Need

    Attention transforms vectors into queries Q, keys K, and values V through learned projections. Each query–key dot product measures compatibility. Dividing by √dk, where dk is key dimension, controls score scale. Row-wise softmax exponentiates and normalizes scores into nonnegative weights summing to one. The output softmax(QKᵀ/√dk)V is a weighted mixture of value vectors, one per query. In self-attention, all three projections originate from the same representation. In cross-attention, queries originate from the representation being updated, while keys and values originate from a separate conditioning representation. Their sequence lengths can differ. Multiple heads learn separate projections, then concatenate and project their outputs.

  23. Effective Approaches to Attention-based Neural Machine Translation

    Minh-Thang Luong, Hieu Pham and Christopher Manning at Stanford compared global and local attention in September 2015. Global attention reads all encoder states for each target prediction; local attention forms a weighted summary within a selected source window, addressing the expense of inspecting every source position. They examined dot-product and learned bilinear compatibility functions alongside other scoring choices. They also fed the preceding attention-informed state into subsequent decoding. Their English–German experiments showed improvements from attention and further gains from this input feeding. Attention thus developed as a family of addressing and information-flow choices within recurrent models before the Transformer.

  24. PyTorch scaled_dot_product_attention

    Ignoring batch and head axes, queries have shape L by d_k, keys S by d_k, and values S by d_v. Scores and weights have shape L by S; the output has shape L by d_v. Softmax runs across source positions. For square causal attention, the permitted entries include the diagonal and lower triangle; excluded scores receive negative infinity before softmax. Constructed teaching example: one query with scaled scores [0,0] and values [2,0] and [0,4] produces weights [0.5,0.5] and output [1,2]. Excluding the second source instead yields [1,0] and [2,0].

  25. Low Level Technicals of LLMs

    A causal decoder must predict from preceding tokens without access to future target information.

  26. Decoding Mistral AI's Large Language Models

    Instruction tuning uses prompt-response pairs and trains next-token prediction on the response while masking the prompt.

  27. Low Level Technicals of LLMs

    Causal masked attention lets a shifted training sequence represent prefix-conditioned predictions while preventing access to future tokens.

  28. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer

    T5 represents relative position with learned scalar biases added to attention logits before attention weights are computed. Bias selection depends on the offset between query and key positions. Its implementation groups offsets into buckets, shares position parameters across layers, and uses different parameters for different heads. The reported configuration uses 32 buckets, with increasingly broad ranges and a shared bucket for sufficiently large offsets. This supplies a concrete contrast with adding absolute position vectors or rotating queries and keys.

  29. RoFormer: Enhanced Transformer with Rotary Position Embedding

    Jianlin Su, Yu Lu, Shengfeng Pan, Bo Wen and Yunfeng Liu at Zhuiyi Technology introduced RoFormer in April 2021. The initial paper supplied preliminary Chinese experiments rather than the English evaluations present in later revisions. Its legal-case matching task asked which of two case descriptions better matched a third. RoFormer performed comparably to WoBERT at a 512-token cutoff and improved when its cutoff increased to 1,024 tokens.

  30. Low Level Technicals of LLMs

    RoPE is presented as encoding token position through sine/cosine-weighted rotations, with the Roformer paper named as its reference.

  31. Low Level Technicals of LLMs

    Insufficient position precision can collapse distinct RoPE positions into the same value.

  32. Are Sixteen Heads Really Better than One?

    The authors ablate attention heads in a translation Transformer and a fine-tuned BERT model. Many individual heads can be removed with little performance change, and some layers retain comparable performance with a selected single head. Other components, particularly some encoder-decoder attention layers, depend substantially on multiple heads. This demonstrates that the presence of multiple heads does not establish that each contributes a unique, indispensable function.

  33. Deep Residual Learning for Image Recognition

    A residual connection adds a learned transformation to its input: y=x+F(x). The shortcut supplies an identity path, while the transformed branch learns a correction relative to that input. Elementwise addition requires matching dimensions; the paper introduces projected shortcuts when dimensions differ. Its motivation is that learning a residual correction can make optimization easier than learning the complete mapping, supported by experiments on deep image-recognition networks.

  34. On Layer Normalization in the Transformer Architecture

    A pre-normalization block can be written u=x+Attention(LayerNorm(x)), followed by y=u+FFN(LayerNorm(u)). Normalization precedes each transformed branch while the residual path carries the unnormalized accumulated state. The paper also applies final normalization before prediction. Post-normalization instead normalizes after each sublayer's residual addition. LayerNorm calculates mean and standard deviation over coordinates of an individual representation vector and applies learned scale and bias. These blocks preserve the outer sequence-by-model-width shape.

  35. nanoGPT model.py

    nanoGPT's forward method adds learned token and position embeddings, executes blocks sequentially, and applies final LayerNorm. With targets, its vocabulary head scores every position and computes cross-entropy; without targets, it projects only the final position. Its separate generation method repeatedly calls forward, takes final-position logits, applies vocabulary softmax, samples an ID and appends it to the prefix. No optimizer update occurs in this loop. Mechanism inference: known input positions are processed together inside each layer, whereas subsequent generated inputs depend on earlier selections. The model's width-d to width-4d to width-d MLP also makes its per-position work explicit.

  36. Root Mean Square Layer Normalization

    RMSNorm rescales a vector using its root mean square: the square root of the average squared coordinate. It then applies learned coordinatewise gains. Unlike LayerNorm, it does not subtract the coordinate mean. The paper separates rescaling from recentering and proposes RMSNorm as a simpler normalization operation that retains rescaling invariance.

  37. LLaMA: Open and Efficient Foundation Language Models

    Hugo Touvron and colleagues at Meta AI documented a concrete later combination of Transformer components in February 2023. LLaMA normalizes sublayer inputs using RMSNorm and uses rotary position embeddings at each layer instead of absolute positional embeddings. The paper explicitly credits Su and colleagues for RoPE. These choices provide a documented downstream use of rotary positions and show that normalization placement and positional handling can change while the Transformer block structure remains recognizable.

  38. Training an LLM from Scratch, Locally

    A residual update adds attention's output to the existing activation instead of replacing that activation.

  39. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    GPT-2 Small repeats the same block operations twelve times, but each block has its own parameters.

  40. Spreadsheets-are-all-you-need: Decoding the Decoder LLM without de code

    Residual connections let information persist around attention and perceptron transformations, supporting a communication-bus view of cooperating layers.

  41. Spreadsheets-are-all-you-need: Decoding the Decoder LLM without de code

    Logit lens applies the language head between layers to reveal how vocabulary rankings evolve before the final prediction.

  42. Improving Language Understanding by Generative Pre-Training

    The original GPT uses a decoder-only Transformer: token and position embeddings pass through repeated masked self-attention and position-wise feed-forward blocks, followed by a vocabulary projection and softmax. The mask restricts a position to earlier context instead of attending to future tokens. Unlike the original encoder-decoder translation Transformer, this language model does not require a separate source encoder and encoder-decoder attention path. Training optimizes prediction of successive tokens; inference applies the learned parameters to the supplied sequence.

  43. Attention Is All You Need

    The original decoder combines masked target self-attention, encoder–decoder attention and a position-wise feed-forward sublayer. Section 3.2.3 specifies decoder-side queries and encoder-output keys and values for encoder–decoder attention, allowing each target position to attend across the source sequence.

  44. Attention Is All You Need — Figure 1 decoder architecture

    Figure 1 shows each original decoder layer proceeding upward through masked multi-head self-attention, encoder–decoder multi-head attention, and a feed-forward sublayer, in that order. An Add & Norm block follows each sublayer. The encoder stack feeds the middle attention sublayer; the decoder state reaches it after masked self-attention and its Add & Norm block.

  45. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

    Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova at Google tested BERT's bidirectional design against a left-context-only language model using matched pretraining data, fine-tuning procedures and hyperparameters. Without next-sentence prediction in either variant, the bidirectional masked-language model performed better on all five reported development tasks, especially passage-answer extraction and paraphrase classification. Adding a bidirectional recurrent layer during fine-tuning improved answer extraction but did not recover the bidirectionally pretrained model's result.

  46. The Small Model Infrastructure Nobody Built (So We Did) — Filip Makraduli, Superlinked

    Supporting BERT, Qwen, and ModernBERT requires accounting for architecture-specific forward-pass behavior rather than assuming identical attention and position handling.

  47. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    The demonstrated language head scores vocabulary tokens using the token embedding matrix, then chooses the largest score for deterministic comparison with another GPT-2 implementation.

  48. Spreadsheets-are-all-you-need: Decoding the Decoder LLM without de code

    The language head applies LayerNorm and an unembedding matrix to produce logits, then the spreadsheet selects the highest-ranked token for its temperature-zero output.

  49. Text generation — Hugging Face Transformers

    Autoregressive generation repeatedly predicts a next token using the prompt and tokens already generated. In notation, P(y|x)=product_t P(y_t|x,y_<t). Decoding chooses each token, for example by taking the highest-probability token or sampling, then extends the sequence. Generation stops on a configured stopping condition such as an end token or output-length limit. Transformers exposes max_new_tokens to bound newly generated tokens; decoder-only generation returns prompt tokens plus the continuation.

  50. Transformers T5 documentation: Training

    Teacher forcing supplies the recorded target sequence as decoder context, shifted so that each position predicts the following target. The documented T5 procedure prepends its start token to decoder inputs and uses target tokens followed by EOS as labels. This establishes the distinction between conditioning training predictions on recorded predecessors and feeding generated choices back during generation. Padding tokens are artificial entries used when batching sequences of different lengths.

  51. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    Autoregressive generation repeatedly appends a predicted token to the input and predicts again.

  52. Transformers GenerationConfig: stopping and output budgets

    Generation can end on an end-of-sequence token, a configured stop string, a length limit, or other stopping criteria. max_new_tokens limits generated tokens independently of prompt length; max_length includes the prompt. These are upper bounds, not promises to produce that many tokens. max_time is not a hard deadline: generation finishes its current pass after the allotted time. For ordinary single-beam generation, do_sample selects sampling versus greedy decoding. An application should distinguish normal completion from length truncation, cancellation and failure rather than interpreting every returned prefix as a completed answer.

  53. Transformers: why causal KV caching works

    Under causal attention, appending future tokens does not change previously computed token representations. Each layer can therefore retain past keys and values. At decoding step t, it computes the new token's query, key, and value, appends k_t and v_t to that layer's cache, and attends with q_t over the retained and current keys and values. This avoids recomputing old projections and old positions' attention outputs. It does not eliminate attention to the retained history: ordinary full-context decoding still performs work proportional to the cached sequence length per new token.

  54. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness

    Dense attention conceptually compares N queries with N keys, producing N-by-N scores before combining values. The paper gives an exact attention algorithm with O(N²d) arithmetic but O(N) additional memory beyond inputs and outputs at fixed head width. Consequently, doubling sequence length approximately quadruples pairwise attention arithmetic without requiring every implementation to store the complete attention matrix. Its algorithm preserves dense attention rather than removing connections.

  55. Longformer: The Long-Document Transformer

    Longformer sparsifies attention by selecting which position pairs can interact. Sliding-window attention connects each token to nearby positions; stacking layers expands the receptive field, meaning the input region that can influence a later representation. Dilated windows skip positions to extend reach. Selected global positions attend across the sequence and are accessible from every position. For question answering, the paper assigns global attention to question tokens; classification uses a global CLS token. With fixed window width and a fixed number of global positions, these patterns require interactions growing linearly with sequence length.

  56. Road to 5 Million Tokens: Breaking Barriers in Long Context Training — Max Ryabinin, Together AI

    The talk distinguishes quadratic attention computation from linearly growing sequence-dependent memory; solving one does not eliminate the other.

  57. Transformers: cache allocation versus retained history

    KV caches retain attention keys and values beyond model weights. DynamicCache grows as tokens arrive; StaticCache preallocates a maximum capacity, masking unused positions and potentially wasting memory and attention work on short sequences. Sliding-window or chunked layers stop growing at their retained-history limits even when the configured sequence capacity is larger. Offloading transfers most layer caches through CPU memory; quantized caches reduce precision but can increase latency for short contexts. Operational inference: allocated slots are a storage decision, not evidence that the model supports that many sequence positions. For ordinary full-history static caching, reserve sufficient slots for prompt plus intended output while independently enforcing the model's supported context limit. Windowed cache capacity must instead follow the architecture's retention rules.

  58. Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation

    ALiBi adds a distance-proportional penalty to query-key scores before softmax, using a fixed slope for each head rather than learned position embeddings. This favors nearer positions without forbidding distant ones. Controlled WikiText-103 experiments trained models on 512- or 1,024-token sequences and evaluated longer inputs. Positional methods differed substantially in how their next-token predictive fit changed beyond training length; ALiBi maintained stronger extrapolation in the reported comparisons. A positional formula being computable at unseen indices is therefore insufficient evidence of reliable length generalization.

  59. Extending Context Window of Large Language Models via Position Interpolation

    Position Interpolation addresses extending an already pretrained RoPE model. It rescales position indices into the original positional range before applying rotary encoding, then fine-tunes the model to the changed representation. The reported LLaMA experiments extend a 2,048-token window to as much as 32,768 tokens and evaluate language modeling, passkey retrieval and summarization. This is adaptation through changed positional handling and further training, distinct from simply evaluating an unchanged checkpoint beyond its training length.

  60. Lost in the Middle: How Language Models Use Long Contexts

    The paper tests multi-document question answering and synthetic key-value retrieval while controlling context length and where relevant information appears. Reordering the answer-containing document changes its position without changing the desired answer. Several evaluated models performed better with evidence near the beginning or end than in the middle; results varied by model and task. This separates fitting tokens inside a supported context window from reliably retrieving and using their information. It motivates controlled position and distractor tests rather than assuming nominal length measures effective use.

  61. RULER: What's the Real Context Size of Your Long-Context Language Models?

    RULER varies sequence length and task complexity using retrieval, variable-chain tracing, aggregation and question answering with distractors. A needle-in-a-haystack task retrieves a specified item from surrounding irrelevant material; RULER extends this beyond single-item retrieval. In its evaluated models, strong simple-retrieval performance often coexists with deterioration on more demanding tasks as inputs lengthen. Accepting a sequence and successfully using its information are therefore distinct claims.

  62. Attention is Not Only a Weight: Analyzing Transformers with Vector Norms

    An attention head's output can be expressed as a sum of attention weights times value vectors transformed by the output projection. A large weight can therefore multiply a very small vector and make only a small additive contribution. In the paper's BERT analysis, special tokens and punctuation often received large attention weights while their transformed-vector contributions were comparatively small. Examining the vectors changed the interpretation suggested by the attention heatmap alone.

  63. Attention is not Explanation

    Sarthak Jain and Byron Wallace's June 2019 paper tested whether attention weights identify inputs responsible for predictions. Across classification, question answering and inference tasks, weights in their recurrent models correlated weakly or inconsistently with gradient-based importance and changes caused by removing tokens. They also constructed substantially different attention distributions that preserved nearly identical predictions while other model parameters remained fixed. Their findings challenge reading a heatmap directly as an explanation of a prediction.

  64. Attention is not not Explanation

    Wiegreffe and Pinter test attention interpretation using uniform-attention baselines, variation across random initializations, transferred attention distributions and adversarially trained alternatives. Learned attention offered little benefit on some classification tasks, while attention distributions transferred from trained recurrent models improved a separate token-level classifier over uniform weighting on the tested datasets. Their findings support testing whether an attention interpretation is useful in a specific setting instead of treating either a heatmap or its manipulability as a universal verdict.

  65. Low Level Technicals of LLMs

    Compare intermediate layer outputs against a reference implementation using a log L2 error plot, but establish the reference before automating variant searches.

  66. Training an LLM from Scratch, Locally

    Each transformer block has its own weights, attention, normalization, and MLP, also called an FFN.

  67. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    Random sampling is an added selection step; the speaker contrasts it with greedy selection, also described as temperature zero.

  68. $1 AI Guardrails: The Unreasonable Effectiveness of Finetuned ModernBERTs – Diego Carpentero

    Unpadding, sequence packing, and FlashAttention address different sources of overhead: meaningless padding work and expensive attention-memory traffic.

  69. $1 AI Guardrails: The Unreasonable Effectiveness of Finetuned ModernBERTs – Diego Carpentero

    ModernBERT's alternating attention is presented as a way to capture localized attack signals while retaining broader context without using global attention in every layer.

  70. Why More Context Makes Your Agent Dumber and What to Do About It

    The speaker reports a U-curve pattern in code-review experiments: initial goals and final inputs receive attention while intervening context can be neglected.

  71. Training an LLM from Scratch, Locally

    For the creative-text exercise, sample from token probabilities rather than always choosing the highest-scoring token, and use top-k to restrict the candidate set.

  72. Road to 5 Million Tokens: Breaking Barriers in Long Context Training — Max Ryabinin, Together AI

    DeepSpeed Ulysses context parallelism distributes attention heads across GPUs while retaining full-sequence attention for each assigned head.