S30 Logo
S30 AI Labwww.thes30.com
Back
#45

Transformer Architecture

Hard📝 NLP & TransformersW10 D1

Before You Start

Required knowledge
Attention, embeddings, normalization, and tensor reshaping.
Libraries used
NumPy
Dataset and source
Toy token IDs and generated model tensors, not a pretrained language model.
Expected output
Positional representations, layer normalization, causal attention, feed-forward layers, and a transformer-block forward pass.

Transformer Architecture — Theory & Concepts

Read this before attempting the exercises. This lab builds a minimal Transformer encoder-style block forward pass in NumPy.


1. What this lab is actually teaching

This is not a full language-model training lab. You are implementing one forward-pass block with:

  • ●token embeddings
  • ●sinusoidal positional encoding
  • ●multi-head self-attention
  • ●feed-forward network (FFN)
  • ●residual connections
  • ●Pre-LN layer normalization

So the real goal is to understand:

  • ●how shapes move through the block
  • ●where masking is applied
  • ●how attention and FFN fit together
  • ●why residuals and layer norm stabilize the architecture

2. The block used in this lab: Pre-LN Transformer

Transformer block overview

The lab uses a Pre-LN block:

x
|
v
LayerNorm
|
v
Multi-Head Self-Attention
|
v
Add residual: x1 = x + MHA(LN(x))
|
v
LayerNorm
|
v
Feed-Forward Network
|
v
Add residual: y = x1 + FFN(LN(x1))

That is exactly what you implement in the final task.

Why Pre-LN matters:

  • ●normalization happens before the sublayer
  • ●gradients usually flow more stably in deep stacks
  • ●this is a common modern choice in large transformer models

Important: the lab stops at the block output y. It does not build the final vocabulary projection or training loss.


3. End-to-end data flow inside this lab

Input token ids
      |
      v
Embedding lookup
      |
      v
Add positional encoding
      |
      v
Sequence tensor X with shape (B, T, Dmodel)
      |
      v
Project into Q, K, V
      |
      v
Split into heads
      |
      v
Scaled dot-product attention per head
      |
      v
Merge heads + output projection
      |
      v
Residual connection
      |
      v
Feed-forward network
      |
      v
Residual connection
      |
      v
Block output Y with shape (B, T, Dmodel)

So this lab is really about going from raw token ids to contextualized token representations.


4. Positional encoding

Attention alone is permutation-invariant. If you only gave the model token embeddings, it would not know whether a word came first, last, or in the middle.

Use this contrast:

Sentence A: The dog chased the cat and it started ...
Sentence B: The cat chased the dog and it started ...

Both sentences contain almost the same words, but the order changes who did what. Without positional information, self-attention only sees a bag of token embeddings and loses that word-order structure.

That is why we add positional information:

Positional encoding intuition

Sinusoidal positional encoding intuition

X = token_embedding + positional_encoding

For sinusoidal positional encoding, the standard formulas are:

PE(pos, 2i)   = sin(pos / 10000^(2i / D))
PE(pos, 2i+1) = cos(pos / 10000^(2i / D))

Where:

  • ●pos = token position in the sequence
  • ●i = pair index of the embedding dimension
  • ●D = model width / embedding dimension

So the embedding for "dog" at position 2 is different from the embedding for "dog" at position 5:

input_to_transformer = token_embedding(word) + positional_encoding(position)

That is what lets the model distinguish:

  • ●"dog" appearing before "cat"
  • ●"cat" appearing before "dog"
  • ●"it" appearing later and attending differently depending on the earlier order

In this lab, you implement the classic sinusoidal encoding:

  • ●even dimensions use sin
  • ●odd dimensions use cos
  • ●different dimensions use different frequencies

This lets the model represent order without learning a separate position table.


5. Multi-head self-attention

Instead of one attention computation, the transformer uses several heads in parallel:

Multi-head split and concat

Given input X of shape (B, T, Dmodel):

Q = XWq
K = XWk
V = XWv

Then each of these is reshaped into heads.

Common shapes in this lab:

ObjectShape
X(B, T, Dmodel)
Q, K, V before split(B, T, Dmodel)
Q, K, V after split(B, h, T, Dh)
DhDmodel / h
attention scores(B, h, T, T)
attention weights(B, h, T, T)
per-head output(B, h, T, Dh)
merged output(B, T, Dmodel)

Why multiple heads help:

  • ●different heads can focus on different relationships
  • ●one head may focus on nearby syntax
  • ●another may focus on long-range dependencies
  • ●after merging, the model combines all of those views

6. Masking

Masks tell attention which keys are legal to use.

This lab uses the convention:

1 = keep
0 = mask

The mask is applied before softmax. Masked scores are replaced by a very negative number so their final softmax weight becomes effectively zero.

Two mask types appear in the lab:

Causal mask

Used when a token should not see future tokens. This is standard for decoder-style autoregressive generation.

query position t can only attend to keys <= t

Padding mask

Used when sequences in a batch have different true lengths. Padding tokens should not act like real keys.

Why both appear here:

  • ●an encoder usually uses bidirectional attention
  • ●a decoder usually uses causal attention
  • ●but the implementation machinery should support both

So even though this lab builds an encoder-style block, it still teaches general masking correctly.


7. Feed-forward network (FFN)

After attention mixes information across tokens, the FFN transforms each token independently.

The lab uses:

FFN(x) = GELU(xW1 + b1)W2 + b2

Interpretation:

  • ●first expand the feature dimension from Dmodel to Dff
  • ●apply a nonlinearity
  • ●project back to Dmodel

So attention handles token-to-token interaction, while the FFN handles richer per-token feature transformation.


8. Encoder vs decoder context

ComponentAttention visibilityTypical use
Encodercan see all tokensBERT, classification, retrieval
Decodercan see only past tokensGPT, text generation
Encoder-decoderdecoder also attends to encoder outputstranslation, T5

This lab focuses on the block mechanics, not on building a full BERT or GPT stack.


9. Strategic picture

The important takeaway is not just the formulas. It is the division of roles:

  • ●embeddings represent tokens
  • ●positional encoding injects order
  • ●self-attention mixes information across positions
  • ●multi-head structure gives multiple parallel views
  • ●FFN refines each token representation
  • ●residuals and Pre-LN keep deep stacks trainable

If you understand that pipeline and can track the shapes cleanly, you understand the core transformer block.


Now switch to the Exercise tab. In this lab, shape correctness, mask correctness, and the Pre-LN ordering matter more than memorizing code.

Ready to practice?

Python 3 — Notebook
0/10 solvedSubstack Notes
1
Dataset & Setup

Transformer Architecture — Student Lab

Implement a minimal Transformer encoder-style block forward pass in NumPy:

  • ●embeddings + sinusoidal positional encoding
  • ●multi-head self-attention (from scratch)
  • ●FFN
  • ●residuals + layer norm (Pre-LN)

Focus: shapes, masking, and correctness.

Section 0 — Utilities (softmax, LayerNorm, activation)

Loading editor...
1

Utilities (softmax, LayerNorm, activation)

2
Section 0 — Utilities (softmax, LayerNorm, activation)

Section 0 — Utilities (softmax, LayerNorm, activation)

Loading editor...
2

Embeddings + positional encoding

3
Implement sinusoidal positional encoding `pos_enc(T, D)` returning (T,D).
1

Section 1 — Embeddings + positional encoding

Task 1.1

Implement sinusoidal positional encoding pos_enc(T, D) returning (T,D). Use the standard formula with sin/cos on even/odd dims.

PE(pos, 2i) = sin(pos / 10000^(2i / D)) PE(pos, 2i+1) = cos(pos / 10000^(2i / D))

Here pos is the token position, i is the dimension-pair index, and D is the embedding size.

Loading editor...
4
Implement token embedding lookup.
1

Task 1.2

Implement token embedding lookup. Given tokens (B,T) and embedding table E (V,D), return X (B,T,D).

Loading editor...
3

Multi-head self-attention

5
Implement masks:
2

Section 2 — Multi-head self-attention

Task 2.1

Implement masks:

  • ●causal_mask(T) -> (1, 1, T, T)
  • ●padding_mask(lengths, T) -> (B, 1, 1, T) Mask convention: 1=keep, 0=mask.
Loading editor...
6
Implement head split/merge utilities.
2

Task 2.2

Implement head split/merge utilities.

Loading editor...
7
Implement scaled dot-product attention over heads.
3

Task 2.3

Implement scaled dot-product attention over heads. Inputs: Q,K,V each shape (B,h,T,Dh). Mask shape should be broadcastable to (B,h,T,T). Return (O,A) where O=(B,h,T,Dh), A=(B,h,T,T).

Loading editor...
8
Implement a multi-head self-attention forward pass:
2

Task 2.4

Implement a multi-head self-attention forward pass:

  • ●project Q,K,V with Wq,Wk,Wv
  • ●split into heads
  • ●apply attention
  • ●merge heads
  • ●output projection Wo Return (Y, A).
Loading editor...
4

Feed-forward network (FFN)

9
Implement FFN forward: `FFN(x) = (gelu(x W1 + b1)) W2 + b2`.
1

Section 3 — Feed-forward network (FFN)

Task 3.1

Implement FFN forward: FFN(x) = (gelu(x W1 + b1)) W2 + b2.

Loading editor...
5

Transformer block (Pre-LN)

10
Implement `transformer_block_forward(x, params, n_heads, attn_mask=None)` returning (y, attn_weights).
3

Section 4 — Transformer block (Pre-LN)

Pre-LN block:

  1. ●x1 = x + MHA(LN(x))
  2. ●x2 = x1 + FFN(LN(x1))

Here x should already contain token embeddings plus positional encodings.

Task 4.1

Implement transformer_block_forward(x, params, n_heads, attn_mask=None) returning (y, attn_weights).

Loading editor...

Need help? Share feedback