How an LLM
actually works
A text-generating LLM receives token IDs, turns them into vectors, repeatedly updates those vectors, and produces a probability distribution for the next token. A response appears by running that prediction loop again and again. This page follows one sentence through the core path, while calling out where real models differ. Click, drag, and test each step.
The shorter paths hide optional sections without simplifying the claims. Change paths at any time.
Scope, evidence & review policy
Scope: the core walkthrough describes autoregressive, decoder-style, text-generating models. Encoder, encoder-decoder, recurrent, state-space, multimodal, and product-specific systems can differ.
Evidence: badges distinguish computed, exact, conceptual, representative, and toy figures. Every technical section links its sources or states its limits.
Review: technically reviewed September 4, 2026. Fast-moving sections are reviewed quarterly; next scheduled review December 2026.
Swipe or scroll through the whole pipeline. Each stage has its own color, and that color follows you down the page.
The chop from text to IDs
Tokenization
Before a text model runs, a tokenizer converts the input string into a sequence of vocabulary entries. Each entry is represented by an integer ID; the exact pieces depend on that model's tokenizer.
A tokenizer takes a string and produces a sequence of integers. Each integer points to one entry in a fixed vocabulary: the tokenizer's frozen list of known pieces. Modern vocabularies hold anywhere from tens of thousands to a few hundred thousand entries.
One integer identifying one vocabulary entry. The original character string is not passed alongside it, although the ID still identifies the token piece that produced it.
The pieces usually aren't whole words. They're subword pieces. Type anything below and watch it split. The colored chips are the tokens, and the small number under each is its ID.
The number under each chip is that piece's fixed vocabulary ID. The model does not receive a separate character array, so operations that humans solve by visually inspecting letters can be awkward when several letters are packed into one token. That is one contributor—not the only contributor—to mistakes on spelling and character-counting tasks.
Tokenization helps explain these failures, but it does not determine them. A model can learn spellings from data, internally recover character patterns, or use a tool. Separating letters can sometimes help by making them explicit units. Number tokenization can likewise make digit-level algorithms harder to learn, although training data, architecture, and tool use also matter.
Different tokenizer vocabularies often draw different boundaries because they were trained with different algorithms, data, normalization rules, and target sizes. Models can also share a tokenizer, so the boundary belongs to the tokenizer—not inherently to the model family.
The practical upshot is compute, context usage, and sometimes price. The same text can occupy different numbers of tokens across APIs. Efficiency also varies by language and script: a tokenizer trained with weak coverage of a script may need more tokens for comparable text, but this must be measured for the specific tokenizer.
Why subwords, and not whole words or single letters? It's a trade-off, and subwords sit in the middle of two bad extremes:
A whole-word vocabulary would need a separate entry for every word in every language, millions of them, and it would still break the moment it met a word it had never seen, like a new product name or a typo. There's no entry to point at.
A byte-level vocabulary can be as small as 256 basic byte values, but sequences become longer because common words and phrases must be composed from many units. A Unicode character vocabulary is larger and still needs a strategy for unseen characters.
Subword tokenization splits the difference: frequent chunks become single tokens while rarer strings are composed from smaller pieces. Byte-level or byte-fallback designs can represent arbitrary input without an unknown-token failure.
The tokenizer's frozen menu of pieces, each with its own ID. If a piece isn't on the menu, the model can never receive it directly.
The classic example is asking an LLM how many times a letter appears in blueberry. The model may receive a few multi-character pieces rather than nine explicit character units. A correct answer therefore requires learned spelling knowledge, an internal decomposition, or a tool; the answer is not directly present as a character array in the input.
Capable models often pass this test because training can teach spelling patterns and decomposition strategies, and some products can call code or other tools. Success does not mean tokenization stopped mattering; it means the larger system learned or supplied a way around the mismatch.
Tokenizer implementations vary. GPT-style systems have commonly used byte-level BPE variants; several Llama releases use SentencePiece-based tokenizers. SentencePiece is a tokenizer framework, not a single segmentation algorithm: it supports both BPE and Unigram models. In every case, normalization, pre-tokenization, special-token handling, and fallback rules are part of the specification.
So what is a tokenizer, on disk?
The explainer above describes what tokenization does. A common BPE tokenizer distribution contains a vocabulary, ranked merge rules, and configuration for normalization, pre-tokenization, and special tokens. Other tokenizer families store different artifacts, and some bundle everything into one file.
"the": 464, "Ġkeys": 8251, "Ġswim": 9422, "ming": 2229, "Ġexploit":14561, "ation": 341
# ranked, in order: s w → sw sw im → swim m i → mi mi ng → ming Ġ swim → Ġswim at ion → ation
"bos_token": "<s>", "eos_token": "</s>", "model_type":"BPE", "add_prefix_space": true, "pre_tokenizer": "ByteLevel"
The key insight people miss: BPE does not store “swimming → swim + ming” directly. It stores an ordered list of merge rules, and applying them in rank order is the algorithm. Watch it build a word from single characters, one merge at a time:
Sources & limits
The live tokenizer is intended to reproduce GPT-2 byte-level BPE. The letter-counting diagrams explain an input-representation mismatch; they do not claim tokenization alone determines model capability.
The prompt is now a sequence of token IDs. The numeric value 8251 carries no ordinal meaning: it selects a learned row in the embedding table. The next stage shows that lookup.
From row index to geometry
Embeddings
A token ID is discrete: ID 8251 is not numerically “closer” to 8252 than to ID 10. An embedding table maps each ID to a learned vector that the network can transform.
A text decoder typically has an input embedding table with one row per vocabulary entry. Each row has the model's hidden width. The output projection may reuse those same weights—called weight tying—or use a separate matrix, so “every model has exactly one table” would be too strong.
A one-dimensional array of numbers. Neural-network layers transform and combine these arrays using matrix operations.
A giant learned lookup table: row number in, vector out. No human wrote a single entry. Training shaped all of it.
The ID therefore acts as an address. Its selected row is the token's input embedding, learned during training rather than written by a person. Calling it “the meaning” is tempting but incomplete: before attention, that row is the same wherever the token appears and cannot yet encode which sense the surrounding sentence requires.
The numbers the model learns during training. Every table and knob in this walkthrough, starting with this embedding matrix, is made of them. Billions of learned numbers, and together they are the model.
Input embeddings are context-free; hidden states are contextual. The lookup for bank starts from the same learned row in “river bank” and “bank approved the loan.” After attention and feed-forward layers mix in surrounding information, the two positions can develop different representations.
Geometric structure does emerge in learned representations, but the famous king − man + woman ≈ queen result comes from particular static word-embedding methods. It should not be treated as a guaranteed property of a modern LLM's subword input table.
Pick a sentence, then run the target token through a conceptual stack. The starting point is identical; context changes the trajectory:
Sources & limits
The row lookup is literal. The 2-D trajectories are explanatory projections, not model measurements. Similarity and linear analogies depend on the model, layer, tokenization, and probing method.
Injecting order
Positional encoding
The next stage is where tokens start comparing themselves to each other, a step called attention that we'll open up in a moment. That comparison, on its own, is completely blind to order. Without a position signal it can't tell that lock came before picks rather than after, and “lock picks” and “picks locks” are not the same sentence.
Whatever trick injects where a token sits into the math, since attention on its own is order-blind.
The original 2017 Transformer added a deterministic pattern of sine and cosine values to each token embedding. Different dimension pairs use different frequencies, so the same token at positions 1 and 5 enters the first layer differently.
The authors chose sinusoids partly because their values can be computed at unseen positions and relative offsets may be learnable from them. Later decoder models explored learned absolute embeddings, relative biases, RoPE, ALiBi, and other schemes. There is no single transition caused by one proven defect.
Can the encoding be evaluated there? A sinusoidal formula can generate a vector for position 5,000; a finite learned lookup table may not contain that row.
Can the trained model work there? Even when an encoding is defined beyond the training window, attention patterns and learned computations may not extrapolate. Long-context capability is an empirical property of the whole trained system.
So modern models (LLaMA, Mistral, Gemma, Qwen…) mostly switched to Rotary Position Embeddings, RoPE. Instead of adding a position vector, RoPE rotates each token's Query and Key vectors (two per-token vectors that attention compares; proper introductions in the next section) by an angle that grows with position. Drag the slider to move a token along the sequence and watch its vector turn:
Rotary Position Embeddings rotate pairs of Query and Key coordinates by position-dependent angles, introducing relative-position dependence into their dot product without learned position parameters.
RoPE became common in open decoder models because it is parameter-free and gives attention scores an explicit dependence on relative position. Its base frequencies and scaling rules still matter: extending a RoPE model beyond its training window often requires interpolation, frequency rescaling, additional training, or a combination of them.
Where tokens talk to each other
Attention
This is the mechanism the architecture is named after. Inside every layer, attention lets each token look at the other tokens it's allowed to see and decide which ones matter.
For each head, learned projections turn every input hidden state into a Query, Key, and Value. Queries and Keys determine the mixing weights; Values supply the vectors that are mixed. These are useful functional labels, not three symbolic objects stored inside a token.
Query and Key vectors produce a compatibility score. That score controls how much of the corresponding Value vector contributes to the output.
Each Query is compared with the permitted Keys using a scaled dot product. These learned compatibility scores need not correspond to human semantic similarity. Softmax converts the scores into non-negative weights that sum to 1, and the head outputs their weighted sum of Value vectors.
Multiply corresponding components and add the results. If vector lengths are controlled, a larger result often indicates stronger directional alignment.
Exponentiates and normalizes a list of scores into non-negative weights that sum to 1. Scale controls how concentrated those weights become.
Here is a deliberately constructed sentence-level example. Click a query token to inspect an illustrative attention pattern:
Pick were as the Query. Its Query vector gets compared, one dot product each, against the Key of every token it's allowed to see.
In the teaching pattern shown here, the score against keys is high and the score against upstairs is low. The numbers are authored to demonstrate the mechanism; they are not activations recorded from a named model.
Softmax normalizes those scores, then the head mixes the Value vectors. A high weight creates a strong contribution, but attention weights alone do not prove that a head represents a grammatical relation or explain the model's final prediction.
In a standard causal decoder, position 5 may attend only to positions 1 through 5. During training the later tokens are present in the batch but masked; during generation they do not exist yet. Implementations apply a mask before softmax so disallowed positions receive zero attention probability.
The blindfold over future positions. A token that's predicting what comes next isn't allowed to peek at it.
The cost: full self-attention forms a quadratic number of Query–Key comparisons during training or prompt prefill. During cached autoregressive decoding, one new token compares with the existing prefix, so that step grows linearly with current context length. FlashAttention reduces memory traffic and avoids materializing the full score matrix, while exact attention still performs quadratic arithmetic over a full sequence.
Parallel conversations
Multi-head attention
Multi-head attention runs several learned Query–Key–Value projections in parallel. Each head can produce a different mixing pattern, and a learned output projection combines their results.
Each parallel pass is a head. The part tutorials often get wrong: a head does not get a literal slice of the token vector. Each head has its own learned projection that maps the full vector down to its own smaller Q, K, V. With 4,096 numbers and 32 heads, each head works in 128 dimensions. But those 128 are a learned projection of all 4,096, not a fixed chunk.
The flow is: project every position into each head's Q/K/V spaces, run attention per head, concatenate the resulting head outputs, and apply a learned output projection. Implementations often compute all projections in fused matrices and reshape them into heads, but the mathematics is equivalent.
One self-contained attention pass with its own learned way of looking at the tokens.
Training does not assign human-readable jobs to heads. Researchers can sometimes identify consistent behaviors—copying, positional patterns, or syntactic correlations—but heads may be redundant, polysemantic, or difficult to interpret. A useful attention pattern is evidence about one computation, not a complete explanation of model behavior.
Autoregressive serving normally caches the Keys and Values already computed for the prefix. The KV cache grows with sequence length, layer count, batch size, element precision, and the number of KV heads. Depending on those values, it can become a major serving-memory constraint.
The saved Keys and Values for every token so far, kept so that generating token 1,001 doesn't mean redoing tokens 1 through 1,000.
Many decoder models reduce this cost with Grouped-Query Attention (GQA): multiple query heads share fewer Key/Value heads. Multi-query attention (MQA) is the extreme case with one KV head per layer. Toggle between MHA and one example GQA configuration:
Grouped-Query Attention: several query heads share each Key/Value head. Llama 2 70B uses 64 query heads and 8 KV heads; the resulting cache reduction is architectural, while quality and speed effects must be measured for each model and implementation.
The per-token transformation
Feed-forward network
After attention mixes information between tokens, every layer has a second step that gets far less attention itself. The feed-forward network (FFN) processes each token on its own: no cross-token mixing at all.
It does three things in order: expand the vector to a larger size, apply a non-linearity, then compress it back down. Press play:
That middle step is the whole reason the FFN exists. A non-linearity is a function that bends its input. The simplest one, ReLU, is almost comically plain: it outputs zero for any negative number and passes positive numbers straight through, unchanged.
Without that bend, expand-then-compress would just be two linear layers stacked back to back, and here's the catch: two linear layers in a row are mathematically identical to a single linear layer. A hundred of them in a row still collapse down to one. All that depth would buy you nothing.
The non-linearity is what breaks that collapse. Slip a bend between the layers and they can no longer be flattened into one, so the FFN can express something genuinely richer than a single matrix multiply. That's the entire point of the middle step.
The bend between linear layers. Without it any stack of layers flattens into one; with it, depth actually buys expressive power.
With common expansion ratios, dense FFNs hold a large share—and often the majority—of a decoder's block parameters. Probing and intervention studies show that FFN computations participate in factual recall and concept processing, but knowledge is distributed across layers and components rather than living in a tidy database of one-neuron facts.
Some models replace each dense FFN with a sparse Mixture of Experts (MoE): multiple expert FFNs plus a learned router that selects a subset for each token. The whole layer still pays memory and communication costs even though each token activates only part of the expert weights.
Mixture of Experts: use several FFN parameter sets and route each token to a selected subset. Capacity grows faster than per-token arithmetic, while memory, routing balance, and device communication remain real costs.
The plumbing that makes depth work
Residual stream & normalization
Two unglamorous pieces hold the whole tower together. The first makes the model additive instead of replacing: when attention or the FFN runs, its output usually doesn't overwrite the token's vector. It gets added to it.
New vector = old vector + the sub-block's output. Across thirty, fifty, a hundred layers, each contribution accumulates. That running sum is the residual stream, and it has a strange property: the original input embedding still has a direct additive path all the way into the final layers.
Instead of replacing a vector, add the block's output onto it: an express lane through the network for both information and gradients.
The “running sum” framing is useful in mechanistic interpretability because branch outputs can be studied as additions to a shared representation. It is still a coordinate-dependent description of a neural computation, not a literal message bus with independently readable facts.
Residual connections were popularized by ResNet. Identity shortcuts create direct paths for activations and gradients and made much deeper image networks easier to optimize. Transformers adopted the same residual pattern around attention and FFN sublayers.
The second piece is normalization. In a pre-norm decoder, the model normalizes the input to each attention or FFN branch; the branch's output is then added to the otherwise unnormalized residual stream. In a post-norm architecture, normalization happens after the addition. That placement changes optimization and signal propagation.
Transforms a hidden vector using statistics of its components, plus learned scale parameters and sometimes a learned bias. Its placement and exact formula vary by architecture.
The 2017 Transformer used post-norm. Many later decoder-only models use pre-norm, which generally improves optimization stability for deep stacks, though both variants and hybrids remain in use. Several open models use RMSNorm, which normalizes by root-mean-square magnitude without centering by the mean.
RMSNorm scales by the root mean square of the components and a learned gain. Unlike LayerNorm, it does not subtract the component mean.
Turning the last vector into a guess
Next-token prediction
The output projection can turn every final hidden state into one score per vocabulary entry. During next-token generation, only the logits at the newest position are needed to choose the following token.
If the vocabulary has 100,000 entries, that's 100,000 numbers. They're called logits: raw scores, any size, positive or negative, not yet probabilities. A softmax (the same operation from attention, in a new place) turns them into a probability distribution over what comes next.
The model's raw output: one unbounded score per vocabulary entry, before softmax turns them into probabilities.
A decoder can choose the highest-scoring token greedily or sample from a distribution. Temperature rescales logits before softmax; top-k and top-p restrict which candidates remain eligible. These are inference procedures, not changes to the model's learned weights.
A positive scale applied to logits before softmax. Lower values concentrate probability on high-logit tokens; higher values flatten the distribution. Effects on quality depend on the prompt and model.
Once a token is chosen, its ID is appended and the decoder computes the next position. A KV cache avoids recomputing earlier Keys and Values, but each new step still runs the model's layers for the new token and attends over the cached prefix.
For a standard autoregressive text model, next-token cross-entropy is the central pretraining objective. It rewards assigning probability to observed continuations. Capabilities such as code completion, factual recall, and some reasoning behavior can emerge because predicting the training distribution requires them—not because the loss contains separate “truth” or “reasoning” labels.
Assistant behavior is then strengthened and shaped through post-training: supervised demonstrations, preference optimization or reinforcement learning, safety training, and product-level controls. Pretraining and post-training are not universal recipes, and frontier systems may add modalities or auxiliary objectives.
A common chat interface serializes roles and messages into a token sequence using a chat template. Reserved tokens or structured control tokens mark boundaries. Post-training teaches the model how those markers relate to user, assistant, system, or tool turns; the markers are useful because of that learned behavior, not merely because they appear in the string.
<|im_start|>system You are a helpful assistant.<|im_end|> <|im_start|>user why is the sky blue?<|im_end|> <|im_start|>assistant
Role markers do not create operating-system permissions, but they are more than arbitrary early words: the model is trained to respond differently to role-labelled content. Across API calls, continuity comes from context assembled by the application—conversation history, summaries, or retrieved memory. Providers may reuse cached prefix computation, so “included in the logical context” does not necessarily mean “recomputed from scratch.”
Reserved vocabulary entries used for structure, boundaries, padding, or stopping. Whether raw input is allowed to contain them is a tokenizer and application policy, not a mathematical impossibility.
One efficiency technique is speculative decoding. A cheaper draft model proposes multiple tokens, then the target model evaluates them together. With the exact acceptance-and-resampling algorithm, the resulting samples follow the target distribution; approximate variants may trade fidelity for speed. The speedup depends on draft quality and hardware utilization.
Draft several tokens cheaply, verify them with the target model in parallel, accept a valid prefix, and resample correctly at the first rejection.
One skeleton, many models
Architecture vs trained weights
Many current language models belong to the Transformer family, but “Transformer” names a design space rather than one fixed blueprint. Public open-weight models expose these choices; proprietary systems disclose only part of their architecture and training recipe.
A common decoder skeleton is tokenization → embeddings → repeated attention and FFN blocks with residual paths and normalization → output logits. Models can differ in attention layout, position method, normalization, dense versus sparse layers, vocabulary, modality encoders, context strategy, and decoding implementation—before training data or post-training even enter the picture.
- Representation and architecture: tokenizer, width and depth, attention variant, position encoding, FFN or MoE design, modalities.
- Learned parameters: weights shaped by the data mixture, ordering, objectives, optimization, and compute budget.
- Post-training and inference: supervised tuning, preference or RL objectives, tool formats, decoding, quantization, and serving choices.
- The product around the model: system instructions, retrieval, memory, tools, permissions, and safety enforcement.
The learned tensors used by the network. A deployable model also needs its architecture configuration and tokenizer; weights alone are not an executable system.
Several motifs recur across successful open decoder models—pre-norm blocks, rotary positions, gated FFNs, and fewer KV heads—but there is substantial variation and no permanent consensus:
| Model | Query heads | KV heads | FFN | Total params | Active / token |
|---|---|---|---|---|---|
| LLaMA-2 70B | 64 | 8 (GQA) | dense SwiGLU | 70B | 70B |
| Mistral 7B | 32 | 8 (GQA) | dense SwiGLU | 7B | 7B |
| Mixtral 8×7B | 32 | 8 (GQA) | MoE · 8 experts, 2 active | 46.7B | ~12.9B |
Sources & limits
The table lists published configurations, not current proprietary frontier systems. “Active parameters” is an implementation-dependent compute proxy, not a complete latency or memory measure.
Beyond the transformer
Transformers were preceded by recurrent and convolutional sequence models, and those ideas never disappeared. Comparing them reveals a central trade-off: what information is retained, how much work scales with sequence length, and which computations can run in parallel.
A basic RNN repeatedly updates a hidden state from the current input and previous state. Backpropagation through time multiplies a chain of Jacobians; depending on their singular values, gradients can shrink or grow exponentially with distance. The slider reduces that matrix problem to one scalar factor so the mechanism is visible:
An LSTM adds a gated cell-state path whose update uses elementwise additions and multiplications. The gates themselves still require learned affine transforms and nonlinearities. When the forget gate stays near 1 and other terms are well behaved, gradients can propagate more effectively; this mitigates rather than abolishes long-range optimization problems.
An exact step-by-step recurrence has a sequential dependency: state 1,000 depends on state 999. Standard Transformer training exposes much more parallel work across token positions, while full attention uses quadratic pairwise comparisons and cached decoding stores a growing prefix. Structured state-space models seek linear sequence work with parallelizable training algorithms and fixed-size recurrent inference state.
A structured SSM uses a recurrent state update that can also be evaluated with convolutional or parallel-scan algorithms during training. Sequence work can scale linearly with length, and recurrent inference maintains fixed-size state. That state is a compressed summary, so constant memory is a trade-off rather than perfect recall.
Mamba's twist is making B, C, and the step size Δ functions of the input, so the model chooses per-token what to let into the state, what to read out, and on what timescale: selectivity, which is the one thing attention had that fixed-weight recurrences didn't.
Transformer blocks can also process representations derived from images, audio, or video. A multimodal system still needs modality-specific preprocessing, encoders or adapters, training data, and objectives; “turn it into tokens” is the interface, not the entire architecture.
The durable parts
Where this is going
Transformer-style blocks now appear across language, vision, audio, and multimodal systems, often alongside convolutional, recurrent, state-space, or modality-specific components. That is broad reuse of an architectural pattern, not proof that one architecture has absorbed every problem.
The active design space includes dense Transformers, MoE variants, state-space models, recurrent hybrids, and multimodal compositions. Rather than predict one winner, it is more useful to recognize the recurring engineering questions:
If you made it here, the next model card or architecture paper you open should read like a parts list you already recognize: every line maps to a mechanism you just poked at. That was the point of building this.
How to read this section
This is a framework for comparing designs, not a forecast. Check each model's primary paper or model card: shared labels such as “Transformer,” “MoE,” or “multimodal” hide important architectural and training differences.