What the model actually does
Tokens, attention, sampling and frozen weights: what the model computes when it writes a reply, and why a confident wrong answer is its normal output when facts are missing.
Classifying messages into queues helped the triage desk, but customers still waited for an agent to write the answer. The team now wants the assistant to write answers itself. A customer types “why was my order for 40 shares rejected at 3:28?” and the assistant should reply with a correct, specific explanation. For that the team will use a large language model, and this chapter explains what such a model computes when it produces that reply.
There is a practical reason to understand the internals rather than treat the model as an API that returns text. Almost every behaviour the team will fight in later chapters (the confident wrong answer, the bill that grows with conversation length, the different reply to the same question, the order id it miscopies) follows directly from the mechanism. Knowing the mechanism tells us which problems to fix in the prompt, which in the surrounding code, and which cannot be fixed at all.
The only thing it outputs is a distribution over the next token
A language model takes a sequence of tokens and returns, for every token in its vocabulary, a probability that it comes next. That is its entire output. To write a reply, the surrounding software picks one token from that distribution, appends it to the sequence, and runs the model again on the longer sequence. A 200-token answer is 200 runs of the model, each one seeing everything before it, including the tokens it has just produced.
The sequence it sees is assembled by our code. It contains the system prompt the team writes, any help-centre passages we retrieve, the conversation so far, and the customer’s latest message, all flattened into one list of tokens. The model has no other input. It does not know which customer this is, what time it is, or what the order book says, unless those facts appear somewhere in that list.
Tokens are the unit everything is counted in
Models do not read characters or words. They read tokens, chunks of text drawn from a fixed vocabulary, commonly somewhere between 100,000 and 250,000 entries. The vocabulary is built before training by a procedure called byte-pair encoding: start with individual bytes, find the pair of adjacent symbols that occurs most often in a large sample of text, merge it into a new symbol, and repeat until the vocabulary is the desired size. Common words end up as single tokens. Rarer words are split into pieces.
For English prose a token averages about four characters, or roughly three-quarters of a word, so a 900-word help article costs about 1,200 tokens. Other text costs more. Scripts that were less common in the tokenizer’s sample, such as Devanagari in many tokenizers, can take several times as many tokens for the same content. Identifiers fare worst of all. An order id like ORD-88213 or an ISIN like INE002A01018 is not a word the tokenizer knows, so it is cut into several fragments, and exactly where the cuts fall depends on the tokenizer.
This has consequences the team will meet directly. Prices and context limits are counted in tokens, so a Hindi-speaking customer’s conversation can cost more than an English one with the same content. And the model never sees the individual digits of an order id as separate items, only the fragments. Asking it to check whether two long ids match digit by digit, or to count characters, is asking it to reason about something its input does not directly show. When the assistant needs to look up order ORD-88213, our code should extract the id and query the order system; the model should not be trusted to copy it perfectly from memory of an earlier turn without a check.
Attention is how each token gathers what it needs
Each token first becomes a vector by lookup in an embedding table, exactly as in the previous chapter, with a little extra information added to mark its position. The problem from that chapter was that averaging these vectors loses order and context. A transformer instead lets each position build a new vector by drawing on the positions before it, and it does this through attention.
Take the sentence “The exchange rejected my order because it”, and consider the position for “it”. To predict what comes next, the model would do well to know what “it” refers to. In attention, every position produces three vectors from its current vector, each by multiplying with a learned matrix: a query (what this position is looking for), a key (what this position offers to others) and a value (what it will pass along if chosen). The query of “it” is compared with the key of every earlier position by a dot product, which gives a score for each.
Suppose, with tiny four-number vectors, the scores come out as 2.0 for “order”, 1.0 for “exchange” and 0.5 for “rejected”, and near zero elsewhere. They are divided by the square root of the vector length, here 2, giving 1.0, 0.5 and 0.25. A softmax turns them into weights that sum to one: e1.0 = 2.72, e0.5 = 1.65 and e0.25 = 1.28, which sum to 5.65, so the weights are 0.48, 0.29 and 0.23. The new vector for “it” is the weighted sum of those three positions’ value vectors, nearly half of it drawn from “order”. The division by the square root matters: in real models the vectors have a hundred or more numbers, raw dot products get large, and without the scaling the softmax would put nearly all its weight on one position and pass back almost no gradient during training.
Three details complete the picture. First, a mask stops each position from looking at later ones, so “it” cannot peek at the words after it. That is what allows the model to be trained on predicting every next token in a document at once. Second, a layer runs many attention computations in parallel, called heads, each with its own query, key and value matrices, so that one head can follow references while another tracks, say, which number is a quantity and which is a price. In trained models a few heads can be seen doing recognisable jobs like this; most are much less tidy. Third, nothing in the mechanism says which relationships matter. The matrices are learned, by the same gradient descent as before, from the single objective of predicting the next token.
A conversation’s prompt grows from 4,000 tokens to 8,000. In each attention head of each layer, how many more query-key comparisons does the model make?
Show the worked answer
Four times as many, not twice. Every position compares its query with every earlier position’s key, so the count grows with the square of the length. At 4,000 tokens there are about 8 million comparisons (half of 4,000 × 4,000, because of the mask); at 8,000 there are about 32 million.
The rest of the model’s work, the per-position layers described next, grows only in proportion to length, so it doubles. For prompts of a few thousand tokens the proportional part still dominates the total; the squared part takes over as contexts grow into the tens and hundreds of thousands. The inference chapter turns this into seconds and money.
What a transformer computes, from tokens to probabilities
A transformer is a stack of identical blocks, a few dozen of them in a typical model. Each position carries one vector through the whole stack, often called the residual stream. Each block reads that vector, computes a change, and adds the change back on, the residual connection from the previous chapter. Inside a block there are two steps. The attention step moves information between positions, as above. Then a feed-forward step, a small two-layer network with a nonlinearity in between, transforms each position’s vector on its own. Each step is preceded by a normalisation layer. Much of what the model “knows” in the sense of facts and associations appears to be stored in the weights of these feed-forward layers.
After the last block, the vector at the final position is multiplied by one more matrix that produces a score, called a logit, for every token in the vocabulary. A softmax turns the logits into the probability distribution we started with. That is the full computation: look up embeddings, run a few dozen blocks of attention and feed-forward, project to the vocabulary, softmax.
A useful rule of thumb follows. Producing one token takes about two arithmetic operations per parameter (one multiply and one add for each weight), plus the attention comparisons. A model with 8 billion parameters therefore does around 16 billion operations per token, and a 70-billion-parameter model around 140 billion. Those operations, and the memory needed to hold the weights they use, are what we pay for when we pay for inference.
How the weights got their values matters too. The model was first trained on a very large amount of text to predict the next token, which gives it grammar, facts, styles and a broad sense of how documents continue. It was then trained further on examples of conversations in a fixed format, with markers separating a system message, user turns and assistant turns, and on human or model judgements of which replies are better. That second stage is why it answers a question instead of continuing it with more questions. Underneath, the chat format is still tokens: the role markers are special tokens in the same sequence. The fine-tuning chapter returns to this second stage.
Sampling turns probabilities into a reply
Suppose the assistant has written “Your order was rejected because of insufficient” and the model’s logits for the next token are 3.0 for “margin”, 2.5 for “funds”, 1.5 for “balance” and 0.0 for “liquidity” (ignoring the long tail). A softmax gives probabilities of 0.53, 0.32, 0.12 and 0.03. Something has to choose one.
Temperature divides the logits before the softmax. At a temperature of 0.5 they become 6, 5, 3 and 0, and the probabilities sharpen to 0.70, 0.26, 0.04 and 0.002. At 2.0 they become 1.5, 1.25, 0.75 and 0, and the probabilities flatten to 0.40, 0.31, 0.19 and 0.09. As the temperature approaches zero, the choice becomes always the top token. Top-p sampling adds a cut: keep the most likely tokens until their probabilities add up to p, and sample only among those. With p = 0.9 at temperature 1, “margin” and “funds” together reach 0.85, adding “balance” reaches 0.97, so “liquidity” is excluded.
For a support assistant that explains policies, we want low temperature: the most likely explanation, worded consistently. Higher temperature is for drafting marketing copy, not explaining why a margin call happened. But low temperature is not a guarantee of identical output. Many providers do not promise determinism even at temperature zero, because the floating-point arithmetic can differ slightly depending on how a request is batched with others on the same hardware, and a tiny difference in one logit can change which token wins a close race. Once one token differs, everything after it is conditioned on a different sequence. Tests that compare the assistant’s output to an expected string character by character will be flaky; the evaluation chapter deals with checking meaning instead.
Why the model answers confidently from the wrong year
Here is the failure that most shapes the rest of this pathway. In an early prototype the team sent customer questions to the model with only a short system prompt (“You are the support assistant for a stock-broking app. Answer helpfully.”). A customer asked, “I sold my shares this morning. When can I withdraw the money?”
Walk through what the model has to work with. Its weights were fixed at training time, with a knowledge cutoff some months before deployment. The training text contained thousands of discussions of settlement and withdrawals, across many brokers, several countries and years of rule changes. The prompt contains nothing about this broker’s policy. So when the model reaches “You can withdraw the proceeds”, the distribution over the next tokens reflects whatever was common in that mixture. It produced “after two working days, once the trade settles”, fluently and without hedging.
That answer described a settlement cycle the broker no longer used, and it ignored the broker’s own rule about when sale proceeds become available for withdrawal, which is in the help centre. Nothing inside the model flags that the continuation is uncertain or outdated. There is no lookup that failed and no error to catch. The model did the one thing it does, produce a likely continuation, and likely and true came apart. This is what “hallucination” means mechanically, and it is why the word is somewhat misleading: the model is not malfunctioning when it does this.
The fix is to change the input, since the weights are fixed. The team retrieves the relevant help-centre article, places it in the prompt, and instructs the model to answer from the provided articles and to say it does not know, and offer to raise a ticket, when they do not cover the question. With the article present, the distribution after “You can withdraw the proceeds” is dominated by the article’s wording, because attention can draw on those tokens directly. The cost is real: about 1,000 to 3,000 more tokens per turn, a retrieval system to build and maintain, and a new failure mode when retrieval returns the wrong article. The context chapter is about paying that cost well. It also reduces rather than eliminates the risk; a model can still blend its prior with the article, which is why answers need checks.
| What we see | Mechanism | Where we deal with it |
|---|---|---|
| Outdated or invented policy, stated confidently | frozen weights; continuation of common patterns | put the source in context (context chapter) |
| Miscopied order id or wrong character count | ids split into fragments; no character-level view | normalise ids in a structured field, then validate them in code before any lookup |
| Different reply to the same question | sampling, plus batch-dependent arithmetic | low temperature, structured output, meaning-based evals |
| Cost and delay grow with conversation length | every new token attends to every earlier one | context budgets (inference and context chapters) |
| An instruction buried mid-prompt is ignored | attention spread across thousands of tokens | prompt structure and placement (prompting chapter) |
How much of this you need day to day
Nobody on the assistant team will compute attention weights by hand at work. The point of knowing the mechanism is to classify problems quickly. If a failure comes from missing information, no amount of rewording the instructions will fix it; the information has to enter the context. If it comes from sampling, retries and constrained output help. If it comes from the cost of long sequences, the fix is in what we choose to include. A team that cannot make these distinctions tends to respond to every failure by editing the system prompt, and the prompt grows into a list of patches that interact in ways nobody can predict.
There are also limits to what this picture explains. It tells us what the model computes, not why a particular model answers a particular question well or badly; that is an empirical question, settled by measuring on our own questions. And the details differ between model families (how positions are encoded, how many key-value heads there are, whether some layers route each token to a subset of specialised feed-forward networks). Those details change speed and cost more than they change behaviour, which brings us to the next chapter.
Serving and inference economics takes the two numbers this chapter produced, the operations per token and the cost of attending to a long context, and turns them into what the business cares about: how long a customer waits for the first word of a reply, and what each support conversation costs.
Two hours, and transformers stop being mysterious.
The diagrams most people picture when they think about attention.
The original transformer paper. Read it after the Karpathy video, not before.