This Attention & Transformers concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.
Attention & Transformers
Decoder-Only Transformer Forward Pass
A shape-first walk from token IDs through a decoder-only Transformer block to logits and masked next-token loss.
Concept Structure
Decoder-Only Transformer Forward Pass
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learner Contract
What this page should let you do.
10 prerequisites listed; refresh them before leaning on the math or code.
Explain the mechanism, trace the main notation, and test one prediction in the live demo.
Read the intuition before the notation; the math should name a mechanism you already felt.
Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.
Claim/source review status
Substantive review recorded
1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
The first useful Transformer-from-scratch question is not "how do I train GPT?" It is smaller and sharper:
If the input is a batch of token IDs, where does the vocabulary dimension first appear?
Inside the block, the model mostly preserves a hidden-state shape. Token IDs start as a table of integers shaped (B,T), where B is batch size and T is sequence length. Embedding turns each integer into a vector, so the residual stream becomes (B,T,d_model). Causal self-attention returns another (B,T,d_model) object. The MLP branch returns (B,T,d_model) too. That sameness is what makes residual addition legal.
Only the final output projection changes the last dimension from d_model to the vocabulary size V. Those logits are then paired with shifted next-token labels and a loss mask from the training example.
This page is a local shape probe, not a training-quality implementation. It is meant to make the forward pass inspectable before we add stacking, optimizers, checkpoints, data scale, or performance kernels.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let:
Bbe batch size.Tbe sequence length.dbed_model, the hidden width.Vbe vocabulary size.X in {0,...,V-1}^{B x T}be token IDs.E_tok in R^{V x d}be the token embedding table.E_pos in R^{T x d}be a learned positional embedding table for this local shape probe.
The input hidden state is
so H_0 has shape (B,T,d).
For a single pre-norm decoder block, the attention branch is applied to normalized hidden states:
For query position i and key position j, the causal mask is
The toy single-head attention output is
A has shape (B,T,d), so the first residual update is legal:
The MLP branch also returns the residual-stream width:
The vocabulary dimension appears when we unembed the final hidden states:
where W_U in R^{d x V} and Z has shape (B,T,V).
For causal language modeling, logit row Z[b,t,:] predicts the next label Y[b,t] = X[b,t+1], except positions excluded by the loss mask. With active positions \Omega, the masked cross-entropy is
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
import numpy as np
rng = np.random.default_rng(0)
B, T, d, V = 1, 6, 4, 8
ids = np.array([[1, 3, 4, 2, 1, 5]])
labels = np.array([[3, 4, 2, 1, -100, -100]])
active = labels != -100
tok = rng.normal(size=(V, d)) * 0.2
pos = rng.normal(size=(T, d)) * 0.2
Wq = rng.normal(size=(d, d)) * 0.2
Wk = rng.normal(size=(d, d)) * 0.2
Wv = rng.normal(size=(d, d)) * 0.2
Wo = rng.normal(size=(d, d)) * 0.2
W1 = rng.normal(size=(d, 2 * d)) * 0.2
W2 = rng.normal(size=(2 * d, d)) * 0.2
Wu = rng.normal(size=(d, V)) * 0.2
def ln(x, eps=1e-5):
return (x - x.mean(-1, keepdims=True)) / np.sqrt(x.var(-1, keepdims=True) + eps)
def softmax(x):
e = np.exp(x - np.max(x, axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
h = tok[ids] + pos[None, :, :]
q, k, v = ln(h) @ Wq, ln(h) @ Wk, ln(h) @ Wv
mask = np.triu(np.full((T, T), -np.inf), k=1)
attn = softmax(q @ np.swapaxes(k, -1, -2) / np.sqrt(d) + mask) @ v
h = h + attn @ Wo
h = h + np.tanh(ln(h) @ W1) @ W2
logits = ln(h) @ Wu
log_probs = logits - np.log(np.exp(logits).sum(axis=-1, keepdims=True))
rows = np.arange(active.sum())
loss = -log_probs[active][rows, labels[active]].mean()
print(h.shape, logits.shape, round(float(loss), 4))
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
The lab below hides the answer-bearing shapes until you commit.
Before reveal, predict which stage first changes the residual stream's last dimension from d_model to the vocabulary size V. After reveal, inspect the full path from token IDs to hidden states, logits, shifted labels, active loss positions, and masked mean cross-entropy.
The important invariant is simple: attention and the MLP update the residual stream; the output projection turns hidden states into vocabulary logits.
Live Concept Demo
Explore Decoder-Only Transformer Forward Pass
The stage is code-native and interactive. Use it to test the explanation against the mechanism.
Manipulate one control and predict the visible change.
Commit to what Decoder-Only Transformer Forward Pass should make visible before reading the result.
After The First Pass
Turn the concept into an inspected object.
Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.
Mechanism Storyboard
See the idea move before the page explains it
A shape-first walk from token IDs through a decoder-only Transformer block to logits and masked next-token loss.
Start with the picture, metaphor, or geometric mechanism.
Before reading further, choose the kind of change Decoder-Only Transformer Forward Pass should make visible.
Visual Inquiry
Make the image answer a mathematical question
A shape-first walk from token IDs through a decoder-only Transformer block to logits and masked next-token loss.
Which visible object should carry the first intuition?
Pick the cue that should make Decoder-Only Transformer Forward Pass easier to reason about before the page gives the answer.
Source Grounding
Canonical references for the mechanism on this page.
Route-level source for implementing tokenizer, Transformer language-model architecture, optimizer, and a minimal language model from scratch. The public adapters expose the same-shape Transformer block contract and LM logits shape.
Open sourcePedagogical source for Transformer residual connections, layer normalization, positionwise feed-forward networks, and masked decoder self-attention.
Open sourcePrimary Transformer source for scaled dot-product attention, decoder masking, residual connections around sublayers, layer normalization, and linear-softmax output generation.
Open sourceNLP sequence-modeling source for next-token language-model framing and Transformer self-attention pedagogy.
Open sourceClaim Review
A shape-first walk from token IDs through a decoder-only Transformer block to logits and masked next-token loss.
Claims without a substantive review badge still need exact source-support review.
cs336-assignment1-basics, d2l-transformer-chapter, vaswani-2017-attention, cs224n-self-attention-transformers
Use equations, runnable code, and demos to check whether the source support is operational.
CS336 supports the block and LM output shape contracts; D2L and Vaswani support residual, normalization, feed-forward, mask, and output-projection mechanics.
Sources: Stanford CS336 Assignment 1: Basics, Dive into Deep Learning: Transformer, Attention Is All You NeedThis page checks a one-block local shape probe. It does not claim benchmark quality, production training, exact PyTorch module parity, KV-cache behavior, weight tying, RoPE implementation details, or modern architecture variants such as grouped-query attention.A bounded review summary is present; still check caveats and exact reference scope.Checked CS336 course/assignment pages and adapters, D2L Transformer text, Vaswani et al. Transformer sections, and the existing Continuous Function packed-example and causal-mask concepts. The page remains review-status pending GPT Pro publication critique.
Reviewer: codex-local-source-audit; reviewed 2026-07-02Source support candidates
course-notes 2025Stanford CS336 Assignment 1: BasicsRoute-level source for implementing tokenizer, Transformer language-model architecture, optimizer, and a minimal language model from scratch. The public adapters expose the same-shape Transformer block contract and LM logits shape.
reference 2026Dive into Deep Learning: TransformerPedagogical source for Transformer residual connections, layer normalization, positionwise feed-forward networks, and masked decoder self-attention.
paper 2017Attention Is All You NeedPrimary Transformer source for scaled dot-product attention, decoder masking, residual connections around sublayers, layer normalization, and linear-softmax output generation.
course-notes 2023CS224N: Self-Attention and TransformersNLP sequence-modeling source for next-token language-model framing and Transformer self-attention pedagogy.
Practice Loop
Try the idea before it explains itself
A shape-first walk from token IDs through a decoder-only Transformer block to logits and masked next-token loss.
Before touching the demo, predict one visible change that should happen in Decoder-Only Transformer Forward Pass.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
Research Room
Attach the question to a claim, equation, code, or demo
Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.Open the draft below to save one note and next action in this browser.
Decoder-Only Transformer Forward Pass
What is the smallest example that makes Decoder-Only Transformer Forward Pass click without losing the math?
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays in this browser, attached to the selected learning item.
- References to inspect: attached references on this page.
- Definition, prerequisite, and contrast concept links
- The equation or runnable code that makes the concept operational
- One demo state that shows the invariant instead of a slogan
- The learner can state the mechanism in their own words
- The learner can name the prerequisite that would repair confusion
- The learner can predict how the mechanism changes under one perturbation
I am working in Continuous Function's research reading room. Object: concept - Decoder-Only Transformer Forward Pass Selected item key: recorded for copy. Context: Attention & Transformers Page anchor: recorded for copy. Open question: What is the smallest example that makes Decoder-Only Transformer Forward Pass click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.
concept/concept-notebook/attention-transformers/decoder-only-transformer-forward-pass
concept:attention-transformers/decoder-only-transformer-forward-pass