The loop in one paragraph
A prompt goes in. A tokenizer converts it to a list of integer ids. An embedding table turns each id into a vector, positional information is mixed in, and the sequence passes through a stack of identical transformer blocks. Each block lets every position look at earlier positions, then transforms each position independently through a small neural network. The final block's output at the last position is projected onto the vocabulary, producing one score per possible next token. Those scores are turned into probabilities, one token is chosen, appended to the sequence, and the whole process runs again with a slightly longer input.
That is the entire mechanism. Everything an LLM appears to do, from writing a poem to debugging a stack trace, is this loop producing one token at a time, conditioned on everything that came before.
Step 1: tokenisation
The tokenizer is a fixed, learned mapping from strings to integers. Most modern models use a variant of byte-pair encoding. The algorithm starts from bytes or characters, counts which adjacent pairs occur most often in a training corpus, merges them into a new symbol, and repeats until it reaches the target vocabulary size. Frequent words end up as single tokens; rare words end up as two or three pieces; anything unseen can still be represented because the base alphabet covers every byte.
Vocabulary size is a trade-off. A larger vocabulary means fewer tokens per sentence, which lowers cost and shortens sequences, but it enlarges the embedding and output matrices and leaves rarer tokens with less training signal. Modern open models sit between 32K and 256K entries. Coverage is uneven across languages: English prose often averages about four characters per token, while Devanagari, Thai or Amharic can average closer to one or two, which means the same text costs several times more and consumes the context window several times faster.
Tokenisation also creates failure modes that look like reasoning failures. Ask a model to count the r's in "strawberry" and it may fail, because it never sees individual letters; it sees a small number of chunks. Ask it to reverse a string, do arithmetic on large numbers, or respect a character limit in a caption, and the same problem appears. Working around it means changing the representation: ask for the string split into characters, or give the model a tool that does the counting.
Step 2: embeddings and positions
Each token id indexes a row in an embedding matrix, producing a vector of a few thousand dimensions. These vectors are learned, not hand-designed. During training, tokens that behave similarly end up in similar regions of the space, and directions in that space often correspond to interpretable properties such as tense, number or sentiment.
A transformer has no inherent sense of order, so position must be injected. Early models added a sinusoidal position vector to each embedding. Most current models use rotary position embeddings, which rotate the query and key vectors by an angle proportional to position. Rotation has a useful property: the dot product between two rotated vectors depends on their relative distance, which is exactly what attention needs, and it extends more gracefully to long sequences than absolute positions.
Step 3: attention, the part that mixes context
Attention is how information moves between positions. Each token's vector is projected into three smaller vectors: a query, a key and a value. The query of one position is compared with the keys of all positions it is allowed to see, producing a score per position. Scores are scaled, passed through a softmax so they sum to one, and used to take a weighted average of the values. The result is a new vector for that position that blends in whatever was relevant elsewhere in the sequence.
Causality is enforced by a mask. In a decoder-only language model, position five may attend to positions one through five but not six or later, because during training the model must not see the answer it is supposed to predict. This is what makes the model autoregressive: each token is generated from the left context only.
Real models run many attention heads in parallel, each with its own projections, so different heads can track different relationships: previous mention of the same entity, matching brackets, subject-verb agreement, the instruction that governs the current sentence. The cost is quadratic in sequence length, because every position compares against every earlier position. Doubling the context quadruples the attention compute, which is why long-context inference is expensive even when memory allows it.
Two variants matter in practice. Multi-query attention shares a single key and value projection across all heads, and grouped-query attention shares them across small groups of heads. Both shrink the memory that attention needs at inference, at a small cost in quality. Nearly every efficient open model uses grouped-query attention, and it is the main reason long-context serving is affordable at all.
Step 4: the feed-forward network
After attention mixes information across positions, each position passes independently through a feed-forward network. It is usually two linear layers with a nonlinearity between them, and the hidden dimension is three to four times the model dimension, so most of the parameters in a transformer live here.
This is where a lot of the model's stored knowledge is thought to reside. Attention decides what information to gather; the feed-forward block transforms it, and its weights encode associations learned across the corpus. Interpretability work has found individual neurons and small groups that fire for specific concepts, languages or factual patterns, though the picture is far from a clean lookup table. Modern models often replace the simple nonlinearity with a gated variant such as SwiGLU, which performs slightly better at the same parameter count.
Mixture-of-experts models change the economics without changing the shape. Instead of one feed-forward block per layer they hold many, and route each token to two or four of them. Total parameters rise, so capacity rises, but each token pays only for the experts it uses, which complicates batching because tokens in the same batch may need different experts.
Step 5: residuals, normalisation and depth
Each block's attention and feed-forward outputs are added back to the running representation rather than replacing it. These residual connections create what researchers call the residual stream: a single vector per position that flows through the entire network, with each layer reading from it and writing an update into it. Early layers tend to handle local syntax and surface patterns; middle layers build entities, relations and task structure; later layers commit to an answer.
Normalisation layers keep the scale of activations stable across dozens of blocks. Most modern models normalise before each sub-block rather than after, which trains more reliably at depth, and use RMSNorm rather than LayerNorm because it is cheaper and works about as well.
Step 6: from hidden state to probabilities
At the top of the stack, the vector for the final position is normalised and multiplied by an output matrix whose rows correspond to vocabulary entries. The result is a vector of logits, one score per token, typically 32,000 to 256,000 numbers. A softmax converts them to probabilities.
The output matrix is often tied to the input embedding matrix, so the same weights read tokens in and score tokens out, which saves parameters and usually improves quality.
The model computes a distribution over the whole vocabulary on every step, even though only one token is chosen. In small models that projection is a substantial share of both compute and memory traffic.
Step 7: sampling decides the output
The distribution is not the output. A decoding rule picks a token from it, and that rule changes the character of the result more than most users expect.
Greedy decoding takes the highest-probability token every time. It is reproducible in principle, tends to be factual on extraction tasks, and tends to loop on open-ended generation. Temperature divides the logits before the softmax: below one it sharpens the distribution toward the top choice, above one it flattens it and gives unlikely tokens more room. Top-k keeps only the k highest-probability tokens and renormalises. Top-p, or nucleus sampling, keeps the smallest set of tokens whose cumulative probability exceeds p, so the candidate pool adapts to how confident the model is. Repetition penalties and presence penalties discount tokens that already appeared.
Structured output adds a mask. When the application requires valid JSON or a value from a fixed list, a grammar or schema constrains which tokens are allowed at each step, which turns a probabilistic text generator into something closer to a typed function. Constrained decoding cannot make the content correct, but it removes an entire class of parsing failures.
Temperature zero does not guarantee identical responses: batch composition, kernel nondeterminism and floating-point order introduce small differences, and one early token changes everything after it. Systems that need reproducibility should cache responses.
Prefill and decode are different workloads
Serving splits into two phases with opposite hardware profiles. Prefill processes the whole prompt at once. Every token is computed in parallel, so the work looks like large matrix multiplications, which keep a GPU's compute units busy. This phase is compute-bound, and it is what determines time-to-first-token.
Decode produces one token per step per sequence. Each step needs the full weight matrices but performs only a tiny amount of arithmetic per weight, so the GPU spends most of its time waiting for memory. Decode is memory-bandwidth-bound, and it is what determines tokens per second. This is why a model's parameter count predicts its single-stream speed so well: at 4-bit precision, a 7B model reads about 4 GB of weights per token, so on a device with 1 TB/s of bandwidth the ceiling is roughly 250 tokens per second, before overheads.
Batching is the lever that fixes the economics. Weights are read once per step and reused across every sequence in the batch, so adding sequences costs memory for their KV caches but very little extra bandwidth. That is why a serving engine can produce thousands of tokens per second in aggregate while a single stream runs at fifty.
The KV cache, and why context costs memory
Attention needs the keys and values of every previous token. Recomputing them on every step would be wasteful, so the model stores them. That store is the KV cache, and it grows linearly with sequence length and batch size.
The size is easy to compute. Each token needs two tensors per layer, keys and values, each with as many dimensions as the model's key/value heads times the head dimension. For a model with 28 layers, 4 key/value heads and a head dimension of 128, that is 2 x 28 x 4 x 128 = 28,672 values per token. At two bytes each, roughly 28 KB per token. A 32K-token conversation therefore holds about 0.9 GB of cache for one sequence. With 32 concurrent users at that length, the cache alone exceeds 28 GB, which is more than the weights.
This arithmetic explains most serving behaviour. Long prompts feel expensive because they consume cache that could have served other users. Concurrency limits are usually set by cache memory rather than by weight memory. Paged attention stores the cache in fixed-size blocks, the way an operating system pages memory, to stop fragmentation wasting a third of the available memory. Grouped-query attention exists to make the per-token cache smaller in the first place.
Training versus inference
Inference runs the forward pass with frozen weights. Training runs the forward pass, computes a loss against the true next token, then back-propagates through every layer to obtain a gradient for each parameter, and updates the weights with an optimiser. Back-propagation roughly doubles the compute of the forward pass and requires storing activations for reuse, which is why training needs far more memory than serving the same model.
A training step on a 7B model needs weights, gradients and optimiser state. In mixed precision with Adam that is roughly two bytes for weights, two for gradients and eight to twelve for optimiser moments, so eighty to a hundred gigabytes before activations. Serving the same model in 4-bit needs under six. That asymmetry is why parameter-efficient methods exist.
Training also differs in what it optimises. The loss is next-token prediction averaged over a batch, computed on tokens the model is allowed to see. Teacher forcing feeds the real previous tokens rather than the model's own guesses, which makes training stable but creates a gap with inference, where the model conditions on its own output. That gap is one reason a model can look excellent on a training metric and still drift or loop in production.
Where things go wrong
- Hallucination: the model produces the most plausible continuation, and plausible is not the same as true. It has no internal signal that separates recalled fact from confident invention.
- Attention dilution: with very long inputs, mid-context material gets less weight than the beginning and end, so a key instruction buried in the middle of a 100K-token prompt may be ignored.
- Context poisoning: an incorrect statement earlier in the context becomes evidence for later tokens, and the model will build on it rather than challenge it.
- Tokenisation artefacts: character counting, string reversal, rhyme, spacing and some arithmetic fail for reasons that have nothing to do with reasoning ability.
- Sampling instability: high temperature plus a long generation gives a wide spread of outcomes, so a single good sample is not evidence of reliability.
- Numeric weakness: arithmetic is pattern completion unless a tool or explicit scratchpad is used, and errors compound silently across steps.
What this means when you build
Several design rules follow directly from the mechanics. Put the most important instruction where attention is strongest, at the start and at the end, not buried in the middle of a long document. Keep prompts stable in their early tokens so providers can cache the prefix and cut both cost and latency. Ask for structured output and validate it, because a schema removes parser failures even though it cannot remove wrong values.
Keep retrieved context tight. Five well-chosen passages usually beat fifty mediocre ones, both in accuracy and in cost, because irrelevant text competes for attention with relevant text. Watch the token count of your system prompt: it is paid on every single request, and it grows quietly as features accumulate.
Finally, treat generation as a sampling process and design accordingly. Set temperature per task rather than globally, cap output length, use stop sequences, and evaluate with multiple runs so you see the distribution rather than one lucky draw.
Key points
- The pipeline is tokenize, embed, attend, transform, project, sample, repeat.
- Attention mixes information across positions and costs quadratically in sequence length.
- Feed-forward layers hold most of the parameters and much of the stored knowledge.
- Sampling settings, not just the model, determine output quality and consistency.
- Prefill is compute-bound and sets time-to-first-token; decode is bandwidth-bound and sets throughput.
- The KV cache, not the weights, usually limits how many users you can serve at long context.