AI & Machine Learning Master Course — 127. Transformer blocks
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 127: Transformer blocks
Prerequisites: Lesson 126. Learning outcome: Trace attention, feedforward, normalization, and residual pathways.
A transformer block is more than an attention matrix
A transformer block combines information across positions and then transforms features at each position. Attention performs the cross-position mixing. A feedforward network applies a nonlinear feature transformation independently at each position, using shared parameters. Residual pathways and normalization help organize these transformations into a trainable stack.
The block consumes and returns the same model width so that residual addition is well defined. If input X has shape (sequence_length, model_width), an attention sublayer may use several internal dimensions, but its output projection returns to model_width before addition. An operation that broadcasts successfully can still be conceptually wrong, so verify axis meanings as well as dimensions.
Embeddings and positional information prepare the sequence before or within the stack according to the architecture. The block itself does not automatically know that position zero is the beginning of a sentence. Our lab supplies a numerical array and concentrates on the block’s mechanics, not a complete language model.
Trace one pre-normalized block
A simplified pre-normalized block first computes normalized input N=LayerNorm(X). It forms attention from N, projects the result, and adds the original X to produce U. Then it normalizes U, applies a two-layer feedforward network with a nonlinearity, and adds that output back to U.
In compact form, U=X+Attention(LayerNorm(X)) and Y=U+FFN(LayerNorm(U)). Post-normalized designs place normalization after residual addition instead. Both are legitimate architectural conventions; swapping their order changes the function and can change training behavior. Record which convention you implement.
Layer normalization here computes mean and variance across each token’s feature coordinates. It does not mix statistics across sequence positions. The lab omits learned normalization scale and offset, uses one attention head, and has no dropout. Those simplifications make it a small transformer-style block, not a faithful reproduction of every component in a published model.
Heads, feedforward width, and residual roles
Multi-head attention uses several learned query, key, and value projections, computes separate weighted combinations, and combines them through an output projection. Heads are opportunities for different representations; their number does not guarantee a matching number of interpretable linguistic functions.
The feedforward sublayer typically expands the feature width, applies a nonlinearity, and projects back. In the lab it expands four features to six and returns to four. The same feedforward weights are applied to every position. Cross-position communication occurs through attention in this construction, not through the position-wise feedforward matrix.
Residual connections add a transformed update to an existing representation. They preserve a direct path, but they do not force the network to copy inputs unchanged. Normalization, nonlinear transformations, and later blocks still determine the output. A residual addition also does not by itself enforce causality; that comes from the information paths and their masks.
CPU lab: verify that future changes stay in the future
The script constructs three tokens with four features each and fixed random weights from a recorded seed. It uses a lower-triangular allowed mask, so position zero sees only itself, position one sees positions zero and one, and position two sees all three.
After one block pass, we substantially change only the final input token and run the same block again. The first two outputs remain unchanged, while the last output changes. This is an intervention test of the causal mask. Shape and finite-value checks also pass.
The code executes with NumPy only. Its layer normalization has epsilon 0.00001, variance divided by feature count, and no learned affine parameters. The attention scaling denominator is two because the key dimension is four. The block is not trained, and the output has no vocabulary prediction head. No language-quality or speed claim follows from this check.
import numpy as np
rng = np.random.default_rng(127)
X = rng.normal(size=(3, 4))
Wq, Wk, Wv, Wo = [rng.normal(0, .2, (4, 4)) for _ in range(4)]
W1 = rng.normal(0, .2, (4, 6)); W2 = rng.normal(0, .2, (6, 4))
def norm(a):
return (a - a.mean(axis=-1, keepdims=True)) / np.sqrt(
a.var(axis=-1, keepdims=True) + 1e-5)
def block(a, mask):
n = norm(a)
scores = (n @ Wq) @ (n @ Wk).T / 2
scores = np.where(mask, scores, -np.inf)
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)
u = a + (weights @ (n @ Wv)) @ Wo
return u + np.maximum(norm(u) @ W1, 0) @ W2
causal = np.tril(np.ones((3, 3), dtype=bool))
Y = block(X, causal)
changed = X.copy(); changed[2] += [10., -5., 2., 1.]
Y2 = block(changed, causal)
assert np.allclose(Y[:2], Y2[:2])
assert not np.allclose(Y[2], Y2[2])
print('Input / output shapes:', X.shape, Y.shape)
print('Earlier causal outputs unchanged:', True)
print('Finite output:', bool(np.isfinite(Y).all()))
Training and inference use the same information boundary
During causal language-model training, a whole known sequence can be processed in parallel because the mask prevents each position from reading its future targets. At generation time, future tokens do not yet exist and are produced step by step. Parallel training therefore does not imply that ordinary autoregressive decoding generates all dependent tokens simultaneously.
Padding masks must be handled as well as causal masks. If a batch contains shorter sequences, padded keys should not contribute content, and padded target positions should not contribute ordinary training loss. APIs may use different Boolean conventions, so test actual behavior with a small intervention like the lab’s.
A real experiment must document depth, width, heads, positional scheme, normalization convention, dropout, and optimization settings. Compare models using fixed evaluation partitions and clearly stated resource budgets. A tiny block can teach the computational graph, but training a useful language model is a separate undertaking requiring data, optimization, and evaluation evidence.
Four practice questions with worked answers
Practice 1
Why must an attention output return to the model width before residual addition?
Answer: The residual sum combines corresponding feature coordinates of the original input and the sublayer output. A projection aligns widths. Accidental broadcasting could produce a numeric array while failing to represent the intended sum.
Practice 2
For three causal positions numbered zero through two, which keys may position one use?
Answer: It may use keys zero and one, but not two. This preserves access to the observed prefix while excluding future information.
Practice 3
The model width is four and feedforward width is six. Ignoring biases, how many feedforward weights are there?
Answer: The expansion matrix has 4×6=24 values and the contraction matrix has 6×4=24. Together they contain forty-eight weights, shared across all positions.
Practice 4
Why does changing the last token leave earlier outputs unchanged in this lab?
Answer: The causal mask blocks earlier queries from attending to the last token. Layer normalization and the feedforward network operate independently per position, and residual paths remain local, so no alternate future-to-past path exists.
Five multiple-choice questions
Question 1
Which sublayer mixes information across positions here?
- A. Self-attention.
- B. The position-wise feedforward network by itself.
- C. Per-token layer normalization by itself.
Correct: A. Attention combines values from allowed positions. The other two operations transform each token independently in this construction.
Question 2
Where is normalization placed in the lab’s pre-normalized block?
- A. Only after every residual addition.
- B. Across all sequence positions using one shared mean and variance.
- C. Before each attention or feedforward sublayer.
Correct: C. Pre-normalization applies to the sublayer input. Post-normalization is a different ordering, and this layer normalization uses per-token feature statistics.
Question 3
What does the future-token intervention test establish?
- A. The random weights have learned useful sentence representations.
- B. The block can decode all dependent output tokens simultaneously.
- C. Earlier outputs obey the implemented causal information restriction.
Correct: C. The test checks information flow. No training occurs, and autoregressive generation remains sequential in its token dependencies.
Question 4
Why does a feedforward expansion return to the original width?
- A. The expansion is required to preserve every input coordinate exactly.
- B. Its result must align with the residual representation.
- C. Returning to the original width removes the need for any nonlinearity.
Correct: B. Residual addition requires aligned features. Width restoration does not imply exact reconstruction or eliminate nonlinear modeling.
Question 5
What else is needed for variable-length padded causal batches?
- A. Removing the causal mask whenever padding is present.
- B. Appropriate padding handling in attention and loss.
- C. Counting padded positions as ordinary next-token targets.
Correct: B. Padding and causal restrictions address different concerns. Both must be respected, and artificial targets should not distort the loss.
Common pitfalls
Do not confuse pre-normalized and post-normalized blocks, infer causality from residual connections, or mistake a successful shape check for a trained model. Test mask behavior through controlled input changes and keep padding rules explicit.
Summary
Transformer blocks combine cross-position attention with position-wise nonlinear transformations, normalization, and residual paths. Correct shapes and masks define the computation; training objectives and evaluation establish whether that computation learns useful behavior.