Originally published Nov. 2025; technical review Jul. 30, 2026.

A language model does not receive words directly. It receives numerical token IDs, turns them into vectors, and repeatedly transforms those vectors. This article follows that path without assuming that any one model uses the exact example sizes shown below.

The explanation is split into four steps. First: tokenization, which divides text into pieces. Second: token embeddings, which give each token ID a learned starting vector. Third: attention, which mixes information across permitted positions. Fourth: training, which adjusts the model's parameters so its predictions improve.

Tokenization - Breaking Text Into Pieces

An LLM cannot process raw text directly. Its tokenizer uses a finite vocabulary of tokens, which may be words, word pieces, bytes, characters, or a mixture. Tokens are not the same thing as ordinary dictionary words.

The problem: There are infinite possible sentences, but a model needs a finite list.

The solution: Break text into small pieces called tokens. Each token gets a number.

Three Ways to Tokenize

You could break text at different levels. Each choice has tradeoffs.

Option 1: Letters

Text: "Hello"
Tokens: ["H", "e", "l", "l", "o"]
Toy English-only vocabulary: ~26 letters plus punctuation and controls

Good: Very small vocabulary. Any word can be spelled.

Bad: Very inefficient. "Hello" needs 5 tokens. Long sequences are slow to process.

Option 2: Subwords

Text: "Hello running"
Tokens: ["Hello", " run", "ning"]
Illustrative vocabulary: tens of thousands of pieces

Good: Mostly full words. Common words stay whole. Rare words break into pieces. Balanced efficiency and coverage.

Bad: Tokenization can be unpredictable. Similar words might split differently.

Option 3: Full words

Text: "Hello"
Tokens: ["Hello"]
Toy full-word vocabulary: potentially hundreds of thousands of entries

Good: Very efficient. One token per word.

Bad: Huge vocabulary. Every verb form needs its own entry: "run", "runs", "ran", "running". Can't handle typos or rare words.

Why use a medium-sized vocabulary? It balances sequence length against the cost of a larger lookup and output table. The best size is model-specific. Token counts also vary by language, text, and tokenizer, so there is no universal tokens-per-word rule.

From Text to Numbers

Once text is tokenized, each token gets a unique number from the vocabulary.

Text: "Hello world"
Tokens: ["Hello", " world"]
Toy token IDs: [15339, 2684]

The example model receives [15339, 2684]. Those IDs are arbitrary row numbers in that tokenizer's vocabulary. Another tokenizer may split the text differently and assign completely different IDs.

Why This Matters

Different tokens are completely unrelated numbers to the model:

Token 15339 = "Hello"
Token 47234 = "hello"
The model sees: 15339 vs 47234 (totally different)

The numbers are arbitrary. Token 100 and 101 have no special relationship just because they're close numerically. The distance between numbers is meaningless.

The problem: How can a model learn that "Hello" and "hello" are similar if they're just unrelated integers?

The answer: Embeddings. That's the next tab.

Summary: Text becomes tokens drawn from a finite, model-specific vocabulary. Subword and byte-aware methods are common because they balance coverage and sequence length. Each token becomes an arbitrary ID, and the ID itself carries no semantic distance.

Embeddings - Giving Tokens a Starting Representation

Remember the problem from tokenization: Token 15339 ("Hello") and Token 47234 ("hello") are just unrelated IDs in this toy tokenizer. Numerical closeness between IDs says nothing about meaning.

The solution: Turn each token into a vector of numbers. Not just one number, but many.

From One Number to Many

A token embedding is a learned list of numbers used as the token's initial representation. The width can range from hundreds to many thousands of values, depending on the model.

Token ID: 15339
Embedding (simplified to 8 dimensions):
[0.24, -0.51, 0.83, -0.12, 0.67, -0.33, 0.91, -0.45]

The eight values above are invented for explanation. Real embedding widths are model-specific. The important idea is that each token ID selects one high-dimensional starting vector.

Why vectors? Vectors can be transformed, compared, and combined by the network. Useful geometric relationships may emerge during training, but a raw token embedding is only a context-free starting point. Contextual meaning appears in the hidden representations produced by later transformer layers.

Visualizing Embeddings

Imagine a 2D space, even though real embeddings are much wider. The coordinates below are invented only to show the idea of a vector space:

Token "cat" → [0.8, 0.6]
Token "dog" → [0.7, 0.5]
Token "kitten" → [0.75, 0.65]
Token "run" → [-0.3, 0.9]

Here's what this looks like in 2D space:

← Dimension 2 →
← Dimension 1 →
cat
dog
kitten
run

In this illustration, "cat", "dog", and "kitten" cluster together while "run" is farther away. A trained model's actual geometry is more complex and need not form such a clean picture.

Measuring similarity with cosine similarity:

One common analysis tool is cosine similarity. It measures how much two vectors point in the same direction, regardless of their length. It is useful for inspecting vectors, but it is not the operation that defines all transformer behavior.

Cosine similarity = (vector A · vector B) / (|A| × |B|)
Range: -1 (opposite) to +1 (same direction)
"cat" ↔ "kitten"
Illustrative cosine: 0.98
"cat" ↔ "dog"
Illustrative cosine: 0.82
"cat" ↔ "run"
Illustrative cosine: 0.18

These three scores are invented, not measurements from a named model. In some embedding analyses, related items have higher cosine similarity, but raw token embeddings do not guarantee a neat semantic map.

Why cosine similarity instead of distance?
Cosine similarity measures the angle between vectors, not their length. A dot product of unit-normalized vectors is mathematically equivalent to cosine similarity. Analysts may also use dot product or Euclidean distance depending on how the vectors were trained and normalized. There is no single best metric for every embedding space.

The Embedding Table

How does this work? The model has an embedding table: a big lookup table that maps each token ID to its vector.

Toy vocabulary size: 50,000 tokens
Toy embedding width: 768
Toy table size: 50,000 × 768 = 38.4 million numbers

In this toy example, token 15339 selects row 15339 and returns a 768-value vector. Both the vocabulary and width depend on the actual model.

Input: Token ID 15339
Lookup: Row 15339 in embedding table
Illustrative output: [0.24, -0.51, 0.83, ..., -0.45] (768 values)

Embeddings Are Learned

Here's the crucial part: the model doesn't know what these embeddings should be at the start.

At initialization, the embedding table is filled with random numbers. Token "cat" might start as [0.01, -0.23, 0.44, ...]. Token "dog" might be [-0.88, 0.12, -0.03, ...].

During training, the model learns better embeddings. It adjusts the numbers so that:

  • Useful geometric relationships can emerge
  • Different tokens can support related predictions
  • The embeddings help the full network predict what comes next

How does it learn? The model tries to predict the next token. When it gets it wrong, it adjusts the embeddings (and other parameters) to do better next time. Over billions of training examples, the embeddings become meaningful representations.

Why This Matters

Embeddings replace arbitrary IDs with trainable vectors:

Before: Token 15339 and Token 47234 are unrelated numbers
After: Each ID selects a learned starting vector

The network can learn to process "Hello" and "hello" similarly even when their IDs differ. That similarity may appear partly in token embeddings and partly in the contextual representations created after attention and MLP transformations.

Relationships such as "run" and "running" or "Paris" and "France" are distributed across learned weights and context-dependent activations, not stored only in one embedding-table row.

The Magic of High Dimensions

Why use a wide vector instead of only two or three values? Because language is complex. The exact width is a model-specific design choice.

The word "bank" can mean:

  • A financial institution
  • The side of a river
  • To tilt an airplane

A wide representation can support many overlapping features at once. Concepts are usually distributed across many dimensions rather than assigned cleanly to one dimension each.

The model doesn't explicitly assign dimensions to concepts. It just learns what works. But the result is that embeddings capture rich, multi-faceted meaning.

Summary: A token ID selects a learned vector from an embedding table. That token embedding is context-free. Transformer layers then turn it into contextual hidden representations that depend on surrounding tokens. The displayed coordinates and similarity scores are illustrative, not observations from a particular model.

But embeddings are just the start. The real power comes from what happens next: learning.

Attention - Letting Tokens Share Context

Token embeddings provide starting vectors, but the model still needs to combine information across positions. Attention is one coordination step. Each position can draw from the positions allowed by the model's attention mask. In a causal language model, that normally means the current and earlier tokens, not future tokens.

The Challenge: Ambiguity in Language

Consider the sentence: "The river reached the bank."

The word "bank" is ambiguous. It could mean:

  • A financial institution (money bank)
  • The side of a river (riverbank)
  • To tilt or lean

A human reader looks at "river" and immediately knows this is the riverside meaning. The model needs a similar ability: to look at context and adjust understanding. Attention provides exactly that.

Queries, Keys, and Values

At a given layer, each current hidden representation is projected into Query, Key, and Value vectors. For each attention head:

Q = X·W_Q (current representation projected by Query weights)
K = X·W_K (current representation projected by Key weights)
V = X·W_V (current representation projected by Value weights)
Query (Q)
What am I looking for?
The "question" this token asks, created by Q = X·W_Q. For "bank", its query signals what context would help. Compared to keys via dot product.
Key (K)
What do I advertise?
The "topic tags" this token offers, created by K = X·W_K. Dot-product with queries determines attention scores (scaled by √d_k).
Value (V)
The information I share
Created by V = X·W_V. This is what gets blended by attention weights. When a token receives attention, its value is what contributes to the output.

Positional Information

Content-only dot-product attention does not carry enough information about token order. Architectures introduce position in different places, so positional information is not always added directly to embeddings:

Common approaches:
• Sinusoidal or learned absolute: Add a position vector to input representations
• RoPE (Rotary): Apply position-dependent rotations to Queries and Keys
• ALiBi: Add a position-dependent bias to attention logits

The causal mask also supplies direction by blocking future positions. Exact positional behavior depends on the model's architecture, but some position-sensitive mechanism is needed to represent order and distance well.

The Attention Mechanism Step-by-Step

Let's trace what happens when a causal model processes "The river reached the bank." Here, "river" occurs before "bank," so the final token is allowed to attend to it:

the
river
reached
the
bank

Step 1: Compute Compatibility Scores

For the token "bank", compute a learned compatibility score between its Query and each allowed token's Key using a dot product. The values below are invented to make the flow visible:

attention_scores = Query(bank) · Keys(all tokens)
Display-only scores: [the: 0.2, river: 0.8, reached: 0.1, the: 0.2, bank: 0.5]

A dot product depends on both direction and magnitude. It is not generally cosine similarity. During training, the projections learn scores that are useful for the task. In this invented example, "river" receives the highest display score because the diagram is illustrating the riverside reading of "bank".

Why dot product? Isn't that cosine similarity?
They are related but not the same. Cosine similarity divides the dot product by both vector lengths. Standard scaled dot-product attention uses QKT/√dk and does not require Queries and Keys to be unit-normalized. Some architectures add normalization, but it is not universal. Magnitude can therefore affect ordinary attention logits.
the
0.2
river
0.8
reached
0.1
the
0.2
bank
0.5

Step 2: Stabilize and Normalize

Raw dot products can grow with dimension. Standard scaled dot-product attention divides by √(d_k), where d_k is the per-head key/query width, then applies softmax. Masks and implementation-specific biases may also be added before softmax. This separate numerical example is constructed only to show the conversion:

Toy shape: d_model=768, num_heads=12 → d_k=64
Illustrative scaled logits: [-2.30, -0.56, -2.53, -2.30, -1.90]
attention_weights = softmax(illustrative_scaled_logits)
Weights: [the: 0.10, river: 0.57, reached: 0.08, the: 0.10, bank: 0.15]

In this toy distribution, "river" has weight 0.57. These weights are not taken from a trained model and should not be interpreted as a universal explanation of how models resolve the word "bank".

Attention weights visualization (for "bank"):
the (10%)
river (57%)
reached (8%)
the (10%)
bank (15%)

Step 3: Blend Values

Multiply each token's Value vector by its attention weight, then sum:

output = (0.10 × Value(the) + 0.57 × Value(river) + 0.08 × Value(reached)
+ 0.10 × Value(the) + 0.15 × Value(bank))

In the toy calculation, the Value vector at "river" contributes the largest share to this head's output for "bank". A real model distributes features across heads and layers, so one visible attention weight is not a complete explanation of the model's decision.

Multi-Head Attention

Many transformers use multiple heads in parallel, each with its own Query, Key, and Value projections. The labels below are intuition, not fixed or guaranteed head roles:

Head 1: Grammar
Tracks subjects, verbs, objects
Attends to: "the" → "bank" (grammatical structure)
+
Head 2: Semantics
Tracks meaning and context
Attends to: "river" (geographical context)
+
Head 3: ...
Other patterns
Multiple specializations
→ Concatenate & Project

Each head produces an output vector. The outputs are usually concatenated and projected to form the attention block's result. Individual heads can show mixed, overlapping, or context-dependent behavior rather than one clean specialization.

Putting It Together: The Attention Mechanism

Scaled Dot-Product Attention (single head)
Attention(Q, K, V) = softmax(QKT / √dk) V
Q = Queries, K = Keys, V = Values, dk = dimension of keys

Summary: Attention mixes Value vectors using weights derived from scaled Query-Key dot products. Standard attention is not generally cosine similarity, and Queries and Keys are not universally normalized. Position may enter through added vectors, transformations such as RoPE, or biases such as ALiBi. The result contributes to richer contextual representations across many heads and layers.

Learning - How Matrix Multiplications and Attention Create Understanding

We have token embeddings now. Their width is model-specific, and at the start of training from scratch their values are typically initialized without useful language structure. The model must learn representations that help it predict.

This is where the transformer architecture comes in. Two main mechanisms work together: attention (which you learned about in the previous tab) and feedforward networks (made of matrix multiplications). They're the tools the model uses to transform embeddings and discover patterns across billions of training examples.

What Is a Matrix Multiplication?

A matrix multiplication is a mathematical operation that transforms vectors. Think of it as a function: you put a vector in, you get a different vector out.

Input vector: [0.8, 0.6, 0.3]
Matrix: [[0.5, 0.2], [0.1, 0.9], [0.7, 0.3]]
Output vector: [0.67, 0.79]

The matrix contains weights (numbers). When you multiply the input vector by the matrix, you get a new vector. The weights control how the transformation happens.

How does matrix multiplication work mathematically?
Each element in the output is a weighted sum of the input. For example: output[0] = (input[0] × 0.5) + (input[1] × 0.1) + (input[2] × 0.7). The matrix tells you what weights to use. In an LLM, these weights are learned during training. The model adjusts them to transform embeddings in useful ways.

How Transformers Work: Attention + Feedforward

Each layer in a transformer has two parts that work together. Here's what happens:

1
Start with initial or contextual representations
Toy vector: [0.24, -0.51, 0.83, ...]
2
Multi-Head Attention
Allowed positions exchange information using Q, K, and V projections.
3
Feedforward Network
Matrix multiplications transform and refine the context-aware vectors
4
Output to next layer
Richer representations with multiple types of learned patterns

This cycle repeats through the model's transformer blocks. A simplified decoder block looks like this, although normalization order, activation functions, positional method, and other details vary by architecture:

Common transformer-block ingredients:
1. Position-sensitive attention:
• Multi-head attention mixes information across allowed positions
• Residual connection preserves and adds to the block input
2. Feedforward block (MLP):
• Learned projections plus a nonlinearity such as GELU or a gated variant
• Operates separately at each position
• Residual connection adds its update
3. Normalization appears before or after sublayers, depending on the design

Key distinction: Attention mixes information across permitted positions. The MLP transforms features at each position separately. Both operations can contribute to many behaviors, so it is too strong to say attention only finds relevance while the MLP alone performs reasoning.

Some analyses find rough depth-related tendencies, but there is no universal rule that assigns local syntax to early layers and reasoning to late layers.

Example: Understanding Context (Attention + Feedforward)

Consider the sentence: "The river reached the bank." The vectors and weights below are invented teaching values:

Token "bank" starts with embedding: [0.2, 0.5, ...]
ATTENTION LAYER:
• "bank" attends to all tokens via queries/keys/values
• Highest attention to "river" (0.57 weight, as you learned)
• Context vector: [0.1, 0.9, ...] (mixed with "river")
FEEDFORWARD LAYER:
• Matrix multiplications refine: [0.1, 0.9, ...] → [0.05, 0.95, ...]
• Toy interpretation: this hidden state now favors the riverside reading

Together, attention, MLPs, residual paths, and normalization can make the representation at "bank" depend on "river." The example is useful intuition, not a claim that one head or one MLP contains the complete interpretation.

Learning Through Training

At the start of training, the weight matrices are random. The model makes terrible predictions. But here's how it improves:

📝
1. Try to predict
Model sees "The cat sat on the" and tries to predict next token
2. Get it wrong
Predicts "car" but correct answer is "mat"
🔧
3. Adjust weights
Change matrix values to make "mat" more likely next time
🔄
4. Repeat over many training batches
The number of tokens and updates depends on the training run

Training software aggregates prediction errors into a loss, computes gradients with backpropagation, and updates parameters with an optimizer. A simplified training loop is:

1. Forward pass: Text → tokens → embeddings → model-specific number of blocks → logits
2. Loss: Softmax cross-entropy between predicted and true next token
3. Backward pass: Compute gradients for all layers
4. Update: Use optimizer (e.g., AdamW) to adjust:
• Transformer weight matrices (attention, MLP)
• Embedding table entries
• Positional encodings (if learned)
5. Repeat across many batches in the training dataset

Over training, optimization usually lowers prediction loss and produces parameters that generalize to many unseen sequences. Exact data volumes and convergence behavior vary by model and run.

Key insight: The model is not given a complete hand-written grammar. Predictive training shapes embeddings, attention and MLP weights, normalization parameters, and the activations they produce. Knowledge and behavior are distributed across this system rather than stored in one simple table or layer.

Why Multiple Layers?

LLMs apply a model-specific number of transformer blocks. Many have dozens of blocks; some have fewer or more. The diagram below is a teaching sketch, not the anatomy of every model.

Layer 1
Possible tendency: token identity, position, and local features begin interacting
Layer 10
Possible tendency: broader syntactic and contextual features become available
Layer 20
Possible tendency: distributed semantic and long-range features develop
Layer 30+
Possible tendency: later representations support the output prediction

Representations usually change and become more task-useful with depth, but features can be distributed, reused, or carried through residual paths. Heads and MLPs do not follow a fixed ladder from grammar to semantics to reasoning in every model.

How many parameters does an LLM have?
A parameter is a trainable number in an embedding, projection, normalization component, or other learned part of the model. Counts such as 7B, 70B, and 405B describe particular model sizes, not universal categories. More parameters can increase capacity, but architecture, data, compute, training, and inference methods also matter.

Putting It All Together: The Complete Transformer Pipeline

Here's the complete pipeline:

Toy example:
1. Text → Tokens: "Hello world" → model-specific token IDs
2. Token IDs → Embeddings: IDs select learned starting vectors
3. Representations → Blocks: Process through a model-specific number of transformer blocks
Each layer contains:
• Attention: Mix information across allowed positions
• MLP: Transform features separately at each position
• Residual paths and normalization
4. Layers → Prediction: Output probabilities for next token

Attention and MLP sublayers repeatedly transform the hidden representations. Attention mixes across permitted positions, while the MLP transforms the features at each position. Their roles overlap and interact, and neither has one fixed interpretation.

The weights in embeddings, attention, MLPs, normalization, and output components are learned. Parameter counts and training-token counts vary widely, so all fixed counts in this article are explicitly toy or model-specific examples.

Summary: Training adjusts many kinds of parameters to improve prediction. Token embeddings provide context-free starting vectors. Attention, MLPs, residual paths, normalization, and position-sensitive mechanisms then create contextual representations. Their contributions are distributed rather than arranged in a fixed mechanistic hierarchy.

The Big Picture: Everything Connected

You now understand the full transformer architecture:

  • Tokenization: Text becomes numbers (token IDs)
  • Token embeddings: Token IDs select context-free learned starting vectors
  • Position: Added vectors, Query-Key transformations, or attention biases represent order
  • Attention: Scaled Q-K dot products weight Value vectors across allowed positions
  • MLPs: Learned nonlinear transformations operate at each position
  • Transformer blocks: These mechanisms repeat a model-specific number of times to create contextual representations

Every prompt follows this broad journey, though the exact tokenizer, position method, dimensions, number of heads, number of blocks, and parameter count depend on the model. The useful behavior comes from the complete trained system, not from one component in isolation.

Current Technical References