LLM_log #003 Understanding Large Language Models – Transformers illustrative explanation

LLM_log #003 Understanding Large Language Models – Transformers illustrative explanation

๐Ÿš€ Understanding Large Language Models: A Complete Visual Guide

๐ŸŽฏ What You’ll Learn

Large Language Models like GPT-4, Claude, and Llama have transformed how we interact with AI, but understanding what actually happens when you type “The cat sat on the” and the model predicts “mat” can feel like opening a black box.

In this comprehensive guide, we’ll demystify the entire process by following a single example through every step of a Transformer’s architecture. You’ll learn exactly how text becomes numbers, how those numbers flow through 12 sequential processing blocks, and how mathematical operations like attention and matrix multiplication work together to generate intelligent predictions.

We’ll use GPT-2 as our reference model (117 million parameters, 768 dimensions, 12 Transformer blocks) because it’s well-documented and represents the core architecture used in modern LLMs.

Tutorial Overview

  1. The Three Main Components – Tokenizer, Transformer Stack, and Language Modeling Head
  2. The Forward Pass – How text flows through the model to generate predictions
  3. Positional Encodings – Teaching the model about word order
  4. Inside Transformer Blocks – Self-attention and feedforward networks
  5. The Feedforward Network – Where 48% of parameters live
  6. Self-Attention in Action – How context influences predictions
  7. Mathematical Deep Dive – Real numbers through attention
  8. Multi-Head Attention – Why we split into 12 parallel heads

1. The Three Main Components

When you ask ChatGPT a question or have Claude write code for you, your text goes through three major processing stages. Understanding this high-level architecture is essential before we dive into the details.

Every Transformer LLM follows the same basic pipeline: Tokenizer โ†’ Transformer Stack โ†’ LM Head

Figure 3-4: The Three Main Components of a Transformer LLM

Input Text
“The cat sat on the”

โ–ผ

1
TOKENIZER
โ€ข Breaks text into tokens
โ€ข Converts tokens to token IDs
“The” โ†’ 464
” cat” โ†’ 3857
” sat” โ†’ 3332
” on” โ†’ 319
” the” โ†’ 262

โ–ผ

2
STACK OF TRANSFORMER BLOCKS
Transformer Block 1
โ†“ PROCESSES โ†“
Transformer Block 2
โ‹ฎ
Transformer Block N
(e.g., 32 blocks)
โ€ข Processes token representations
โ€ข Each block refines understanding

โ–ผ

3
LM HEAD
Language Modeling Head
โ€ข Converts final representation to probabilities
โ€ข Scores EVERY token in vocabulary
โ€ข Predicts most likely next token
50,000 probability scores โ†’
One selected token

โ–ผ

Output: Next Token
“mat”
(Most probable next token)

Complete output:
“The cat sat on the mat

๐Ÿ’ก Key Insight
Tokenizer โ†’ Entry point (text to numbers)
Transformer Stack โ†’ The “brain” (heavy processing)
LM Head โ†’ Exit point (numbers to prediction)
๐Ÿ’ก Why This Architecture?

The three-component design elegantly separates concerns. The tokenizer handles text-to-numbers conversion, the Transformer stack does the computational heavy lifting, and the LM Head converts refined representations back into probabilities over words.

๐Ÿ”ด Critical Point: Everything is Numbers

By the time text reaches the Transformer blocks, it’s already converted into dense vectors of 768 numbers each. The model never sees actual words after tokenization – only numerical representations.


2. The Forward Pass

Let’s trace exactly what happens to “The cat sat on the” as it flows through the model.

GPT-2 Specifications

  • Vocabulary: 50,257 tokens
  • Embedding dimension: 768
  • Number of blocks: 12
  • Context window: 1,024 tokens
  • Total parameters: ~117 million

Step 1: Tokenization

Figure 3-5: Tokenizer Vocabulary & Token Embeddings

Our Example
“The cat sat on the”

Token Vocabulary
Token ID Token
0 !
1
262 the
319 on
464 The
3332 sat
3857 cat
50,000 Zyzzyva
Total: 50,000 tokens

Token Embeddings
Each token ID maps to a vector
(e.g., 3,072 dimensions)
ID 0:
[0.23, -0.45, …, 0.89]
ID 1:
[-0.11, 0.78, …, 0.23]
ID 262:
[0.12, 0.56, -0.89, …, 0.34]
โ† “the”
ID 319:
[0.67, -0.34, 0.12, …, -0.56]
โ† “on”
ID 464:
[0.45, 0.23, -0.67, …, 0.12]
โ† “The”
ID 3332:
[-0.89, 0.45, 0.23, …, 0.78]
โ† “sat”
ID 3857:
[-0.23, 0.89, 0.34, …, -0.45]
โ† “cat”
ID 50,000:
[0.34, 0.56, …, 0.67]

๐Ÿ“ Transformation Flow

Step 1: Text Input
“The cat sat on the”

โ–ผ

Step 2: Tokenization
“The”
” cat”
” sat”
” on”
” the”

โ–ผ

Step 3: Token IDs
[464, 3857, 3332, 319, 262]

โ–ผ

Step 4: Each ID โ†’ Embedding Vector
464 โ†’ [0.45, 0.23, -0.67, …, 0.12] โ† 3,072 numbers
3857 โ†’ [-0.23, 0.89, 0.34, …, -0.45]
3332 โ†’ [-0.89, 0.45, 0.23, …, 0.78]

๐Ÿ’ก Key Points
โ€ข Vocabulary size: Typically 32K – 100K+ tokens
โ€ข Unique IDs: Each token has a numeric identifier
โ€ข Dense vectors: Each ID maps to 1000s of dimensions (e.g., 3072)
โ€ข Learned representations: Trained to capture semantic meaning
๐Ÿ”ด Embeddings Are NOT Universal

The embedding for “cat” in GPT-2 is completely different from “cat” in GPT-3 or Claude. Each model learns its own embeddings during training. You cannot transfer embeddings between models.

Step 2: Through Transformer Stack

Figure 3-6: Complete Forward Pass & Probability Distribution

Input Text
“The cat sat on the”

โ–ผ

TOKENIZER
The
cat
sat
on
the
โ†“ Token IDs: [464, 3857, 3332, 319, 262]

โ–ผ

STACK OF TRANSFORMER BLOCKS
Each token flows through its own processing stream:

464
โ†“
3857
โ†“
3332
โ†“
319
โ†“
262
โ†“
LAST
Block 1 โ†’ Block 2 โ†’ … โ†’ Block 32
โœ“ All 5 tokens processed in parallel
โœ“ Only LAST position (“the”) used for prediction

โ–ผ

LM HEAD
Outputs probability for EVERY token in vocabulary (e.g., 50,000 tokens)

Top Candidates:
Token Probability Visual
! 0.01%
0.02%
mat 45% ๐Ÿ‘‘
HIGHEST
floor 18%
couch 12%
rug 8%
chair 5%
12% (49,995 other tokens)
All probabilities sum to 100%

โ–ผ

Selected Output Token
“mat”
Complete: “The cat sat on the mat

๐Ÿ’ก Key Insights
1. Parallel Processing: All 5 tokens flow through simultaneously
2. Last Position Matters: Only output of “the” position used for prediction
3. Full Distribution: Model scores ALL 50,000 tokens
4. Highest Score Wins: “mat” (45%) is most likely next token
๐Ÿ’ก Parallel Processing

All 5 tokens process in parallel through each block. They don’t go one-by-one – imagine 5 separate streams flowing simultaneously. Each stream can “look at” the others (that’s attention), but all move forward together.

Step 3: Decoding Strategies

Figure 3-7: Choosing a Token – Decoding Strategies

Prompt
“The cat sat on the”

โ–ผ

Model Output: Token Probabilities
Token Probability Visual
mat 45%
๐ŸŽฏ HIGHEST
floor 18%
couch 12%
rug 8%
chair 5%
12% (49,995 other tokens)

โ–ผ

How do we pick the output token?

๐ŸŽฏ Greedy Decoding
How it works:
Always pick the token with the highest probability
Decision:
Pick “mat” (45%)
Characteristics:
โœ… Deterministic (same every time)
โœ… Fast and simple
โŒ Can be repetitive
โŒ Less creative
Temperature = 0

๐ŸŽฒ Sampling
How it works:
Pick randomly based on probabilities
Possible outcomes:
“mat” (45% chance)
“floor” (18% chance)
“couch” (12% chance)
etc…
Characteristics:
โœ… More creative/diverse
โœ… Different each time
โš ๏ธ Can be unpredictable
โš ๏ธ May pick unlikely tokens
Temperature > 0

โ–ผ

๐Ÿ“ Example Outputs

๐ŸŽฏ Greedy Decoding (Always the same):
“The cat sat on the mat

๐ŸŽฒ Sampling (Different each time):
Run 1:
“… on the mat
Run 2:
“… on the floor
Run 3:
“… on the couch
Run 4:
“… on the rug
Run 5:
“… on the chair

๐Ÿš€ Advanced Sampling Strategies
Top-k Sampling
Only sample from the top k tokens (e.g., k=3)
Sample from: “mat”, “floor”, “couch”
Top-p (Nucleus) Sampling
Sample from tokens whose cumulative probability is p (e.g., p=0.8)
Sample from tokens until reaching 80% cumulative probability

๐Ÿ’ก Key Takeaways
1. Probability โ‰  Certainty: Model gives scores, decoding strategy picks token
2. Greedy = Predictable: Always picks highest probability (deterministic)
3. Sampling = Creative: Picks based on probabilities (varied output)
4. Temperature: Controls randomness (0 = greedy, higher = more random)
5. Real LLMs: Often use advanced strategies (top-k, top-p) for best results

3. Positional Encodings

There’s a critical problem: the model has no idea about word order. “The cat chased the dog” would look identical to “The dog chased the cat” without position information.

Figure 3-8: Positional Encodings – Teaching the Model About Order

โš ๏ธ The Problem
Without positional information, these sentences would look identical to the model:โ€ข “The cat chased the dog” โ‰  “The dog chased the cat
โ€ข “You love me” โ‰  “You love me?”

Word order matters in language! The model must know which token comes first, second, third, etc.

โœ… The Solution: Positional Encodings
Add position information to each token’s embedding:
Final Embedding = Token Embedding + Position EncodingThis way, the model can distinguish between “cat at position 2” vs “cat at position 5”

How Positional Encodings Work

Example: “The cat sat on the”

Token
“The”
+

Position
1
=

Final Embedding
“The” at position 1

Token
“cat”
+
Position
2
=
Final Embedding
“cat” at position 2

Token
“sat”
+
Position
3
=
Final Embedding
“sat” at position 3

โ‹ฎ

Two Types of Positional Encodings

1. Learned Positional Embeddings
Used in GPT-2:
โ€ข Separate embedding table for positions
โ€ข Position 0 โ†’ vector [0.23, -0.45, …]
โ€ข Position 1 โ†’ vector [0.12, 0.67, …]
โ€ข …
โ€ข Position 1023 โ†’ vector [-0.34, 0.89, …]
Pros: Simple, learned during training
Cons: Fixed maximum length (1024 for GPT-2)
Parameters: 1,024 ร— 768 = 786,432

2. Sinusoidal (RoPE)
Used in Modern Models:
โ€ข Mathematical function, not learned
โ€ข sin/cos waves of different frequencies
โ€ข Applied during attention computation
โ€ข Can handle any length!
Pros: No parameters, any length
Cons: More complex implementation
Parameters: 0 (computed)

How Vectors Are Combined (GPT-2 Example)
Token “cat” (ID 3857) embedding:
[0.12, -0.45, 0.67, …, 0.23]
(768 dimensions)
+
Position 2 encoding:
[0.08, 0.23, -0.12, …, 0.45]
(768 dimensions)
=
Final input to Transformer:
[0.20, -0.22, 0.55, …, 0.68]
(768 dimensions)
Element-wise addition: Each dimension adds: 0.12 + 0.08 = 0.20, -0.45 + 0.23 = -0.22, etc.

Where Positional Information Is Added
Input Text
“The cat sat on the”
โ–ผ
Tokenization
โ†’ Token IDs
โ–ผ
Token Embeddings
Lookup in embedding table
โ–ผ
โญ ADD POSITIONAL ENCODINGS โญ
Token embedding + Position encoding
โ–ผ
Into Transformer Blocks
Ready for attention & feedforward
Important: Positional info is added ONCE at the start, before any Transformer blocks. It’s not added again inside the blocks.

๐Ÿ’ก Key Insights
1. Essential for word order: Without positional info, “dog bites man” = “man bites dog”
2. Added at input: Token embedding + Position encoding = Final embedding
3. Two approaches: Learned (GPT-2) vs Sinusoidal/RoPE (modern models)
4. Context limit: GPT-2 can handle max 1,024 tokens (positions 0-1023)
5. Once and done: Position info flows through the network but isn’t re-added
๐Ÿ’ก When Position Info Is Added

Positional information is added ONCE at the very beginning, right after token embedding lookup. It’s not re-added at each block. The position info flows through the network encoded in the vectors themselves.


4. Inside Transformer Blocks

Now let’s see what happens inside those 12 Transformer blocks.

The Stack

Figure 3-11: Inside the Transformer – Stack of Processing Blocks

Token Embeddings In
5 vectors of 768 dimensions each
(From: “The cat sat on the”)

โ–ผ

STACK OF TRANSFORMER BLOCKS

Transformer Block 1
Self-Attention + Feedforward

โ–ผ

Transformer Block 2
Self-Attention + Feedforward

โ–ผ

โ‹ฎ

โ–ผ

Transformer Block 12
Self-Attention + Feedforward

โ€ข Each block refines token representations
โ€ข Output of one block = Input to next block
โ€ข Example: GPT-2 has 12 blocks

โ–ผ

Processed Representations Out
5 refined vectors of 768 dimensions each
โ†’ Ready for LM Head to predict next token

๐Ÿ’ก Key Insight
The bulk of LLM processing happens in this stack. Each Transformer block progressively refines the representation of each token, incorporating more context and understanding at each layer. Models range from 6 blocks (original Transformer) to 100+ blocks (large modern LLMs).

Real Model Examples:
โ€ข GPT-2: 12 blocks
โ€ข GPT-3: 96 blocks
โ€ข Llama 2: 32-80 blocks (depending on size)
โ€ข Original Transformer: 6 blocks

Inside One Block

Figure 3-12: Inside a Transformer Block

Input Vectors
Token representations from previous block

โ–ผ

TRANSFORMER BLOCK

1๏ธโƒฃ SELF-ATTENTION LAYER
Purpose:
Incorporates contextual information from other tokens in the sequence
How it works:
โ€ข Determines which previous tokens are relevant
โ€ข Combines information from relevant positions
โ€ข Example: Understanding “it” in “The cat sat on the mat because it…”
โ€ข Uses Query, Key, Value matrices

โ–ผ

2๏ธโƒฃ FEEDFORWARD NEURAL NETWORK
Purpose:
Houses the majority of the model’s memorization and processing capacity
What it stores:
โ€ข Learned patterns from training data
โ€ข Factual knowledge (e.g., “Paris” after “France”)
โ€ข Language patterns and relationships
โ€ข Enables both memorization & generalization

โ–ผ

Output Vectors
Refined token representations
โ†’ Passed to next Transformer block

๐Ÿ“Š Division of Labor
Self-Attention
Handles context and relationships between tokens
Feedforward
Stores knowledge and makes predictions

๐Ÿ’ก Key Insight
These two components work together: Self-attention figures out what information is relevant, then feedforward processes that information to make predictions. This combination is repeated in every Transformer block, progressively refining the understanding of the input.

๐Ÿ“ Simple Example:
Input: “The Shawshank”Self-attention: Looks at how “The” and “Shawshank” relate
Feedforward: Recalls from training data that “Redemption” often follows

Result: High probability for “Redemption”


5. The Feedforward Network

Let’s zoom into the feedforward component – it contains 48% of the model’s parameters!

Figure 3-13: Feedforward Neural Network – Where Knowledge Lives

๐Ÿ’ก The Knowledge Store
The feedforward network (FFN) contains 48% of GPT-2’s parameters (~56 million out of 117 million total). This is where the model stores most of its learned knowledge, patterns, and linguistic understanding.

Feedforward Network Architecture (GPT-2)

INPUT
768 dimensions
Output from attention layer

โ–ผ

LINEAR LAYER 1: EXPANSION โฌ†๏ธ
768 โ†’ 3,072 dimensions
4ร— expansion! (768 ร— 4 = 3,072)
Parameters: 768 ร— 3,072 = 2,359,296

โ–ผ

ACTIVATION FUNCTION (GeLU)
Non-linear transformation
Allows network to learn complex patterns
GeLU(x) = x ยท ฮฆ(x)

โ–ผ

LINEAR LAYER 2: COMPRESSION โฌ‡๏ธ
3,072 โ†’ 768 dimensions
Compress back to original size
Parameters: 3,072 ร— 768 = 2,359,296

โ–ผ

OUTPUT
768 dimensions
Ready for next layer

Total FFN Parameters (per block):
2,359,296 + 2,359,296 = 4,718,592
(~4.7 million parameters per Transformer block)

Comparison: Feedforward vs Self-Attention

๐ŸŸก FEEDFORWARD
Parameters: ~4.7M
Purpose: Store knowledge
Operation: Transform each token independently
Expansion: 768 โ†’ 3,072 โ†’ 768
Share: 66% of block params
Largest component!

๐Ÿ”ต SELF-ATTENTION
Parameters: ~2.4M
Purpose: Understand context
Operation: Mix information across tokens
Matrices: Q, K, V, Output (4ร—)
Share: 34% of block params
Lighter weight

Parameter Distribution (per block)
Feedforward
66% (~4.7M)
Attention
34% (~2.4M)

Why Is The Feedforward Network So Large?

1. Knowledge Storage Capacity
The 3,072 hidden dimensions provide enormous space to encode patterns, facts, and linguistic structures learned from billions of training examples. More parameters = more knowledge storage.

2. The 4ร— Expansion Rule
Most Transformers expand by 4ร— (768 โ†’ 3,072). This empirically works well – provides enough capacity without being wasteful. GPT-3 uses 12,288 โ†’ 49,152 (also 4ร—).

3. Non-Linear Transformations
The expansion through activation (GeLU) allows the network to learn complex, non-linear patterns. Linear transformations alone can’t capture the complexity of language.

4. Per-Token Processing
Unlike attention (which mixes tokens), FFN processes each token independently. This allows specialized transformations for each position, requiring more parameters.

๐Ÿ“Š GPT-2 Full Model Breakdown
Component Parameters Percentage
Token Embeddings 38.6M 33%
12 ร— Feedforward Layers 56.6M 48% ๐Ÿ†
12 ร— Attention Layers 28.3M 24%
Other (LayerNorm, etc.) ~1M ~1%
TOTAL ~117M 100%

๐Ÿ’ก Key Takeaway
The feedforward network is the largest component of each Transformer block. Its massive 4ร— expansion (768 โ†’ 3,072 โ†’ 768) provides the capacity needed to store knowledge, learn patterns, and make predictions. This is where most of the model’s “intelligence” is encoded through its 56.6 million learned parameters.
๐Ÿ’ก Where Knowledge Lives

The feedforward network is the model’s primary knowledge store. That 4ร— expansion (768 โ†’ 3,072 โ†’ 768) provides massive capacity to encode patterns learned from billions of training tokens.


6. Self-Attention in Action

Now let’s see attention working with our example sentence.

Figure 3-14: Self-Attention Incorporates Relevant Context

๐Ÿค” Understanding Context
Input: “The cat sat on the”Question: When predicting the next word after “the”, which previous tokens are most relevant?
โ€ข Should we focus on “cat”? ๐Ÿฑ
โ€ข Or on “sat”? ๐Ÿ’บ
โ€ข Or on “on”? ๐Ÿ“

How Self-Attention Solves This

Step 1: Input Tokens
The
cat
sat
on
the

โ–ผ

Step 2: Self-Attention Scoring
Processing token: “the” (position 5)
The model calculates relevance scores for each previous token:
The

5%

cat

25%

sat
HIGHEST

58% ๐ŸŽฏ

on

12%

โ–ผ

Step 3: Enriched Representation
Result:
The representation of “the” now incorporates strong information from “sat” (58% attention weight)The model understands: We need a noun that something sits ON
โ†’ Predicts: “mat” (common object to sit on)

Visual Flow
๐Ÿฑ
cat
25% attention
โ†’
๐Ÿ“
the
current token
โ†
๐Ÿ’บ
sat
58% attention โ˜…

๐Ÿ’ก Key Insight
Self-attention is how the model understands context. When processing “the” (position 5), the model looks back at previous tokens and determines that “sat” is most relevant (58%). This tells the model we need a noun that something sits ON – leading to predictions like “mat”, “floor”, “couch”, etc.

๐ŸŽ“ How the Model Learned This:
During training on billions of sentences, the model saw many examples like:โ€ข “The cat sat on the mat
โ€ข “The dog sat on the floor
โ€ข “She sat on the chair

The model learned that after “sat on the“, common completions are furniture/surfaces. The attention mechanism learned to focus on the verb “sat” to understand what type of word should come next.

๐Ÿ”ด Attention is Learned, Not Designed

The model doesn’t have hardcoded rules saying “attend to ‘sat’ when predicting furniture.” These patterns emerge through training on billions of tokens. The attention weights are learned parameters that get adjusted to minimize prediction error.


7. Mathematical Deep Dive

Let’s follow real numbers through the attention mechanism using a simplified 4D example.

Part 3: Attention Mechanism – Mathematical Deep Dive

Following the numbers through every step

๐Ÿ“ Our Simplified Example
To make the math clear, we’ll use:
โ€ข Sentence: “The cat sat on the”
โ€ข Vector dimension: 4 (instead of GPT-2’s 768)
โ€ข Focus: Processing the last token “the” to predict “mat”
โ€ข Real numbers: Actual matrix multiplications you can verify!

Step 0: Input Embeddings (Start Here)
Each token has a 4-dimensional embedding vector:
Token 1: “The”
xโ‚ = [1.0, 0.5, 0.2, 0.8]
Token 2: “cat”
xโ‚‚ = [0.6, 0.9, 0.3, 0.4]
Token 3: “sat”
xโ‚ƒ = [0.8, 0.3, 0.7, 0.5]
Token 4: “on”
xโ‚„ = [0.4, 0.6, 0.5, 0.9]
Token 5: “the” โฌ… Currently processing
xโ‚… = [0.7, 0.4, 0.6, 0.3]
Matrix form: All input vectors stacked as 5ร—4 matrix (5 tokens, 4 dimensions each)

Step 1: Projection Matrices (Learned Parameters)
The model has learned three 4ร—4 projection matrices during training:

WQ (Query)
[0.5 0.2 0.3 0.1]
[0.1 0.4 0.2 0.5]
[0.3 0.1 0.5 0.2]
[0.2 0.3 0.1 0.4]

WK (Key)
[0.4 0.3 0.2 0.3]
[0.2 0.5 0.1 0.2]
[0.3 0.1 0.4 0.5]
[0.1 0.2 0.3 0.4]

WV (Value)
[0.6 0.1 0.2 0.4]
[0.3 0.5 0.3 0.1]
[0.2 0.3 0.4 0.5]
[0.4 0.2 0.1 0.3]
Important: These matrices are learned during training, not designed by hand. The model adjusts them to capture meaningful patterns in language.

Step 2: Compute Q, K, V Matrices (Matrix Multiplication)
Formula: Q = X ยท WQ, K = X ยท WK, V = X ยท WV

Computing Query for token 5 (“the”):
qโ‚… = xโ‚… ยท WQ
qโ‚… = [0.7, 0.4, 0.6, 0.3] ยท
[0.5 0.2 0.3 0.1]
[0.1 0.4 0.2 0.5]
[0.3 0.1 0.5 0.2]
[0.2 0.3 0.1 0.4]
qโ‚… = [0.59, 0.41, 0.56, 0.43]
Calculation: (0.7ร—0.5 + 0.4ร—0.1 + 0.6ร—0.3 + 0.3ร—0.2) = 0.59, …

Computing Keys for all previous tokens:
kโ‚ = xโ‚ ยท WK = [0.58, 0.55, 0.47, 0.61]
kโ‚‚ = xโ‚‚ ยท WK = [0.52, 0.63, 0.40, 0.57]
kโ‚ƒ = xโ‚ƒ ยท WK = [0.66, 0.56, 0.55, 0.68]
kโ‚„ = xโ‚„ ยท WK = [0.53, 0.58, 0.52, 0.65]

Computing Values for all tokens:
vโ‚ = xโ‚ ยท WV = [0.84, 0.45, 0.41, 0.73]
vโ‚‚ = xโ‚‚ ยท WV = [0.67, 0.58, 0.47, 0.54]
vโ‚ƒ = xโ‚ƒ ยท WV = [0.79, 0.48, 0.56, 0.75]
vโ‚„ = xโ‚„ ยท WV = [0.68, 0.55, 0.44, 0.61]

Step 3: Compute Attention Scores (Dot Products)
Formula: scorei = qโ‚… ยท kiT / โˆšdk (where dk = 4)
Computing dot products:
scoreโ‚ = qโ‚… ยท kโ‚ =
[0.59,0.41,0.56,0.43] ยท
[0.58,0.55,0.47,0.61]
= 0.59ร—0.58 + 0.41ร—0.55 + 0.56ร—0.47 + 0.43ร—0.61 = 1.13
scoreโ‚‚ = qโ‚… ยท kโ‚‚ = 1.09
scoreโ‚ƒ = qโ‚… ยท kโ‚ƒ = 1.28 โฌ… HIGHEST
scoreโ‚„ = qโ‚… ยท kโ‚„ = 1.15
Scaling: Divide by โˆš4 = 2 to normalize:
[1.13/2, 1.09/2, 1.28/2, 1.15/2] = [0.565, 0.545, 0.640, 0.575]

Step 4: Apply Softmax (Normalize to Probabilities)
Formula: attentioni = exp(scorei) / ฮฃ exp(scorej)
Scaled scores: [0.565, 0.545, 0.640, 0.575]
Apply exp(): [1.76, 1.72, 1.90, 1.78]
Sum = 1.76 + 1.72 + 1.90 + 1.78 = 7.16
Attention weights (softmax output):
ฮฑโ‚ = 1.76/7.16 = 0.246 (24.6%)
ฮฑโ‚‚ = 1.72/7.16 = 0.240 (24.0%)
ฮฑโ‚ƒ = 1.90/7.16 = 0.265 (26.5%) โ˜… HIGHEST
ฮฑโ‚„ = 1.78/7.16 = 0.249 (24.9%)
Check: 0.246 + 0.240 + 0.265 + 0.249 = 1.000 โœ“ (All probabilities sum to 1)

Step 5: Weighted Sum of Values (Final Output)
Formula: output = ฮฃ (ฮฑi ร— vi)
Recall our values:
vโ‚ = [0.84, 0.45, 0.41, 0.73]
vโ‚‚ = [0.67, 0.58, 0.47, 0.54]
vโ‚ƒ = [0.79, 0.48, 0.56, 0.75]
vโ‚„ = [0.68, 0.55, 0.44, 0.61]
And attention weights:
ฮฑโ‚ = 0.246, ฮฑโ‚‚ = 0.240, ฮฑโ‚ƒ = 0.265, ฮฑโ‚„ = 0.249
Computing weighted sum:
output = 0.246ร—[0.84, 0.45, 0.41, 0.73] +
0.240ร—[0.67, 0.58, 0.47, 0.54] +
0.265ร—[0.79, 0.48, 0.56, 0.75] +
0.249ร—[0.68, 0.55, 0.44, 0.61]
output = [0.745, 0.515, 0.470, 0.656]
Interpretation: This output vector is the new representation of token “the” after incorporating context from previous tokens, with emphasis on “sat” (26.5% weight).

๐ŸŽจ Understanding “Coloring” – The Key Insight
What Just Happened?
We just “colored” or “tinted” the embedding of token 5 (“the”) by mixing in information from previous tokens!

BEFORE Attention
[0.7, 0.4, 0.6, 0.3]
Generic “the”
NO context

โ†’

AFTER Attention
[0.745, 0.515, 0.470, 0.656]
Contextualized “the”
COLORED by “sat” (26.5%)
The “Mixing Recipe”:
outputโ‚… = 24.6% of vโ‚ (“The”) +
24.0% of vโ‚‚ (“cat”) +
26.5% of vโ‚ƒ (“sat”) โ† MOST
24.9% of vโ‚„ (“on”)
Result: Token 5 now “knows” it follows “sat on” and needs a noun that something sits ON โ†’ predicts: mat, floor, couch, chair, etc.

โšก Why Parallel Processing is Essential
Notice the weighted sum requires vโ‚, vโ‚‚, vโ‚ƒ, vโ‚„ from all previous tokens!To compute outputโ‚…, we needed:
โ€ข Keys (kโ‚, kโ‚‚, kโ‚ƒ, kโ‚„) โ†’ to compute attention scores
โ€ข Values (vโ‚, vโ‚‚, vโ‚ƒ, vโ‚„) โ†’ to combine in weighted sum
โ€ข Query (qโ‚…) โ†’ to determine what to attend to

All tokens must be processed simultaneously to generate their K and V vectors. This is why Transformers process tokens in parallel – not for speed, but because the math requires it!

๐ŸŽฏ Complete Attention Flow Summary
Input: xโ‚… = [0.7, 0.4, 0.6, 0.3]
โ†“ (multiply by WQ, WK, WV)
Projections: qโ‚…, kโ‚…kโ‚„, vโ‚…vโ‚„
โ†“ (dot products & softmax)
Attention: [0.246, 0.240, 0.265, 0.249]
โ†“ (weighted sum of values)
Output: [0.745, 0.515, 0.470, 0.656]

๐Ÿ’ก Key Insights
1. Self-attention is matrix multiplication: No magic, just learned weights!
2. Token “sat” got highest attention (26.5%): This is why the model predicts furniture/surfaces
3. All operations are differentiable: The model can learn optimal WQ, WK, WV through backpropagation
4. In real GPT-2: Vectors are 768-dimensional, not 4, but the math is identical!
5. This happens in parallel: All 5 tokens are processed simultaneously

After self-attention, this output vector [0.745, 0.515, 0.470, 0.656] goes through:
โ†’ Feedforward Neural Network
โ†’ More Transformer blocks (repeat 11 more times in GPT-2)
โ†’ LM Head to predict “mat”
๐Ÿ’ก Why Parallel Processing is Required

The weighted sum formula needs value vectors from ALL previous tokens simultaneously. To compute output for position 5, we need vโ‚, vโ‚‚, vโ‚ƒ, vโ‚„ all at once. This is why Transformers are inherently parallel – the math requires it!


8. Multi-Head Attention

GPT-2 actually runs attention 12 times in parallel using different learned matrices.

Figure 3-17: Complete Flow Through One Transformer Block

INPUT
768 dimensions

โ†“

SPLIT INTO 12 HEADS
768 โ†’ 12 ร— 64 dimensions

โ†“

EACH HEAD: Q, K, V MATRICES
Q = XยทWQ ย  K = XยทWK ย  V = XยทWV

โ†“

ATTENTION FORMULA
Attention(Q,K,V) = softmax(QKT / โˆšdk) V
dk=64, โˆšdk=8

โ†“

CONCATENATE 12 HEADS
12 ร— 64 โ†’ 768 dimensions

โ†“

WO (OUTPUT MATRIX)
768 ร— 768 projection

โ†“

ADD & NORM
LayerNorm(input + output)

โ†“

FEEDFORWARD NETWORK
768 โ†’ 3,072 โ†’ 768

โ†“

ADD & NORM
LayerNorm(input + FFN)

โ†“

OUTPUT
768 dimensions
โ†’ Next block or LM Head

๐Ÿ”— Connection to LM Head
After all 12 Transformer blocks:Block 12 output (768 dims)
โ†“
LM Head matrix (768 ร— 50,257)
โ†“
50,257 logits
โ†“
Softmax โ†’ probabilities
โ†“
Select token (e.g., “mat”)

๐Ÿ“ The Complete Formula
Multi-Head Attention:

MultiHead(Q,K,V) = Concat(head1,…,head12)WO
Where each head:

headi = Attention(QWQi, KWKi, VWVi)

๐Ÿ’ก Information is Distributed

Each head sees dimensions 0-63, 64-127, etc. But information isn’t neatly separated – it’s distributed across all dimensions. Each head sees a partial, blurred view of everything. Through learned Q/K/V projections, different heads learn to emphasize different patterns.


๐ŸŽ“ Final Synthesis

The Complete Flow

  1. Text โ†’ Tokenizer โ†’ Token IDs
  2. Token IDs โ†’ Embedding Lookup โ†’ 768-dim vectors
  3. Add positional encodings (once, at the start)
  4. Flow through 12 Transformer blocks sequentially
  5. Each block: Self-attention + Feedforward + Residual connections
  6. Final output โ†’ LM Head โ†’ 50,257 logits
  7. Softmax โ†’ Probabilities โ†’ Pick next token

Key Takeaways

๐Ÿ’ก Essential Concepts

Everything is learned: Token embeddings, attention weights, feedforward parameters – all learned from data, not hand-designed.

Parallel processing: All tokens flow simultaneously. This isn’t just for speed – the math requires it.

Context is key: Same word has different representations depending on context, thanks to attention.

Scale matters: GPT-2’s 117M parameters enable good performance, but GPT-3 (175B) and GPT-4 (rumored 1.7T) achieve dramatically better results.

It’s predictive: Despite seeming intelligent, LLMs do next-token prediction based on learned patterns.

๐ŸŽ‰ You’ve Completed the Guide!

You now understand how Large Language Models work from input to output. You’ve seen the architecture, followed numbers through calculations, and learned why design choices were made.

This knowledge applies to GPT-4, Claude, Llama, and virtually all modern LLMs.

Reference Model: GPT-2 (50,257 tokens โ€ข 768 dimensions โ€ข 12 blocks โ€ข 117M parameters)
Consistent Example: “The cat sat on the” โ†’ “mat”
Colors: Google Material Design Palette
All figures: Self-contained with inline CSS


๐Ÿ“ Appendix: Complete Mathematical Reference

This appendix provides all key mathematical formulas used in Transformer language models, with proper LaTeX notation.

1. Attention Mechanism

Single-Head Attention

Attention(Q, K, V) = softmax(QKT / โˆšdk) V

Where:

  • Q = Query matrix (what we’re looking for)
  • K = Key matrix (what each token offers)
  • V = Value matrix (actual information to combine)
  • dk = dimension of keys (64 per head in GPT-2)
  • โˆšdk = scaling factor to prevent large dot products
๐Ÿ’ก GPT-2 Example

For each attention head: dk = 64, so โˆšdk = โˆš64 = 8

Multi-Head Attention

MultiHead(Q, K, V) = Concat(head1, head2, …, headh) WO

Where each head is computed as:

headi = Attention(QWQi, KWKi, VWVi)

Parameters:

  • WQi โˆˆ โ„dmodel ร— dk = Query projection for head i
  • WKi โˆˆ โ„dmodel ร— dk = Key projection for head i
  • WVi โˆˆ โ„dmodel ร— dv = Value projection for head i
  • WO โˆˆ โ„hdv ร— dmodel = Output projection matrix
  • h = number of heads (12 in GPT-2)
  • dmodel = 768 (GPT-2)
  • dk = dv = dmodel/h = 64 (GPT-2)

2. Softmax Function

softmax(xi) = exp(xi) / ฮฃj=1n exp(xj)

Properties:

  • Output range: (0, 1) for each element
  • Sum constraint: ฮฃi softmax(xi) = 1
  • Monotonic: preserves ordering of inputs
  • Differentiable: enables gradient-based learning

In attention context:

attention_weighti = exp(scorei) / ฮฃj exp(scorej)

Where scorei = (q ยท ki) / โˆšdk

3. Layer Normalization

LayerNorm(x) = ฮณ โŠ™ x – ฮผ / โˆš(ฯƒยฒ + ฮต) + ฮฒ

Where:

  • ฮผ = (1/d) ฮฃi=1d xi (mean)
  • ฯƒยฒ = (1/d) ฮฃi=1d (xi – ฮผ)ยฒ (variance)
  • ฮณ, ฮฒ = learnable parameters (scale and shift)
  • ฮต = 10-5 (small constant for numerical stability)
  • โŠ™ = element-wise multiplication
  • d = feature dimension (768 for GPT-2)

4. Residual Connections

Post-normalization (original Transformer):

output = LayerNorm(x + Sublayer(x))

Pre-normalization (modern Transformers, including GPT-2):

x1 = x + MultiHeadAttention(LayerNorm(x))
output = x1 + FeedForward(LayerNorm(x1))

5. Feedforward Neural Network

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

Parameters:

  • W1 โˆˆ โ„dmodel ร— dff = First layer weights
  • b1 โˆˆ โ„dff = First layer bias
  • W2 โˆˆ โ„dff ร— dmodel = Second layer weights
  • b2 โˆˆ โ„dmodel = Second layer bias
  • dff = feedforward hidden dimension (typically 4 ร— dmodel)

GPT-2 Configuration:

  • dmodel = 768
  • dff = 3,072 (exactly 4 ร— 768)

6. GeLU Activation Function

Gaussian Error Linear Unit:

GeLU(x) = x ยท ฮฆ(x)

Where ฮฆ(x) is the cumulative distribution function of standard normal distribution:

ฮฆ(x) = ยฝ[1 + erf(x/โˆš2)]

Approximation (commonly used in practice):

GeLU(x) โ‰ˆ 0.5x(1 + tanh[โˆš(2/ฯ€)(x + 0.044715xยณ)])

7. Positional Encoding

Learned Positional Embeddings (GPT-2)

Etotal(t, p) = Etoken(t) + Epos(p)

Where:

  • Etoken โˆˆ โ„50,257 ร— 768 = token embedding matrix
  • Epos โˆˆ โ„1,024 ร— 768 = position embedding matrix
  • t = token ID
  • p = position (0 to 1,023)

Sinusoidal (Original Transformer)

PE(pos, 2i) = sin(pos / 100002i/dmodel)
PE(pos, 2i+1) = cos(pos / 100002i/dmodel)

Where:

  • pos = position in sequence
  • i = dimension index
  • dmodel = model dimension (768)

8. Language Modeling Head

Project to vocabulary:

logits = xfinal ยท WLM

Apply softmax to get probabilities:

P(tokeni) = exp(logiti) / ฮฃj=1V exp(logitj)

Where:

  • xfinal โˆˆ โ„768 = output from last Transformer block
  • WLM โˆˆ โ„768 ร— 50,257 = LM head weight matrix
  • V = 50,257 (vocabulary size)
  • logits โˆˆ โ„50,257 = scores for each token

9. Temperature Scaling

Temperature parameter controls randomness in sampling:

PT(tokeni) = exp(logiti / T) / ฮฃj=1V exp(logitj / T)

Temperature effects:

  • T = 0: Greedy decoding (always pick highest probability)
  • T = 1: Sample from raw distribution
  • T > 1: More random (flattens distribution)
  • T < 1: More confident (sharpens distribution)

10. Parameter Count Formulas

Per Transformer block:

Multi-head attention:

Paramsattention = 4 ร— dmodelยฒ = 4 ร— 768ยฒ = 2,359,296

Feedforward network:

ParamsFFN = 2 ร— (dmodel ร— dff) = 2 ร— (768 ร— 3,072) = 4,718,592

Total per block:

Paramsblock = 2.36M + 4.72M โ‰ˆ 7.1M

Full GPT-2 model:

Paramstotal = V ร— dmodel + L ร— 12dmodelยฒ

Where:

  • V = 50,257 (vocabulary size)
  • dmodel = 768 (embedding dimension)
  • L = 12 (number of blocks)

GPT-2 breakdown:

  • Token embeddings: 50,257 ร— 768 = 38,597,376
  • Position embeddings: 1,024 ร— 768 = 786,432
  • 12 Transformer blocks: 12 ร— 7.1M = 85.2M
  • Total: ~117M parameters

11. Training Loss Function

Cross-entropy loss for next-token prediction:

โ„’ = -ฮฃi=1n log P(xi+1 | x1, …, xi)

Per-token loss:

โ„’i = -log(exp(logittarget) / ฮฃj=1V exp(logitj))

Where:

  • xi = token at position i
  • P(xi+1 | x1, …, xi) = predicted probability for next token
  • logittarget = score for the actual next token

๐Ÿ“š Formula Summary

Attention softmax(QKT/โˆšdk) V
Multi-Head Concat(heads) WO
Feedforward GeLU(xW1)W2
Layer Norm ฮณ(x-ฮผ)/โˆš(ฯƒยฒ+ฮต) + ฮฒ
Residual x + Sublayer(LayerNorm(x))
Position Etoken + Epos
LM Head softmax(xยทWLM)

๐Ÿ“– References

  • “Attention Is All You Need” (Vaswani et al., 2017) – Original Transformer
  • “Language Models are Unsupervised Multitask Learners” (Radford et al., 2019) – GPT-2
  • “Layer Normalization” (Ba et al., 2016)
  • “Gaussian Error Linear Units (GELUs)” (Hendrycks & Gimpel, 2016)
  • “RoFormer” (Su et al., 2021) – Rotary Position Embeddings