This Attention & Transformers concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.
Attention & Transformers
Pre-Norm Transformer Block
Where normalization sits inside a Transformer block, why attention and MLP branches must preserve residual-stream shape, and how pre-norm changes the local gradient route.
Concept Structure
Pre-Norm Transformer Block
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.
5 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.
A Transformer block is easiest to understand as a residual-stream update.
The residual stream carries one vector per token. Attention writes one update into that stream. The MLP writes another update. Both updates must have the same shape as the stream, otherwise the residual addition is not legal.
The slippery question is not whether we use normalization. The question is:
Do we normalize before the branch reads from the stream, or after the branch has been added back?
Post-norm, the original Transformer layout, does this for a sublayer:
The residual addition happens, then the sum is normalized.
Pre-norm moves normalization inside the branch:
Now the branch still reads a normalized vector, but the residual stream has a more direct identity route through the addition. That is why pre-norm is often introduced when discussing deeper Transformer stacks and training stability.
Keep the caveat sharp: pre-norm is not a universal magic switch. It changes the local computation graph. Full training behavior also depends on depth, initialization, learning-rate schedule, normalization variant, residual scaling, optimizer, dropout, data, and task.
Vaswani et al. define the original post-norm-style sublayer output as LayerNorm(x + Sublayer(x)) and require sublayers to output d_model so residual addition works.
D2L's Transformer chapter teaches the same AddNorm idea, the positionwise feed-forward branch, and the requirement that residual inputs have matching shapes.
Xiong et al. analyze layer-normalization placement and argue that the original Post-LN placement can create large expected gradients near the output layer at initialization, while Pre-LN places normalization inside residual blocks and has better-behaved initialization gradients in their setting.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let:
Bbe batch size.Tbe sequence length.dbe residual-stream width.X_l in R^{B x T x d}be the residual stream entering blockl.Nbe LayerNorm or RMSNorm applied per token over the feature axis.Abe the attention branch.Mbe the MLP branch.
Both branches must return residual-stream width:
That shape invariant is what lets a block update the stream rather than replace the interface.
For a two-sublayer pre-norm block:
The attention branch and MLP branch each read a normalized stream, but each residual addition has an explicit identity path.
For the corresponding post-norm layout:
The same shapes appear, but the norm sits after each residual addition.
The local Jacobian picture explains the demo. For one sublayer F:
There is an explicit identity term.
For post-norm:
The residual addition is still present, but the path out of the sublayer passes through the normalization Jacobian. This local calculation is an intuition for placement, not a full convergence theorem.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
import numpy as np
rng = np.random.default_rng(4)
B, T, d = 1, 4, 6
x = rng.normal(size=(B, T, d))
Wa = rng.normal(size=(d, d)) * 0.08
W1 = rng.normal(size=(d, 2 * d)) * 0.08
W2 = rng.normal(size=(2 * d, d)) * 0.08
def ln(u, eps=1e-5):
return (u - u.mean(-1, keepdims=True)) / np.sqrt(u.var(-1, keepdims=True) + eps)
def attn(u):
return u @ Wa # toy same-shape attention branch
def mlp(u):
return np.tanh(u @ W1) @ W2 # expand then project back to d
def pre_block(u):
v = u + attn(ln(u))
return v + mlp(ln(v))
def post_block(u):
v = ln(u + attn(u))
return ln(v + mlp(v))
def jac(fn, flat):
eps, y0 = 1e-4, fn(flat)
J = np.zeros((y0.size, flat.size))
for i in range(flat.size):
step = np.zeros_like(flat); step[i] = eps
J[:, i] = (fn(flat + step) - y0) / eps
return J
flat = x.reshape(-1)
Jpre = jac(lambda z: pre_block(z.reshape(B, T, d)).reshape(-1), flat)
Jpost = jac(lambda z: post_block(z.reshape(B, T, d)).reshape(-1), flat)
print("pre/post shapes:", pre_block(x).shape, post_block(x).shape)
print("trace per dim:", round(np.trace(Jpre) / flat.size, 3), round(np.trace(Jpost) / flat.size, 3))
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
The lab below compares one branch at a time.
Before reveal, choose which norm placement gives the residual stream a more direct identity route for gradients. After reveal, inspect the formulas, same-shape ledger, and local gradient-path summary.
The key invariant is: attention and MLP write same-shape updates into the residual stream; pre-norm moves normalization before the branch, while post-norm normalizes after the residual addition.
The demo is deliberately narrow. It does not say every model must use pre-norm, and it does not turn a local Jacobian sketch into a full training theorem.
Live Concept Demo
Explore Pre-Norm Transformer Block
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 Pre-Norm Transformer Block 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
Where normalization sits inside a Transformer block, why attention and MLP branches must preserve residual-stream shape, and how pre-norm changes the local gradient route.
Start with the picture, metaphor, or geometric mechanism.
Before reading further, choose the kind of change Pre-Norm Transformer Block should make visible.
Visual Inquiry
Make the image answer a mathematical question
Where normalization sits inside a Transformer block, why attention and MLP branches must preserve residual-stream shape, and how pre-norm changes the local gradient route.
Which visible object should carry the first intuition?
Pick the cue that should make Pre-Norm Transformer Block easier to reason about before the page gives the answer.
Source Grounding
Canonical references for the mechanism on this page.
Primary Transformer source for residual connections around each sublayer, post-norm LayerNorm(x + Sublayer(x)), and the same d_model output dimension needed for residual addition.
Open sourcePedagogical source for AddNorm, positionwise feed-forward networks, residual shape requirements, and Transformer block assembly.
Open sourcePrimary source comparing Post-LN and Pre-LN placement and arguing via mean-field analysis that Post-LN can have large initialization gradients near the output layer while Pre-LN gradients are better behaved in their setting.
Open sourceFramework source for LayerNorm over the last D dimensions and same input/output shape.
Open sourcePrimary RMSNorm source for RMS-only rescaling. This page mentions RMSNorm as a common normalization object that can occupy the same pre-branch placement.
Open sourceCourse-level route source for implementing Transformer model architecture as part of a language-model-from-scratch path.
Open sourceClaim Review
Where normalization sits inside a Transformer block, why attention and MLP branches must preserve residual-stream shape, and how pre-norm changes the local gradient route.
Claims without a substantive review badge still need exact source-support review.
vaswani-2017-transformer-sublayers, d2l-2026-transformer-addnorm, xiong-2020-layernorm-transformer, pytorch-layernorm, zhang-2019-rmsnorm, cs336-language-modeling-from-scratch
Use equations, runnable code, and demos to check whether the source support is operational.
Vaswani and D2L support residual-plus-normalization sublayer structure and same-shape residual requirements; PyTorch supports LayerNorm same-shape behavior; Xiong et al. support the distinction between Post-LN and Pre-LN placement and the claim that placement affects initialization gradients and warm-up behavior in their analysis.
Sources: Attention Is All You Need, Dive into Deep Learning: Transformer Architecture, On Layer Normalization in the Transformer Architecture, PyTorch torch.nn.LayerNormThis is a one-block shape and local-gradient-route witness. It does not prove universal superiority of pre-norm, does not cover every modern normalization variant, and does not replace full training-stability experiments.A bounded review summary is present; still check caveats and exact reference scope.Checked Vaswani et al. sections 3.1/5.4, D2L Transformer AddNorm material, Xiong et al. 2020 abstract/source page, PyTorch LayerNorm docs, RMSNorm source context, and Stanford CS336 route context. Page remains review-status pending GPT Pro publication critique.
Reviewer: codex-local-source-audit; reviewed 2026-07-02Source support candidates
paper 2017Attention Is All You NeedPrimary Transformer source for residual connections around each sublayer, post-norm LayerNorm(x + Sublayer(x)), and the same d_model output dimension needed for residual addition.
book 2026Dive into Deep Learning: Transformer ArchitecturePedagogical source for AddNorm, positionwise feed-forward networks, residual shape requirements, and Transformer block assembly.
paper 2020On Layer Normalization in the Transformer ArchitecturePrimary source comparing Post-LN and Pre-LN placement and arguing via mean-field analysis that Post-LN can have large initialization gradients near the output layer while Pre-LN gradients are better behaved in their setting.
documentation 2026PyTorch torch.nn.LayerNormFramework source for LayerNorm over the last D dimensions and same input/output shape.
Practice Loop
Try the idea before it explains itself
Where normalization sits inside a Transformer block, why attention and MLP branches must preserve residual-stream shape, and how pre-norm changes the local gradient route.
Before touching the demo, predict one visible change that should happen in Pre-Norm Transformer Block.
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.
Pre-Norm Transformer Block
What is the smallest example that makes Pre-Norm Transformer Block 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 - Pre-Norm Transformer Block Selected item key: recorded for copy. Context: Attention & Transformers Page anchor: recorded for copy. Open question: What is the smallest example that makes Pre-Norm Transformer Block 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/pre-norm-transformer-block
concept:attention-transformers/pre-norm-transformer-block