Skip to main content
LearnMLAcademy
Intermediate10 min read

Transformer Architecture & LLM Model Families

Understand Transformer multi-head self-attention mechanics and QKV math, with token walkthroughs, prompt design tasks, and retrieval exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

How can one token use information from another?

Read: “The animal didn't cross the street because it was tired.” To interpret “it”, information from earlier words matters. Treating every position as equally useful would be wasteful.

Attention is a learned mechanism that lets each position assign different weights to other allowed positions and combine their information.

Attention asks: which earlier words are useful here?

Theanimaldidn'tcrossthestreetbecauseitwastired
Query: what information does “it” need?
Keys: what does each position offer for matching?
Values: what information is passed forward when relevant?
For the pronoun “it”, useful information may come from “animal” and “tired”. Attention learns weighted connections; it is not human understanding.

The sentence The animal didn't cross the street because it was tired is shown with stronger conceptual emphasis on the pronoun it and the words animal and tired.

Query, Key and Value — without the mystery

Q, K and V in plain English

Q, K and V in plain English
VectorBeginner mental modelRole
Query (Q)What information am I looking for?Used to score how relevant other positions are
Key (K)What information do I offer for matching?Compared with the Query
Value (V)What information should I pass forward?Mixed according to the attention weights

From matching scores to attention weights

  1. Compare Query with Keys

    A dot product gives larger scores to stronger matches in the learned space.

  2. Scale the scores

    Divide by √dₖ, where dₖ is the Key-vector dimension, to keep large dot products from making softmax excessively sharp.

  3. Normalize with softmax

    Convert the scores into non-negative weights that sum to 1 across the allowed positions.

  4. Mix the Values

    Multiply each Value vector by its attention weight and add the results.

Attention(Q, K, V) = softmax(QKᵀ / √dₖ) V
Read it as: compare Q with K, scale, turn the scores into weights, then use those weights to combine V.

A tiny weighted-value calculation

Suppose one query produces attention weights 0.731 and 0.269 over two positions. Their Value vectors are [1, 0] and [0, 2].

0.731 × [1, 0] = [0.731, 0]

0.269 × [0, 2] = [0, 0.538]

Output = [0.731, 0.538]

The result is not a label. It is a new representation containing a weighted mixture of information from the two Value vectors.

The weighted result is a new representation for a token, not the final generated word. The surrounding Transformer layers process that representation further; the architecture comparison below explains which positions are allowed to exchange information.

One attention operation is not the whole Transformer

Inside a Transformer block

Inside a Transformer block
PartWhy it is there
Multi-head attentionRuns several learned attention projections so the block can represent different useful relationships
Feed-forward networkApplies a learned nonlinear transformation independently at each position
Residual connectionsCarry earlier information around sublayers and support deep optimization
NormalizationHelps keep activations numerically stable as many blocks are stacked

Multiple heads are useful, but a head is not guaranteed to have one fixed human-readable job such as “grammar head”.

Three common Transformer families

Architecture family and typical use

Architecture family and typical use
FamilyInformation flowTypical fit
Encoder-onlyReads the available input in both directionsUnderstanding/classification/representations
Decoder-onlyUses causal visibility so a position cannot see future target tokensAutoregressive text generation
Encoder-decoderEncoder reads the source; decoder generates the targetTasks such as translation or transformation

Why the next lesson matters

The Transformer can now produce scores for possible next tokens. How does the system choose which token to actually generate?

Text Generation & Decoding →

Summary / Key Takeaways

  • Attention lets each token position weight information from other allowed positions.
  • Query supports looking for a match, Key supports matching, and Value carries the information to mix.
  • Scaled dot-product attention turns Q–K scores into weights and uses them to combine V.
  • Multi-head attention, feed-forward layers, residual paths, and normalization form a Transformer block.
  • Decoder-only Transformers use causal masking and are a natural fit for next-token generation.
  • The Transformer produces useful contextual representations; the next lesson explains how scores become actual generated tokens.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Transformer Architecture & LLM Model Families"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What is the most accurate beginner interpretation of Query, Key, and Value?
Question 2 of 5numerical/formula
The toy attention weights are 0.731 and 0.269, with value vectors [1,0] and [0,2]. What output does the weighted sum produce?
Question 3 of 5interpretation
Why divide QKᵀ by √dₖ before softmax?
Question 4 of 5practical selection
Which Transformer family is the most natural fit for autoregressive text generation?
Question 5 of 5debugging/diagnostic
During causal language-model training, a decoder can attend to the correct future answer tokens. What is wrong?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the most accurate beginner interpretation of Query, Key, and Value?▼

Correct Answer: Query expresses what a position looks for, Key supports matching, and Value carries information to be mixed

Q/K determine matching weights, while V contains the information combined according to those weights.

2The toy attention weights are 0.731 and 0.269, with value vectors [1,0] and [0,2]. What output does the weighted sum produce?▼

Correct Answer: [0.731, 0.538]

`0.731×[1,0] + 0.269×[0,2] = [0.731,0.538]`.

3Why divide QKᵀ by √dₖ before softmax?▼

Correct Answer: To prevent larger-dimensional dot products from making softmax excessively sharp

Scaling moderates dot-product magnitude and stabilizes the softmax distribution.

4Which Transformer family is the most natural fit for autoregressive text generation?▼

Correct Answer: Decoder-only with causal visibility

Decoder-only causal models are designed to predict the next token without seeing future target tokens.

5During causal language-model training, a decoder can attend to the correct future answer tokens. What is wrong?▼

Correct Answer: The causal mask is missing or incorrect

Causal masking exists specifically to prevent future-token leakage.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next