Transformer blocks, residual paths, and position
How to study this lesson
Read one section, trace the worked example, and try the knowledge check. Bookmark saves a shortcut; notes appear in My notebook. Mark lesson complete is your own assessment and does not mark its lab passed.
By the end, you can
- Trace hidden states through attention and feed-forward sublayers.
- Explain residual and normalization roles without treating them as guarantees.
- Compute a rotary position transformation and relative-position property.
A decoder is repeated hidden-state transformation
After token embedding, a decoder-only transformer repeatedly updates a hidden vector at every position. Each block typically includes an attention sublayer and a position-wise feed-forward sublayer, combined with residual connections and normalization. The final hidden states are transformed into vocabulary logits. Exact arrangements vary, so inspect the architecture configuration rather than assuming every named transformer uses identical ordering.
Attention mixes information across permitted positions. The feed-forward sublayer transforms each position's features using shared learned weights, often expanding to a wider intermediate representation before projecting back. With causal masking, the hidden state for a prefix position cannot depend on future tokens. That property is central to why old key and value representations can later be reused during incremental generation.
Residual paths preserve a route through depth
A residual update has the form x plus F(x). The sublayer learns a change to the existing representation while an identity path remains available. In backpropagation, that identity path contributes directly to the derivative, which can help optimization in deep networks. It is not a guarantee against instability or a promise that every layer preserves an interpretable fact.
Consider x = [2, -1] and a sublayer output [0.1, 0.3]. The residual result is [2.1, -0.7]. Without the addition, the output would contain only [0.1, 0.3]. The numerical example is simple, but it captures why a sublayer can make a small correction instead of reconstructing the whole representation. Learned projections and normalization can still substantially change information over many layers.
Normalization controls scale inside the block
Layer normalization uses statistics across a position's feature coordinates, followed by learned scale and often shift parameters. RMS normalization instead scales using the root mean square and does not perform the same mean-centering operation. Architectures may normalize before a sublayer, after it, or use additional variants. These choices alter the computation and training behavior; the names are not interchangeable.
For x = [3,4], the root mean square is the square root of 12.5, approximately 3.536. Dividing by it produces approximately [0.849,1.131] before learned scaling. This operation changes magnitude but retains some relative coordinate structure. A small epsilon avoids division by zero. Normalization is internal feature conditioning, not a substitute for validating user data or calibrating final output probabilities.
RoPE rotates pairs according to position
Rotary positional embedding applies position-dependent rotations to paired query and key coordinates. For a pair [a,b] and angle theta, the rotated pair is [a cos theta - b sin theta, a sin theta + b cos theta]. Different coordinate pairs use different frequencies. Rotation preserves the pair's norm while changing its orientation, so position influences query-key dot products.
A useful identity is that the dot product of q rotated by m theta and k rotated by n theta depends on their relative rotation, proportional to n-m. Rotating both by an additional shared angle leaves their dot product unchanged. This supplies a structured relative-position effect within attention. Actual models use many coordinate pairs and architecture-specific frequency or scaling settings; the two-coordinate demonstration is only the underlying mechanism.
Architecture details become deployment assumptions
Modern decoder variants can use gated feed-forward activations, grouped key/value heads, tied embedding and output weights, or mixtures of experts. These choices affect parameter count, active computation, memory traffic, and cache shape. A model's total parameter count does not by itself specify per-token compute or serving memory. The next lesson focuses on one especially practical consequence: the cache retained for previous tokens.
The example verifies norm preservation and a shared-shift dot-product identity for a single rotary pair, then performs a visible residual update. It makes no claim about a particular deployed model. When inspecting an open architecture, write down layer count, hidden dimension, head layout, position settings, normalization type, and vocabulary size. These configuration facts help explain behavior more concretely than a model-family label alone.
Work through the code
Two query/key coordinate pairs are rotated at different positions, then both positions are shifted by seven. Their dot product remains equal within floating-point tolerance. The separate residual calculation demonstrates addition. This is a RoPE identity check, not a complete positional implementation for a pretrained model.
import math
def rotate(pair, position, frequency):
angle = position * frequency
a, b = pair
return [a * math.cos(angle) - b * math.sin(angle),
a * math.sin(angle) + b * math.cos(angle)]
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
q, k = [1.0, 2.0], [3.0, -1.0]
frequency = math.pi / 8
base = dot(rotate(q, 2, frequency), rotate(k, 5, frequency))
shifted = dot(rotate(q, 9, frequency), rotate(k, 12, frequency))
print("shared shift preserves dot:", math.isclose(base, shifted))
print("rotation preserves norm:", math.isclose(dot(q, q), dot(rotate(q, 2, frequency), rotate(q, 2, frequency))))
x, update = [2.0, -1.0], [0.1, 0.3]
print("residual:", [round(a + b, 3) for a, b in zip(x, update)])
shared shift preserves dot: True rotation preserves norm: True residual: [2.1, -0.7]
Run Python snippets locally with the prerequisites named above. The module coding lab runs directly in your browser.
Pause and reason
A model uses RoPE with query at position 4 and key at position 1. If both positions increase by 100 under the same unchanged frequency rules, what happens to their pairwise dot product? What assumption could break this comparison?
Check your understanding
Which statement accurately distinguishes attention from a position-wise feed-forward sublayer?
Your notes
Explain the mechanism in your own words. Add a failure you want to test.