Transformers Under the Hood: Blocks That Scale
The Transformer is not one idea but a small set of choices that happen to compose well: parallel attention, a wide feed-forward block, residual connections that keep gradients alive, and normalization that keeps activations sane. Learn to read those four pieces and you can decode almost any modern architecture description, because most published models are the same skeleton with different widths, depths, and routing rules. This lesson walks the skeleton in the order data actually flows through it.
The Residual Stream Every Layer Writes To
Picture the forward pass as a shared accumulator rather than a pipeline. An embedding vector enters at the bottom, and each block reads it, computes a correction, and adds that correction back. The stream therefore carries information forward untouched for as long as a layer chooses not to modify it, which is why a 96-layer model can still route the original token identity to the top. Attention layers mix information across positions; feed-forward layers transform each position independently.
This design has two consequences you will feel in practice. First, gradients flow straight down the accumulator, so deep stacks train without the vanishing problems that plagued recurrent networks. Second, individual heads can specialize â one head tracks the previous token, another matches a closing bracket â because writing a small delta is cheaper than rewriting the whole vector. When a model misbehaves, researchers probe the stream to find which layer started the damage, and interventions at a single layer can redirect the output.
What One Block Actually Computes
A standard block is deterministic and short to write: normalize, attend, add; normalize, feed forward, add. Layer normalization stabilizes the scale before the sub-layer runs, and the residual addition preserves what was already there. The feed-forward network is usually the parameter heavyweight â a hidden dimension roughly four times the model width, applied token by token â and it is where much of the model's factual storage is believed to live.
import torch
import torch.nn as nn
class Block(nn.Module):
def __init__(self, width, heads, ff_mult=4, dropout=0.0):
super().__init__()
self.norm1 = nn.LayerNorm(width)
self.attn = nn.MultiheadAttention(width, heads, dropout=dropout, batch_first=True)
self.norm2 = nn.LayerNorm(width)
self.ff = nn.Sequential(
nn.Linear(width, width * ff_mult),
nn.GELU(),
nn.Linear(width * ff_mult, width),
nn.Dropout(dropout),
)
def forward(self, x, causal_mask=None):
h = self.norm1(x)
attn_out, _ = self.attn(h, h, h, attn_mask=causal_mask, need_weights=False)
x = x + attn_out
return x + self.ff(self.norm2(x))
demo = Block(width=256, heads=8)
tokens = torch.randn(2, 16, 256)
mask = torch.triu(torch.full((16, 16), float("-inf")), diagonal=1)
print(demo(tokens, mask).shape) # torch.Size([2, 16, 256])
Note what is absent: recurrence, convolution, and any operation that forces tokens to be processed in order. That absence is exactly what lets training use every position simultaneously.
Position Information Without Recurrence
Because the block above treats the sequence as a set, the model would be blind to word order without help. The original paper added sinusoidal signals at each index, letting attention recover relative positions from phase differences. Alternatives now include learned absolute embeddings, rotary position embeddings that rotate query and key vectors, and ALiBi biases that decay scores with distance. Whatever the scheme, it must generalize beyond the lengths seen in training or long-context behavior collapses.
import math
import torch
def sinusoidal_positions(length, width, device="cpu"):
pos = torch.arange(length, device=device).unsqueeze(1).float()
dims = torch.arange(0, width, 2, device=device).float()
angles = pos / torch.pow(10000, dims / width)
table = torch.zeros(length, width, device=device)
table[:, 0::2] = torch.sin(angles)
table[:, 1::2] = torch.cos(angles)
return table
print(sinusoidal_positions(8, 64).shape) # torch.Size([8, 64])
for length in (512, 4096, 32768):
print(length, float(sinusoidal_positions(length, 64).abs().max()))
The maxima stay bounded at every length, which is why the scheme transfers to sequences longer than anything in the corpus.
Three Shapes, One Family
The original design paired an encoder with a decoder, but the field quickly specialized. Encoder-only models such as BERT see the whole sequence at once and excel at classification and tagging. Decoder-only models such as the GPT line use causal masking and dominate text generation because next-token prediction aligns naturally with them. Encoder-decoder models such as T5 keep both halves and shine at sequence-to-sequence work like translation and summarization.
| Shape | Masking | Pretraining objective | Best fit |
|---|---|---|---|
| Encoder-only | None, bidirectional | Masked token reconstruction | Classification, tagging, retrieval |
| Decoder-only | Causal, left to right | Next-token prediction | Chat, code, long-form generation |
| Encoder-decoder | Causal decoder, full encoder | Denoising or span corruption | Translation, summarization, parsing |
| Mixture of experts | Causal plus routing | Next-token with sparse layers | Large models under a compute budget |
If you remember only one rule: pick the shape whose visibility pattern matches the task. Giving a classifier causal masking hides half the sentence for no reason; giving a generator bidirectional attention at inference time is impossible.
Hyperparameters and What They Cost
Configuration numbers look dry until you price them. Embedding width sets the compute cost of every linear layer, depth multiplies it, and vocabulary size dominates the output projection â a 128,000-token vocabulary at width 4,096 produces a half-billion-parameter head by itself. Head count matters less than it appears: total attention parameters depend on width, and heads simply subdivide it, so more heads at fixed width means smaller, more numerous views rather than more capacity.
def parameter_budget(width=768, layers=12, vocab=50257, ff=4, heads=12):
per_block = (
4 * width * width * ff # feed-forward pair
+ 4 * width * width # attention projections
+ 4 * width # layer norms and biases
)
body = layers * per_block
embedding = vocab * width
head = vocab * width
total = body + embedding + head
return {"attention_and_ff": body, "embeddings_and_head": embedding,
"total_millions": round(total / 1e6, 1), "heads": heads}
print(parameter_budget())
print(parameter_budget(width=1024, layers=24, vocab=50257))
Doubling width roughly quadruples body parameters while doubling depth only doubles them, which is why teams widen first and deepen second until memory pressure argues otherwise.
Why Parallel Training Changed the Economics
Recurrent networks forced a step-by-step schedule: token t could not start until token t minus one finished. The Transformer removes that dependency, so a graphics processor can lay the whole sequence out as one matrix multiply. Training time then tracks arithmetic throughput instead of sequential latency, and hardware vendors responded by building chips that favor exactly that workload. Scaling laws followed: loss falls as a smooth power law in parameters, data, and compute, which made frontier labs willing to spend nine-figure budgets with predictable returns.
The same property helps inference, up to a point. Prefill â processing the prompt â parallelizes fully, while decode still emits one token at a time. That asymmetry explains why long prompts cost many milliseconds of compute yet return quickly, and why prompt caching is one of the highest-leverage optimizations in serving. It also explains the shape of the ecosystem: hardware optimized for training favors big matmuls, while hardware optimized for decode favors memory bandwidth, and the two constraints pull model designs in opposite directions.
Reading a Config Before You Trust a Benchmark
Model cards bury the numbers that determine fit: width, depth, head count, vocabulary, context window, and whether the model is dense or routed. Compare those before comparing leaderboard scores, because a 70-billion-parameter dense model and a 400-billion model with 10 percent active parameters make completely different promises about latency and cost. Also check the tokenizer â a vocabulary tuned for one language family silently inflates token counts, and therefore price, for everyone else.
âšī¸A quick sanity check
Common Mistakes
Assuming more attention heads means more capacity
Fix: Capacity scales with model width; heads only partition it, so compare width and parameter count instead
Adding positional embeddings sized only for the training length
Fix: Choose a scheme that extrapolates, and validate on sequences longer than anything you trained on
Copying a config without checking vocabulary size
Fix: The output head can be a third of all parameters; report body and embedding budgets separately
Treating encoder-decoder as a drop-in upgrade for chat
Fix: Causal decoder-only models are what users expect from assistants; reserve encoder-decoder for structured transforms
Key Takeaways
- The residual stream lets every layer add a small correction while preserving information from below
- A block is normalize, attend, add, normalize, feed forward, add â no recurrence anywhere
- Position encodings exist because attention alone is permutation-invariant
- Encoder-only, decoder-only, and encoder-decoder differ mainly in which positions each token may see
- Width multiplies parameters faster than depth, and prefill parallelizes while decode does not