Learn
Architecture

What is a Transformer architecture in AI?

The short answer

A transformer is a neural network built from repeated blocks that combine self-attention with a small per-token feed-forward network, wrapped in residual connections and normalisation. Every token is processed in parallel and can pull information from any earlier token, which is why the design trains efficiently on GPUs and scales to billions of parameters.

On this page

The block, end to end

A decoder-only transformer takes a sequence of token IDs, looks each one up in an embedding table, adds position information, and pushes the resulting vectors through N identical blocks. Each block does two things: tokens exchange information through attention, then each token is transformed on its own by a feed-forward network. A final normalisation and a linear projection to the vocabulary produce one score per possible next token at every position.

Written as equations, the skeleton is short. Start with x0 = Embed(tokens) + Pos. For each layer, x = x + Attn(Norm(x)), then x = x + FFN(Norm(x)). Finish with logits = Unembed(Norm(x)). Everything else in a real implementation - dropout, attention masks, rotary embeddings, tensor-parallel splits - is scaffolding around those four lines. The stability of this recipe is the reason a 2017 design still describes essentially every frontier language model in 2026.

Self-attention in concrete terms

Each token vector is projected three ways: a query, a key, and a value. A token's query is compared with every key it is allowed to see, producing a score per pair. Scores are divided by the square root of the head dimension, passed through a softmax so they sum to one, and used as weights to average the corresponding values. In matrix form over a whole sequence: Attention(Q, K, V) = softmax(QK^T / sqrt(d_k) + M) * V, where M is zero for allowed positions and negative infinity for masked ones.

The causal mask M is the piece that makes training on raw text possible. Position t may only attend to positions up to and including t, so the prediction at every position is a genuine next-token prediction, and all positions are computed at once. A batch of 8 sequences of 4,096 tokens yields 32,768 independent loss terms from one forward pass, which is why transformers use GPUs far better than recurrent networks did.

Multi-head attention runs h of these operations in parallel with head width d_model / h, concatenates the results, and mixes them with an output projection. The split matters: different heads learn different jobs. Some track the previous token, some match brackets and quotes, some implement induction - finding a token that followed the same prefix earlier in the context and copying what came after it. Interpretability work keeps finding human-nameable circuits built out of exactly these pieces.

The feed-forward network

After attention, each position passes through a small two-layer network applied independently - no interaction between positions at all. The classic form is W2 * activation(W1 * x), with the hidden width d_ff set to four times d_model. Modern models usually use SwiGLU, which needs three matrices and a hidden width of about 8/3 * d_model to keep the parameter count equal.

This part is best understood as a key-value memory. The rows of the first matrix act as keys that fire on particular input patterns, and the rows of the second act as the values written back when they fire. Factual associations - capital cities, chemical symbols, idioms - concentrate here, which is why the feed-forward block holds roughly two-thirds of the parameters in a dense model and why mixture-of-experts architectures scale exactly this component.

A concrete comparison for a 7B-class model with d_model = 4,096: attention costs 4 x 4,096^2 ~ 67M parameters per layer, while a SwiGLU feed-forward with d_ff = 11,008 costs 3 x 4,096 x 11,008 ~ 135M. Multiply by 32 layers and add the embedding table and you land near 6.7B.

Residual stream and normalisation

Every block reads from and writes to a shared per-token vector called the residual stream. Layers add their output to it rather than replacing it, so information written at layer 3 is still available at layer 30 unless something overwrites it. This is why you can attach a classifier to an intermediate layer and get a sensible answer, and why the logit lens - projecting intermediate states straight to vocabulary scores - shows predictions sharpening gradually across depth.

Normalisation placement matters more than it looks. The original paper normalised after each sub-layer (post-norm), which needed careful learning-rate warmup to avoid divergence at depth. Nearly all modern models normalise before each sub-layer (pre-norm): x + Sublayer(Norm(x)). Gradients then flow through the residual path almost untouched, so very deep stacks train without drama. The price is a final normalisation before the unembedding and a slightly different loss landscape, which is a trade almost everyone now accepts.

Why it replaced recurrent networks

  • Sequence positions are processed in parallel; an RNN must step through time serially and cannot fill a GPU.
  • The path between any two tokens is one attention hop, not n recurrent steps, so long-range dependencies are easier to learn.
  • Compute per token is fixed regardless of context, with no hidden state acting as a fixed-width bottleneck.
  • The same block handles text, code, audio frames and image patches - anything that can be turned into a sequence of vectors.
  • Loss is computed at every position rather than only at the end, giving far more learning signal per sample.
  • Scaling behaved predictably: more layers, more width and more data produced smooth, forecastable loss improvements.

Three shapes of transformer

Encoder-only models such as BERT attend in both directions and are trained with masked-token prediction. They are excellent at classification, tagging and producing embeddings for retrieval, but they cannot generate text incrementally. Encoder-decoder models such as T5 and Whisper keep a bidirectional encoder and a causal decoder, which suits translation and speech recognition where the input is fully available before output begins.

Decoder-only models won the chat era for unglamorous reasons: one objective (next token), one architecture for every task expressible as text, clean incremental inference with a key-value cache, and no need to decide in advance which parts of the input the model may see. When in doubt about which shape a new model uses, look at the attention mask - if it is lower-triangular, it is causal.

What training actually optimises

Training is next-token prediction measured with cross-entropy. For each position the model produces a probability distribution over the vocabulary, and the loss is the negative log probability assigned to the token that actually came next. Averaged over a batch, that single number drives everything: a well-trained model assigns maybe 1.7 nats to typical English text, which corresponds to a perplexity near 5.5 - roughly the uncertainty of a careful human guessing the next word.

Because the mask hides future tokens, one forward pass over a 4,096-token sequence yields 4,095 training examples. Gradients from all of them are summed, clipped to a norm near 1.0, and applied with AdamW at a peak learning rate around 3e-4 for a 7B model, warmed up over the first couple of thousand steps and decayed on a cosine schedule to about a tenth of peak. Batch size is measured in tokens, not sequences: 4M tokens per step is common at the 7B scale, assembled from many micro-batches through gradient accumulation.

Two details cause most training failures. First, loss spikes usually trace to a bad data batch - duplicated documents, malformed markup, or a learning rate that is too high for the depth. Second, the objective rewards confident guesses, so models calibrate poorly out of the box; a model that says it is 95% sure is often right only 70% of the time. Both are properties of this loss, not of the transformer block, and both are addressed in post-training rather than architecture.

A parameter and compute budget you can check

Two rules of thumb make hardware conversations concrete. Training compute is about 6ND floating-point operations for N parameters and D training tokens: two for the forward pass and four for the backward pass. Inference is about 2N operations per generated token, plus attention work that grows with context.

Take a 7B model trained on 2 trillion tokens: 6 x 7e9 x 2e12 = 8.4e22 FLOPs. An H100 sustains perhaps 400 TFLOP/s in bf16 at a realistic 40% model-FLOPs utilisation, so the run takes 8.4e22 / 4e14 ~ 2.1e8 seconds, or about 58,000 GPU-hours - 6.6 GPU-years, roughly 100 GPUs for three weeks. At $2 per GPU-hour that is around $116,000 of compute, before any failed runs, which is why a 30% waste in tokenization or data ordering is expensive.

Inference arithmetic is different and often counter-intuitive. Generating one token from a 7B model requires reading 14 GB of weights; at 3 TB/s of memory bandwidth that is under 5 milliseconds of pure weight traffic, so a single stream tops out near 200 tokens per second no matter how fast the matrix units are. Batch 32 sequences and the same weight read serves 32 tokens, pushing throughput up by an order of magnitude while per-token latency barely moves. This single fact explains most of the design of serving systems.

What it costs

Attention work grows with the square of sequence length: roughly 2 * n^2 * d multiply-adds per layer for the score and value products, against 2 * n * d * d_ff for the feed-forward. At 4K tokens attention is a modest slice of total compute; at 128K it dominates, which is what motivated sliding-window attention, grouped-query attention and latent-attention variants.

Weight memory is simple: P parameters x bytes per parameter. A 7B model is 14 GB in fp16, 7 GB in int8 and about 3.5 GB in 4-bit. The key-value cache is the part people forget: 2 * layers * kv_heads * head_dim * tokens * batch * bytes. For a 32-layer model with 32 key-value heads of width 128 at 4,096 tokens in fp16, that is 512 KiB per token, or 2 GiB for a single sequence - larger than many people expect and the reason serving engines page and share it.

Inference splits into two phases with opposite bottlenecks. Prefill processes the whole prompt in parallel and is compute-bound. Decode generates one token at a time and must read every weight for each token, so it is memory-bandwidth-bound: a single-stream generation typically reaches a few percent of the hardware's arithmetic peak. Batching is what recovers throughput, because the same weight read then serves many sequences.

How to read a model card

Six numbers tell you most of what you need: parameter count, layer count, d_model, attention head count, key-value head count and vocabulary size, plus the context window and precision. From those you can compute weight memory, key-value cache per token, and roughly the compute per generated token.

Worked example: 32 layers, d_model 4,096, 32 query heads, 8 key-value heads, 128K vocabulary, 8,192-token context, fp16. Weights ~ 14 GB. Key-value cache per token = 2 x 32 x 8 x 128 x 2 bytes = 128 KiB, so an 8K sequence needs 1 GiB and 16 concurrent users need 16 GiB on top of the weights. That arithmetic decides your GPU count long before any benchmark does.

Common mistakes

  • Equating parameter count with capability. Training tokens, data quality and post-training matter at least as much; compute-optimal training sits near 20 tokens per parameter.
  • Treating the advertised context window as usable memory. Recall is strongest at the start and end of a long prompt and weakest in the middle.
  • Forgetting that attention without position information is permutation-invariant - two sentences with the same words in a different order would look identical.
  • Budgeting GPU memory from weights alone and then running out during the first long request because of the key-value cache.
  • Assuming a larger model is always slower. A small model buried under a 100K-token context can be slower per token than a larger model at 2K.
  • Reading benchmark scores without checking the prompt format, since chat templates and tool-call syntax change results substantially.

Where the design is going

Mixture-of-experts replaces the dense feed-forward with many expert networks and a router that sends each token to a couple of them. Total parameters grow while compute per token stays roughly flat: Mixtral 8x7B holds 46.7B parameters but activates about 12.9B per token. The block diagram is unchanged; only the feed-forward is widened and gated.

Attention itself keeps being re-engineered - sliding-window layers interleaved with global ones, linear and state-space hybrids, multi-head latent attention that compresses keys and values. The goal in every case is the same: keep the quality of full attention while cutting the n^2 compute and the linear memory growth. Six years of alternatives have not dislodged the block; they have made its expensive part cheaper.

Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.