English | 简体中文 · Series home · Part I
In this article
- 1 Let's step inside
model() - 2 Token IDs become initial vectors through a lookup
- 3
states: the same token can have different states in different sentences - 4 Attention: how does a position use its context?
- 5 After gathering information: why stack so many layers?
- 6 From the last position's vector to vocabulary scores
- 7 Put the whole
model()pipeline together - 8 Previous article
LLMs & Agents, Explained — From LLMs to Agents, one question at a time. For engineers who can code but haven't studied machine learning. We start with concrete examples, add pseudocode, and follow the data flow to understand how LLMs and agents actually work.
1 Let's step inside model()
In the previous article, we followed the generation process from a message to an answer. One line did the most important work:
scores = model(context_ids)
We know what goes in: the token IDs for the current context. We also know what comes out: a score for every candidate next token. But we left one question open: where do those scores come from?
This time, we'll step inside model(): how does a sequence of IDs use context to become a set of candidate scores?
We'll keep the same translation example. Suppose generation has reached this point:
User request: Please translate “我喜欢猫” into English.
Generated so far: I like
What comes next: ?
Let's pause the generation loop just after I like, before the next token is selected:
# Original input: the formatted conversation, including the translation request
# Existing answer: the token IDs for "I like"
context_ids = prompt_ids + answer_ids
# Score every candidate next token using the current context
scores = model(context_ids)
The model receives both the original request and the answer prefix I like. Together, they influence the next set of scores.
We'll follow that data inward: how IDs become vectors, how those vectors change as they incorporate context, and how the final result becomes scores.
We use the same teaching convention as Article 01:
model()returns only the scores from the last position, used to predict the next token. Our focus is one forward pass through an already trained model. We'll discuss training only far enough to explain where the tables and weights come from and whether inference changes them. Training data, learning objectives, and how knowledge develops belong in Article 04.
2 Token IDs become initial vectors through a lookup
The first job inside model() is to give those IDs something useful to compute with.
As we saw in Article 01, a token ID is just an identifier. If 猫—the Chinese word for “cat”—has ID 89, the number doesn't describe any property of cats. Nor does it mean that token 90 must be similar.
An ID makes a token easy to look up. The model still needs a vector of numbers for the computations that follow. That's where the embedding table comes in.
The model's embedding table
First, let's distinguish two tables:
| Table | What it does | Teaching example |
|---|---|---|
| Tokenizer vocabulary | Associates tokens with IDs | "猫" → 89 |
| Model embedding table | Retrieves an initial vector for an ID | 89 → [0.5, -0.2, 0.9, 0.1] |
Imagine a tiny model in which each token's initial vector contains four numbers. Real models choose their own fixed embedding dimension; in many LLMs, it runs into the thousands or tens of thousands.
The lookup looks like this:
Token: 猫
↓ Tokenizer encoding
Token ID: 89
↓ Model embedding lookup
Initial vector: [0.5, -0.2, 0.9, 0.1]
In pseudocode, it's a familiar array lookup:
cat_vector = embedding_table[89]
The job of 89 is to identify a row. There isn't a magic formula that turns the integer 89 into the meaning of “cat.”
Suppose a model has a vocabulary of 100,000 tokens and an embedding dimension of 4,096. Its embedding table has 100,000 rows and 4,096 columns. Each row holds one token's initial vector.
All token boundaries, IDs, and vector values in this section are illustrative. Actual vocabulary sizes, dimensions, and parameter values vary by model.
One input position, one vector
Now zoom out from a single 猫 to a sequence. Suppose part of the input is:
Text: 我喜欢猫 (“I like cats”)
Assumed tokens: ["我", "喜欢", "猫"]
Corresponding IDs: [12, 357, 89]
Looking up the IDs in order gives:
[
[0.2, -0.7, 0.4, 0.6], ← initial vector for 我 (“I”)
[0.8, 0.1, -0.3, 0.2], ← initial vector for 喜欢 (“like”)
[0.5, -0.2, 0.9, 0.1] ← initial vector for 猫 (“cat”)
]
A sequence of IDs has become a sequence of vectors. Stack those vectors as rows, and you have a matrix.
We'll call this intermediate result states:
# Retrieve one initial vector per position, in input order
states = [
embedding_table[token_id]
for token_id in context_ids
]
Later, we'll use the shorter notation:
states = embedding_table[context_ids]
If the current context contains 20 tokens and each vector has 4,096 components:
context_ids: 20 IDs
↓ Lookup
states: 20 rows × 4,096 columns
Each row: the initial vector for one input position
Each column: one component of that vector
The actual lookup covers the full context_ids: the formatted original conversation plus the answer prefix generated so far. We're isolating 我喜欢猫 only to make the mechanics easier to see.
Who fills in the numbers?
The embedding table is part of the model's parameters. Its values are learned during training.
For now, think of training as adjusting this table alongside the model's other parameters, so that they work together to make better predictions. Nobody assigns meanings like these by hand:
First number = cuteness
Second number = animal-ness
Third number = how much someone likes it
Information is generally distributed across many values and their combinations. You can't simply pick a column and translate it into a human concept.
During the ordinary inference we're discussing, the model reads its already trained embedding table. A lookup reads parameters; it does not update them.
We now have an initial vector for every input position. But this lookup has not yet incorporated the current sentence's context.
If 猫 is the same token in 我喜欢猫 (“I like cats”) and 我害怕猫 (“I'm afraid of cats”), both lookups return the same initial vector. The sentences clearly mean different things, though.
How can the same starting point develop into different contextual states? That's what we'll follow next.
3 states: the same token can have different states in different sentences
In the previous section, a lookup turned a sequence of IDs into initial vectors:
states = embedding_table[context_ids]
Those vectors will now pass through layer after layer of computation, gradually incorporating context.
But first, an obvious engineering question: if these vectors came from the embedding table, won't changing them mess up the table?
The embedding table holds parameters; states holds working data
A useful way to picture the lookup is:
Retrieve the required vectors from the trained embedding table, in input order, to form a working copy for this computation.
Trained embedding table
│
│ Look up values using context_ids
↓
Initial states
│
↓ Layer 1
Updated states
│
↓ Layer 2
Updated states
│
↓
...
The model continues processing that working data. During ordinary inference, the results are not written back to the embedding table, and they do not update the model's other parameters.
def model(context_ids):
# Look up the initial states for this forward pass
states = embedding_table[context_ids]
# Each layer computes new states from the current ones
for layer in transformer_layers:
states = layer(states)
# Later, turn the states into candidate scores
...
This line:
states = layer(states)
means “continue with the result of this layer.” It does not execute:
embedding_table[context_ids] = states
The table doesn't get rewritten because today's conversation is about cats, then overwritten again when tomorrow's is about dogs.
Model parameters determine how information is processed.
statesholds the working information being processed during a forward pass.
Other intermediate results exist inside the model, too. But following states is enough to track the main data flow in this article.
“Working copy” is a way to understand the data flow, not a requirement for a particular memory-copy implementation. Real systems may also cache intermediate results for later generation steps. Neither changes the key point: ordinary inference does not write state updates back into model parameters.
Why would the same “cat” have different states?
Consider:
我喜欢猫。 (“I like cats.”)
我害怕猫。 (“I'm afraid of cats.”)
Assuming 猫 is the same token in both sentences, both lookups retrieve the same embedding row.
But 喜欢 (“like”) and 害怕 (“fear”) change the context. Subsequent computation allows the position containing 猫 to use that information, producing different states:
Initial vector for 猫
/ \
↓ ↓
Working state A Working state B
│ │
Use 我喜欢 Use 我害怕
│ │
↓ ↓
Updated A Updated B
The two working states evolve separately. The original embedding stays the same.
A changed state does not mean that the token itself has been replaced:
context_ids[i] # The token ID originally supplied at this position
states[i] # This position's current computational state
Here, i is a position in the input sequence. Updating states[i] does not modify context_ids[i].
An intermediate state doesn't have to equal any token's initial embedding, either. The model doesn't finish each layer by checking the table and asking, “Which word have you turned into now?”
Likewise, if a token occurs several times in one input, each occurrence occupies a separate position and has its own row in states. Identical starting vectors can develop into different states.
Don't interpret “carrying contextual information” as storing text labels in fixed slots:
Slot 1: cat
Slot 2: like
Slot 3: the speaker is me
In the actual computation, information is represented through numerical values and their combinations, which later parts of the network use. There is no fixed legend translating every dimension into a human concept.
The model needs to know where, as well as what
Context includes token order, not just token identity. Compare:
我喜欢你。 (“I like you.”)
你喜欢我。 (“You like me.”)
Suppose each sentence is split into four tokens. They contain the same tokens, but their order—and meaning—differs.
An embedding lookup depends on token ID. The model also needs a way to use position and order during computation.
A position is simply where a token occurs in the sequence:
Position: 0 1 2 3
Token: 我 喜欢 你 。
The model needs to distinguish where tokens occur and in what order, as well as which tokens are present.
Architectures handle position in different ways. Some add position vectors to the initial representations; others introduce position information within attention. We won't go into the formulas here. In particular, don't picture this as merely appending a position number to the end of every vector.
These operations don't rewrite the original embedding table either.
Same shape, changing information
Suppose the context has 20 tokens and each state vector has 4,096 dimensions. In the architecture we're discussing:
After lookup: 20 rows × 4,096 columns
After layer 1: 20 rows × 4,096 columns
After layer 2: 20 rows × 4,096 columns
...
Each layer preserves the input/output shape, while changing the numbers inside it.
Rows still refer to the original input positions. Their vectors progressively incorporate context. The same token can start with the same embedding and develop different computational states in different contexts.
That leaves one question: how does a position bring information from other positions into its own computation?
Let's look at attention.
4 Attention: how does a position use its context?
We now know that states is the working data for this computation. Each row represents one input position and contains its current vector.
But “the vectors change” still leaves a lot unexplained.
Suppose the answer has reached I like. How can the next step use the translation request, the Chinese source text, and the answer written so far?
User request: Please translate “我喜欢猫” into English.
Generated so far: I like
What comes next: ?
This is where attention comes in. Here's its job in concrete terms:
For a given position, use its current state to gather information from the positions it is allowed to access, then combine that information with different weights.
What does “read” mean here? It means reading state vectors. The text has already become IDs and vectors; the model isn't paging through the original text word by word.
Pick one position and see what it can access
For this example, assume I like consists of two tokens: "I" and " like".
Focus on the last existing token, " like". Call its position i:
Formatted user request and role markers ... "I" " like"
↑
Current position i
This is a position that already exists in the input. The next token hasn't been selected yet.
In the causal self-attention we're discussing, position i can access itself and every earlier position:
allowed_positions = range(i + 1) # Positions 0 through i, inclusive
So it can use information from the instruction to translate into English, the source 我喜欢猫, and the generated prefix I like.
Every position follows this rule: access itself and earlier positions, but not later ones. That's what “causal” means here—the model can't peek at a later answer while predicting what comes next.
Step 1: assign weights to accessible positions
Being able to access many positions doesn't mean they all contribute equally.
Attention uses the current position's state, each accessible position's state, and learned parameters to compute matching scores:
match_scores = [
match_score(
states[i], # Position currently being processed
states[j], # One accessible position
head_parameters,
)
for j in allowed_positions
]
If 20 positions are accessible, this produces 20 scores—one per position.
These scores come from numerical computation. They aren't hand-written rules, and they don't simply mean “how similar are these two words?”
Next, softmax converts the scores into weights:
weights = softmax(match_scores)
The weights are nonnegative and sum to 1. They control the proportions used to mix information.
Sound familiar? Softmax appeared in Article 01, but it was operating on something different:
| Where softmax is used | What its outputs correspond to |
|---|---|
| Inside attention | Accessible context positions |
| During next-token selection | Candidate tokens in the vocabulary |
Attention weights are not next-token probabilities. They determine how the information supplied by each position is mixed in this attention calculation.
Even with fixed model parameters, the weights change with the input states. Training determines how to calculate them; the current context determines the values obtained.
Step 2: extract information and take a weighted sum
Now that we have weights, what are we mixing?
A learned transformation extracts an information vector from each accessible position's state:
values = [
extract_value(states[j], head_parameters)
for j in allowed_positions
]
These are still numerical vectors—not text labels such as “translation instruction,” “cat,” or “like.”
The model then takes their weighted sum.
Let's construct a separate tiny example with three accessible positions and two-dimensional value vectors:
Position 0: v0 = [1, 0] Weight: 0.2
Position 1: v1 = [0, 2] Weight: 0.3
Position 2: v2 = [2, 1] Weight: 0.5
The combined result is:
collected_info = 0.2 * v0 + 0.3 * v1 + 0.5 * v2
# Calculate each component separately:
# Component 1: 0.2×1 + 0.3×0 + 0.5×2 = 1.2
# Component 2: 0.2×0 + 0.3×2 + 0.5×1 = 1.1
# collected_info = [1.2, 1.1]
That's what “reading and combining information” means operationally: obtain vectors from accessible positions and mix them into a new vector using computed weights.
These positions, dimensions, vectors, and weights are illustrative—not measurements from our translation example. A larger weight means a larger mixing coefficient for that value vector. It is not, by itself, an explanation of the model's reasoning or a measure of factual reliability.
Step 3: incorporate the result into the current state
So far, we've followed one attention head at one position.
In multi-head attention, several heads compute their own results using their own parameters. Their outputs are concatenated and passed through an output projection, producing context_info[i] with the same dimension as the original state.
We don't need the concatenation and projection formulas yet. The important point is that the result is a vector that can be added to the current state:
new_states[i] = states[i] + context_info[i]
This preserves the original state while adding the information computed by attention. It's a residual connection; we'll place it back into the complete layer in the next section.
After this update:
- The token ID at this position hasn't changed.
- The original embedding table hasn't changed.
- The state vector has changed, so subsequent computation can use the newly incorporated information.
Other positions perform similar calculations, each with its own accessible range and weights. We're following one position only to make the process easy to see.
Put the attention steps together
Here is the work of one attention head at position i:
# Teaching pseudocode: one head at one position
# Normalization, position handling, and score scaling are omitted here.
allowed_positions = range(i + 1)
# 1. Match the current position against each accessible position
match_scores = [
match_score(states[i], states[j], head_parameters)
for j in allowed_positions
]
# 2. Convert matching scores into mixing weights
weights = softmax(match_scores)
# 3. Extract the value vectors to be combined
values = [
extract_value(states[j], head_parameters)
for j in allowed_positions
]
# 4. Take a weighted sum to obtain this head's output
head_output_i = weighted_sum(values, weights)
Combine the heads, then update the state:
context_info_i = concatenate_and_project(head_outputs_at_i)
new_states[i] = states[i] + context_info_i
Optional terminology: Query, Key, and Value. The current position's Query is matched against accessible positions' Keys to calculate matching scores. Values are the information vectors combined using the resulting weights. All three are computed from state vectors using learned transformations; they are not additional text inputs. That's enough terminology for now—we're tracing a program, not taking a detour into a linear algebra course.
Back in our translation example, attention gives the last position a way to use the request, the source text, and the answer prefix.
This does not imply a fixed internal program that says “find the translation instruction, then find the cat.” The current states and learned parameters determine the weights, and the calculations can differ across layers and heads.
We can now make “using context” more concrete: attention computes mixing weights and brings information from accessible positions into the current position's state.
But gathering information is only part of the process. The states also pass through a feed-forward network, and this pattern repeats across many layers. Let's zoom out to see how a complete Transformer layer works.
5 After gathering information: why stack so many layers?
In the previous section, attention let a position extract information from other positions, combine it with weights, and incorporate the result into its state.
That state still needs further processing.
Within a Transformer layer, this work is usually done by a feed-forward network, often called feed_forward, an FFN, or an MLP.
“Feed-forward” describes data flowing through the network from input to output. For now, think of it as a small neural network that processes each position's vector.
Attention gathers across positions; the FFN processes each position
Suppose attention has left us with three rows of states:
states[0]: the current vector at position 0
states[1]: the current vector at position 1
states[2]: the current vector at position 2
The feed-forward network processes each row:
processed_info[0] = feed_forward(states[0])
processed_info[1] = feed_forward(states[1])
processed_info[2] = feed_forward(states[2])
Two details matter:
-
This step does not directly read other positions. When processing
states[2], the FFN receives that row. Context gathered earlier is already reflected in its values. - All positions within the same layer share the same FFN parameters. The transformation is the same, but different input vectors can produce different outputs.
We wrote three calls for readability. Actual implementations usually process many rows in parallel.
The division of work is:
attention: extract and combine information across positions
feed_forward: further transform each position's current vector
But what does “further transform” actually involve?
Work through a vector, one calculation at a time
Here's a basic feed-forward network:
def feed_forward(x):
intermediate = x @ W1 + b1
activated = nonlinear_function(intermediate)
output = activated @ W2 + b2
return output
W1 and W2 are learned weight matrices; b1 and b2 are bias parameters. They remain fixed during ordinary inference.
The @ operator means matrix multiplication. Without diving into the matrix rules, you can think of it as recombining input values using learned coefficients.
Input vector
↓ First numerical combination
Intermediate vector
↓ Nonlinear transformation
Transformed intermediate vector
↓ Second numerical combination
Output vector
Let's build a tiny example we can calculate by hand. Suppose one position's vector has just two components:
x = [1, 2]
The first transformation produces three components:
# Expand the scalar arithmetic to make every step visible
intermediate = [
x[0] + x[1],
x[0] - x[1],
2 * x[1],
]
# Result: [3, -1, 4]
This is equivalent to choosing a particular set of weights to recombine the input. We've omitted bias and chosen simple coefficients for the demonstration.
Next, apply a simple nonlinear function: ReLU. It replaces negative values with zero and leaves the others unchanged:
activated = [
max(0, value)
for value in intermediate
]
# [3, -1, 4] → [3, 0, 4]
Finally, combine the values again to return from three dimensions to two:
output = [
activated[0] + activated[1],
activated[2] - activated[1],
]
# Result: [3, 4]
The complete sequence is:
[1, 2]
↓ First transformation
[3, -1, 4]
↓ ReLU: replace negative values with zero
[3, 0, 4]
↓ Second transformation
[3, 4]
That's a concrete example of “processing a vector”: numerical combinations and a nonlinear operation turn one representation into another.
The result [3, 4] is still an intermediate vector. It is neither a token ID nor a probability distribution over tokens.
All dimensions, parameters, and values here are illustrative. We use a basic two-layer FFN with ReLU to explain the mechanism. Actual models may use other activation functions, gated structures, or transformations without bias.
Why include a nonlinear function?
If we only applied these two transformations:
intermediate = x @ W1 + b1
output = intermediate @ W2 + b2
they could be collapsed into a single transformation of the same kind. Writing two steps wouldn't make the relationship fundamentally more expressive.
A nonlinear function lets the computation respond differently to different inputs.
In our example, this component:
x[0] - x[1]
survives ReLU only when it is positive. Change the input, and this component can switch from being suppressed to contributing to subsequent computation.
That gives the network a way to represent more complex relationships. Training adjusts the weights to make these transformations useful for prediction.
Still, don't assign a fixed semantic meaning to every intermediate value. Real models generally represent information through many interacting values, rather than a slot explicitly labeled “this is a translation task.”
Put attention and the FFN back into one layer
We can now write a simplified Transformer layer:
def transformer_layer(states):
# 1. Gather information across positions
context_info = attention(norm(states))
# 2. Add the result to the original states
states = states + context_info
# 3. Process each position's current vector
processed_info = feed_forward(norm(states))
# 4. Add the result to the current states
states = states + processed_info
return states
Notice the order: the FFN receives states that already incorporate the attention result.
Two supporting operations appear here.
norm() is normalization. For now, think of it as adjusting each vector's numerical scale to help stabilize subsequent computation. It does not convert the vector into token probabilities or select an answer.
This operation:
states = states + new_result
is a residual connection. It provides a direct path for the existing state to continue forward, while adding the result of the current computation.
Using our toy example, if the original state is [1, 2] and the FFN produces [3, 4], the sum is:
Original state: [1, 2]
FFN result: + [3, 4]
──────
Updated state: [4, 6]
We ignore normalization in this tiny calculation so we can isolate the addition.
The layer pseudocode uses a common arrangement in which normalization comes before each sublayer's computation. Specific architectures may differ. Our focus is how attention, the FFN, and residual connections work together.
Why repeat this across many layers?
Because every layer receives states that the previous layer has already processed:
states = embedding_table[context_ids]
for layer in transformer_layers:
states = layer(states)
This loop does not repeatedly feed the same initial vectors into the same function.
Typically, each layer has its own parameters. Even when the input and output shapes match, the transformations can differ:
Initial states
↓ Layer 1: gather, then process
Layer 1 output
↓ Layer 2: gather again using the updated states, then process
Layer 2 output
↓ Layer 3: continue the computation
...
The key is that the next attention layer reads contextualized states from the previous layer, rather than only the initial token embeddings.
Return to our request to translate 我喜欢猫 into English. At one layer, a position may have incorporated information about the task or source text. In the next layer, positions allowed to access it can read that updated representation. The model computes new matching scores and gathers information again, using the new states.
The FFN then processes those newly combined representations.
Gather across positions
↓
Process each position
↓
Gather again using the processed states
↓
Process each position again
↓
...
This creates more computational steps for combining information in complex ways.
But don't imagine a manually assigned checklist:
Layer 1: identify the translation task
Layer 2: understand “cat”
Layer 3: decide how to say it in English
Real models have no such tidy, fixed division of labor. Training shapes the computations, and information processing can be distributed across multiple layers and heads.
Who chooses the depth? Are more layers always better?
The number of layers is usually chosen when designing the architecture. A model might have 24 layers, 32 layers, or more. Training primarily learns parameters within that structure. Ordinary inference executes it; the model doesn't decide, “This question is hard—I'd better grow ten more layers.”
More layers provide a deeper computation path, but also add computation, latency, and training challenges. Quality depends on model width, training data, training methods, and other factors. Layer count alone cannot tell you how good a model is.
Stacked Transformer layers give the states repeated rounds of gathering and processing, allowing later computation to use the representations formed by earlier layers.
In the structure we're discussing, a layer can still have:
Input: 20 rows × 4,096 columns
Output: 20 rows × 4,096 columns
The FFN's internal dimension may change. Its output returns to the state dimension so that residual addition is possible.
After all the layers, we have a sequence of vectors that have undergone multiple rounds of contextual processing.
Next comes the final step: how does the last position's vector become scores for the entire vocabulary?
6 From the last position's vector to vocabulary scores
After the Transformer layers, we have updated state vectors. With 20 context tokens and 4,096 dimensions per position:
states: 20 rows × 4,096 columns
These vectors have been through several rounds of gathering and processing. They are not yet candidate-token scores.
To produce those scores, model() needs two more steps:
Take the last position's state
↓
Use the output layer to score every candidate token
Why the last position?
Return to our running example:
User request: Please translate “我喜欢猫” into English.
Generated so far: I like
What comes next: ?
Assuming the answer prefix is split into "I" and " like", the current sequence ends like this:
Formatted user request and role markers ... "I" " like"
↑
Last existing position
In the autoregressive language model we're discussing, the output at position i is used to predict the token immediately after it:
Output at "I" → predicts what follows "I"
Output at " like" → predicts what follows "I like"
We want to continue the answer written so far, so we use the last position:
last_state = states[-1]
-1 selects the last row. We take one vector out of the matrix:
states: 20 × 4,096
↓ Take the last row
last_state: 4,096 dimensions
Why can that row predict what comes next?
First, causal attention lets it access itself and all earlier positions. Second, training teaches the model to use that visible context to predict subsequent tokens.
So we don't select it merely because it happens to be last. Its prediction task is exactly the task we need at this point in generation.
Being able to use preceding information does not mean the last vector contains a lossless compression of the entire context. It is a representation used for prediction. It can miss information and lead to errors.
The other positions weren't computed for nothing. Their states participated in the contextual computations across earlier layers. At the final scoring stage of this generation step, however, we only need the last position's output.
One final numerical adjustment
In the architecture we've been using, we apply final normalization before scoring:
final_state = final_norm(last_state)
This adjusts the vector's numerical scale. It doesn't turn it into probabilities or change its dimension:
Before normalization: 4,096 dimensions
After normalization: 4,096 dimensions
Specific architectures may differ. Here, treat it as a final numerical processing step before the output layer.
The output layer gives every token a score
We now have final_state. The output layer converts it into as many numbers as there are tokens in the vocabulary:
scores = output_layer(final_state)
A common form is:
scores = final_state @ W_output + b_output
-
W_outputcontains learned output weights. -
b_outputis a bias; some models omit it. -
@denotes matrix multiplication.
With a 100,000-token vocabulary, and using the matrix orientation shown here:
final_state: 4,096 dimensions
W_output: 4,096 × 100,000
scores: 100,000 scores
The output layer maps one state vector to a score for every vocabulary candidate.
scores[token_id] is the score for that token as the next candidate. These scores are commonly called logits.
A three-candidate example you can calculate by hand
Real state vectors and vocabularies are large. Let's shrink both to see the arithmetic.
Suppose the final state has two dimensions:
final_state = [1, 2]
Our imaginary vocabulary contains just three candidates:
" cats"
" dogs"
"."
Give each candidate a vector of output weights, leaving out bias:
| Candidate token | Output weights |
|---|---|
" cats" |
[1, 2] |
" dogs" |
[2, 0] |
"." |
[-1, 1] |
To score a candidate, multiply the final state's components by the corresponding weights, then add:
Score for " cats": 1 × 1 + 2 × 2 = 5
Score for " dogs": 1 × 2 + 2 × 0 = 2
Score for ".": 1 × (-1) + 2 × 1 = 1
The result is:
scores = [5, 2, 1]
In matrix form:
# Each column holds one candidate's output weights
W_output = [
[1, 2, -1],
[2, 0, 1],
]
scores = final_state @ W_output
# [1, 2] @ W_output → [5, 2, 1]
We now have our next-token score table:
| Candidate token | Score |
|---|---|
" cats" |
5 |
" dogs" |
2 |
"." |
1 |
The vocabulary, state, and weights are all constructed for teaching. These are not the actual scores a real model produced for our translation request.
Why can these weights produce useful scores?
Developers don't fill them in as rules like:
If the user mentions a cat:
add 5 points to " cats"
The output weights are learned together with the preceding model parameters. Training encourages the whole network to cooperate:
Earlier network: form a final state using context
Output layer: use that state to score possible next tokens
During ordinary inference, output weights remain fixed. Different contexts produce different final_state vectors, which lead to different scores.
The output layer doesn't reread the original text. It receives the vector produced by the preceding computation.
Nor does it search the embedding table for a vector that exactly matches. It performs a scoring calculation over all candidates.
Some models share weights between the input embedding and the output layer. Even then, the operations serve different purposes: input lookup retrieves a vector by ID; output scoring uses the final state to compute vocabulary scores.
Returning scores completes this call to model()
Putting the steps together:
# states has already passed through every Transformer layer
# 1. Take the last existing position
last_state = states[-1]
# 2. Apply final normalization without changing the dimension
final_state = final_norm(last_state)
# 3. Map the vector to scores for the entire vocabulary
scores = output_layer(final_state)
We haven't selected the next token yet, and we haven't directly “translated the vector into text.”
What follows is familiar from Article 01:
probabilities = softmax(scores)
next_token_id = select_token(probabilities)
For our three-candidate example:
Scores: [5, 2, 1]
↓ Softmax
Probabilities: approximately [93.6%, 4.7%, 1.7%]
↓ Selection strategy
One token ID is selected
These probabilities are calculated over the three imaginary candidates. A real model scores its own full vocabulary. They describe the model's next-token distribution, not the probability that the answer is factually correct.
We've now opened up the original line:
scores = model(context_ids)
Inside it, the data follows this path:
Token IDs
↓ Lookup
Initial vectors
↓ Transformer layers
Contextualized state vectors
↓ Last position, then final normalization
final_state
↓ Output layer
Scores for the entire vocabulary
Next, we'll put all those pieces back into one continuous pseudocode example.
7 Put the whole model() pipeline together
We can now return to the question that opened this article:
scores = model(context_ids)
How does this one line turn IDs into scores for the next token? The pieces we've examined can now be connected.
Follow the complete data flow
Keep the generation loop paused just after I like:
# Original conversation + answer generated so far
context_ids = prompt_ids + answer_ids
Inside the model:
context_ids: token IDs for the current context
↓ Embedding lookup
states: initial vector for each position
↓ Transformer layers using position information
states: vectors after multiple rounds of contextual processing
↓ Take the last existing position
last_state
↓ Final normalization
final_state
↓ Output layer
scores: scores for every token in the vocabulary
Most of the computation happens in the Transformer layers: attention gathers information across positions, the FFN processes each position, and residual connections add the new results to the current states.
Each layer takes the preceding layer's output and continues the calculation.
A complete teaching implementation
We'll choose one simplified architecture so that the code forms a coherent whole:
- Each Transformer layer applies normalization before attention and before the FFN.
- Position information is incorporated inside attention.
- The FFN uses two linear transformations with ReLU between them.
- The vocabulary output layer omits bias.
This is teaching pseudocode, not a universal implementation shared by all models. Real architectures differ, but the main data flow we're following is all here.
# These objects already contain trained parameters:
#
# embedding_table
# transformer_layers
# final_norm
# W_output
#
# Ordinary inference uses these parameters without updating them.
def model(context_ids):
# 1. Look up initial states by token ID
# N input positions, D dimensions per position
# states has shape N × D
states = embedding_table[context_ids]
# 2. Prepare a position index for each token
positions = range(len(context_ids))
# 3. Pass the states through each Transformer layer
for layer in transformer_layers:
states = transformer_layer(
states,
positions,
layer,
)
# 4. Use the last existing position to predict the next token
last_state = states[-1]
# 5. Final normalization preserves the D-dimensional shape
final_state = final_norm(last_state)
# 6. Score every token in the vocabulary
# W_output has shape D × V; scores contains V values
scores = final_state @ W_output
return scores
def transformer_layer(states, positions, layer):
# A. Attention: extract and combine information across positions
context_info = multi_head_attention(
layer.norm1(states),
positions,
layer.attention,
)
# Preserve the input states and add the attention result
states = states + context_info
# B. FFN: process each position's current vector
processed_info = feed_forward(
layer.norm2(states),
layer.ffn,
)
# Preserve the current states and add the FFN result
states = states + processed_info
return states
def multi_head_attention(states, positions, attention):
head_outputs = []
# Each head computes with its own parameters.
# The loop shows the logic; implementations usually parallelize it.
for head in attention.heads:
queries = states @ head.W_query
keys = states @ head.W_key
values = states @ head.W_value
# This example incorporates position information inside attention
queries, keys = apply_position_information(
queries,
keys,
positions,
)
# Compute scaled matching scores between positions
match_scores = (
queries @ keys.T
) / sqrt(head.key_dim)
# Causal mask: position i cannot access positions after i
match_scores = mask_future_positions(match_scores)
# Compute mixing weights separately for each query position
weights = softmax(
match_scores,
axis="accessible_positions",
)
# Combine the value vectors using those weights
head_output = weights @ values
head_outputs.append(head_output)
# Concatenate features, then project back to D dimensions
combined = concatenate_along_features(head_outputs)
return combined @ attention.W_output
def feed_forward(states, ffn):
# Apply the same transformation independently to each row
intermediate = states @ ffn.W1 + ffn.b1
activated = relu(intermediate)
output = activated @ ffn.W2 + ffn.b2
return output
You don't need to memorize this code. Follow the key data objects:
| Data object | What it contains at this point |
|---|---|
context_ids |
Token IDs for the current context |
states |
The current vector at each position |
context_info |
Information combined by multi-head attention and projected back to the state dimension |
processed_info |
The result of feed-forward processing |
final_state |
The last position's vector after final normalization |
scores |
Next-token candidate scores for the entire vocabulary |
Inside attention, queries, keys, and values are intermediate vectors computed from the current states for matching and weighted combination.
Check the shapes along the way
Suppose:
Context length: N = 20
State dimension: D = 4,096
Vocabulary size: V = 100,000
The main sequence of shapes is:
context_ids
20 IDs
↓
Embedding lookup
↓
states
20 × 4,096
↓
Transformer layer 1
20 × 4,096
↓
Transformer layer 2
20 × 4,096
↓
...
↓
Take the last row
4,096 dimensions
↓
Final normalization
4,096 dimensions
↓
Output layer
100,000 candidate scores
Intermediate results inside a layer can have different shapes. The states passed between layers retain the shape N × D.
Reconnect to the generation loop
Once model() returns scores, the surrounding program does the work we covered in Article 01:
# Include the original conversation and the answer generated so far
context_ids = prompt_ids + answer_ids
# Score the next-token candidates using the current context
scores = model(context_ids)
# Convert scores to probabilities, then select a token
probabilities = softmax(scores)
next_token_id = select_token(probabilities)
# If generation hasn't ended, append the new token to the answer
if next_token_id != end_token_id:
answer_ids.append(next_token_id)
On the next iteration, the answer prefix is longer, the context has changed, and the model computes a new set of scores.
Also remember that softmax serves two different purposes in this pipeline:
Inside attention:
Matching scores → mixing weights over positions
During next-token selection:
Candidate scores → predicted probabilities over tokens
The mathematical operation is the same kind of operation; the objects and purposes differ.
What have we opened up?
In Article 01, we stayed outside the model and followed an answer being generated token by token.
In this article, we stepped inside model(). We watched IDs become vectors, followed those vectors as they incorporated context across layers, and saw the final state become candidate scores.
Now this line:
scores = model(context_ids)
stands for a data flow we can trace:
Look up initial states, repeatedly process them through attention and feed-forward networks, then map the last position's state to scores over the vocabulary.
That brings us to a new question.
If chatting doesn't change the parameters, how can the model pick up on things we said earlier—or tell us, “I'll remember that”?
In the next article, we'll unpack that promise: what stays in the current context, what the application stores, and how that information gets back into the model's input.
8 Previous article
English | 简体中文 · Series home · Part I
Previous: How Does a Message Become an Answer?
Next: When AI Says “I’ll Remember,” Where Does That Memory Go? — coming soon.







Top comments (0)