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 r...





