Transformer structure
What makes a transformer
A transformer processes token representations using attention and position-wise neural networks. It is an architecture, not a particular chatbot or a guarantee of correct reasoning. Tokens are pieces of an input sequence, represented by IDs; embeddings map those IDs to vectors. Positions matter because content-only unrestricted self-attention without positional information is permutation-equivariant. Position information can be added to embeddings (as in the original sinusoidal encoding) or incorporated in attention using other schemes. Not every transformer uses the same position scheme.
Encoder, decoder and encoder-decoder
An encoder-only model commonly lets input positions attend in both directions and returns contextual representations for tasks such as classification. A decoder-only language model commonly uses causal self-attention and predicts next-token scores. An encoder-decoder model encodes a source sequence and uses a target decoder with causal self-attention and cross-attention to the source, useful for sequence-to-sequence tasks such as translation. These are common patterns, not universal restrictions; task-specific masks and objectives may differ.
Causal masking and prediction order
A causal mask for a three-position sequence allows row 0 to see column 0; row 1 sees 0 and 1; row 2 sees all three. No position uses a future token. A padding mask is different: it excludes padding keys even if their position would be causally visible. Combine constraints by intersection. Here True means allowed, unlike some framework mask interfaces. With equal allowed scores and scalar values, causal attention reduces to prefix averages; the next example implements only this special case, not learned Q/K/V attention. Nonnegative integer length and small finite values are assumed.
def causal_mask(n): if n < 0: raise ValueError("length must be nonnegative") return [[j <= i for j in range(n)] for i in range(n)]
def prefix_means(values): total = 0 outputs = [] for i, value in enumerate(values, 1): total += value outputs.append(total/i) return outputsprint(causal_mask(3))print(prefix_means([2,4,9]))print(prefix_means([2,4,99])[:2])Read the causal output
The mask is [[True, False, False], [True, True, False], [True, True, True]]. Prefix means of [2,4,9] are [2.0, 3.0, 5.0]. Replacing the future value 9 with 99 leaves the first two outputs [2.0, 3.0] unchanged. This property is necessary for causal attention, but a full model must also avoid future leakage in preprocessing, labels and other layers. During teacher-forced training, target inputs and next-token labels are shifted; inference repeatedly predicts and appends a token.
Multi-head attention and transformer blocks
A head uses its own learned Q/K/V projections to form one attention result. Multiple head outputs are concatenated along their feature dimensions and linearly projected back to the model width. Different heads may capture different patterns but no particular interpretable specialization is guaranteed. A typical block also has a position-wise feed-forward network, residual connections (add a sublayer input back to its output), and normalization. Pre-norm and post-norm are different arrangements; the original architecture used post-norm. The following code isolates the concatenation/projection step using fixed head outputs and no bias; each projection row contains the weights for one output coordinate. It is not a trainable transformer.
def project_heads(heads, projection): joined = [v for head in heads for v in head] if not joined or not projection or any(len(row) != len(joined) for row in projection): raise ValueError("projection rows must match concatenated width") return [sum(x*w for x,w in zip(joined,row)) for row in projection]heads = [[2,4],[1,3]]print(project_heads(heads, [[1,0,1,0],[0,1,0,1]]))# A toy vocabulary head, not a trained model.print(project_heads(heads, [[1,0,0,0],[0,1,0,0],[0,0,1,1]]))From token sequence to logits
The first output [3,7] comes from combining the first and third, then second and fourth concatenated coordinates. The second projection gives toy logits [2,4,4] for a three-token vocabulary; a greedy selection would need a defined tie-breaking policy. In a real language model, contextual vectors from repeated blocks feed a vocabulary projection, then softmax or a decoding procedure determines next-token selection. Logits are scores, not normalized probabilities. A new token changes the context for the next step. A simplified pipeline is token IDs → embeddings and position information → stacked masked attention and feed-forward blocks → contextual vector → vocabulary logits → selected token → append and repeat. No external model was invoked.
Common mistakes and practice
A transformer is not just attention: learned projections, nonlinear layers, normalization and residual paths matter. Causal masking prevents using later positions inside the attention operation, not hallucinations or all data leakage. Standard dense attention computes L×S scores per head, so memory and work can grow quadratically for equal-length self-attention; optimized kernels and alternative architectures change practical behavior. Practice: sketch an encoder-decoder for translation and identify the origin of Q, K and V in cross-attention. Explain why attention weights alone are not a complete explanation. Further implementation and training belong to the LLM Engineering track.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Transformer structure quiz
Apply the attention and transformer mental models.
Which attention pattern is typical of a decoder-only next-token language model?
With a causal mask alone, which zero-based keys can query position 1 see in a three-token sequence?
How does a standard multi-head attention layer combine its head outputs?
In encoder-decoder cross-attention, where do key/value vectors generally originate?
Why does a large attention weight alone not establish a token’s causal effect on a prediction?