MANAV BAROT / INTERACTIVE NOTEBOOK
Inside the
Transformer.
An interactive, code-first guide to the architecture behind modern language models. Change the input, inspect tensors, click attention weights, and trace a token through a complete forward pass.
One forward pass. Five big ideas.
At its core, a Transformer converts text into vectors, repeatedly mixes information between token positions, transforms features, and predicts what comes next. Click each stage to inspect its role and tensor shape.
Tokenization
A neural network doesn't read words directly. A tokenizer maps text fragments to integer IDs. Edit the prompt below — its tokens feed the live visualizations throughout this page.
Embeddings & positional information
Embedding lookup gives each token a learnable vector. A Transformer must also encode where a token is in the sequence; otherwise, attention alone does not know token order.
PE(pos, 2i+1) = cos(pos / 100002i/d)
This visualization uses sinusoidal encoding. For clarity, it omits the original model’s √d_model embedding scale. Modern models also use learned positions, RoPE (rotary position embeddings), and relative position methods. Changing position changes the resulting vectors.
Queries, keys & values
Every input vector is projected into three distinct representations. Queries ask what a position needs; keys describe what positions match; values carry the information to combine.
Illustrative sizes: X ∈ ℝn×8 ; Q, K, V for one head ∈ ℝn×2
Scaled dot-product attention
Each query compares itself against every key. The similarity scores are scaled, optionally masked, normalized with softmax, and used to weight the values. Click a heatmap row or cell to explore exactly where a token attends.
scores = Q @ K.T / sqrt(d_head)
scores = causal_mask(scores) # optional: future positions → −∞
weights = softmax(scores, axis=-1)
output = weights @ V
Multi-head attention
Instead of one attention map, Transformers calculate several in parallel. Their outputs are concatenated and projected back into the model dimension. Select a head to inspect its pattern in the attention lab above.
4 heads × 2 channels = 8 channels, then WO ∈ ℝ8×8
Residuals, LayerNorm & the FFN
Attention moves information between tokens; the position-wise feed-forward network (MLP) mixes features within each token. Skip connections preserve a direct information path, while normalization stabilizes activations.
The toy block omits dropout, uses zero FFN biases and fixed LayerNorm gain 1 / bias 0. The skip path adds the input back to a sublayer's result: y = x + f(x). This helps gradient flow.
LayerNorm centers and scales features of each token using its own mean and variance, with learnable gain and bias.
W₂ · GELU(W₁x+b₁)+b₂. The same MLP weights apply independently to every position.
Encoder, decoder, or both?
Attention masking and information flow determine what tokens are allowed to see. Explore the three main Transformer layouts, including cross-attention in sequence-to-sequence models.
The key–value cache
Without caching, generation would repeatedly recompute past keys and values. A KV cache stores K/V for previous tokens, so each decoding step projects only the new token while attending to earlier cached positions.
Logits, softmax & sampling
A final projection maps the last token's hidden vector into one logit for each vocabulary entry. Softmax converts logits into probabilities. Temperature and top-k change how the next token gets selected.
Lower T → sharper distribution · higher T → flatter distribution · top-k → restrict to k highest logits, renormalize
Next-token training & cross-entropy
During autoregressive training, a sequence is shifted by one position: each token predicts the next. The loss penalizes low probability assigned to the correct next token, and backpropagation updates the weights.
Perplexity = exp(mean cross-entropy)
Production training sums or averages over many positions, examples, and batches. Padding and other tokens may be excluded from loss.
Check your mental model.
Three quick questions to test whether the pieces fit together. Select an answer for immediate feedback.