A visual walkthrough · one sentence, all the way through

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.

Choose your depthOne explanation, three paths

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.

Open the 48-section claim ledger · Report a correction

Swipe or scroll through the whole pipeline. Each stage has its own color, and that color follows you down the page.

An interactive, click-and-drag walkthrough. Every figure is live and hand-built.
scroll to begin · stage 01
01

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.

Jargon check Token ID

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.

Live tokenizer · real GPT-2 vocabulary computed
These are real GPT-2 token IDs, computed by the actual byte-pair encoding algorithm on GPT-2's real 50,257-entry vocabulary — not a demo approximation. The Ġ is GPT-2's own marker for a leading space, which is part of the token: the model tells " token" apart from "token" because they're different entries. Chars-per-token is the compression ratio; higher means the vocabulary packed your text more tightly.

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.

Why token boundaries can make letter tasks awkward conceptual

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.

Same text · four real tokenizers

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:

The intuition

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 vocabulary trade-off
Whole-word vocabularies are gigantic and still choke on words they've never seen. Character vocabularies are tiny but force the model to rebuild every pattern from scratch. Subword keeps common pieces whole and composes rare words out of fragments.
Jargon check Vocabulary

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.

Why “how many B’s are in blueberry?” is a trick question

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.

vocab.json / inside tokenizer.jsonthe map
"the":    464,
"Ġkeys": 8251,
"Ġswim": 9422,
"ming":  2229,
"Ġexploit":14561,
"ation": 341
merges.txt (BPE only)the algorithm
# ranked, in order:
s  w        → sw
sw im       → swim
m i         → mi
mi ng       → ming
Ġ swim      → Ġswim
at ion      → ation
tokenizer_config.jsonthe rules
"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:

BPE merges, applied in order
Many current tokenizers operate on bytes or include byte fallback, which prevents unknown characters. GPT-2's byte-to-Unicode mapping displays a leading-space byte as Ġ. Other families differ: WordPiece uses continuation conventions such as ##, while a Unigram tokenizer chooses a likely segmentation from a scored vocabulary rather than replaying BPE merges.
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.

02

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.

The lookup · ID → row → vector mechanically exact
The tokenizer supplies ID 8251; an embedding lookup selects row 8251. The row is a learned starting representation—not a human-readable definition of the token.
Jargon checkVector

A one-dimensional array of numbers. Neural-network layers transform and combine these arrays using matrix operations.

Jargon checkEmbedding matrix

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.

Jargon checkWeights (parameters)

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.

The distinction that matters

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:

From one lookup to different contextual states conceptual
This animation is not a plot of activations from a specific model. It illustrates the architectural distinction: lookup supplies the same starting row; the transformer stack produces a context-dependent hidden state. Position information, introduced next, also changes what the network can distinguish.
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.

03

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.

Jargon checkPositional encoding

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.

Sinusoidal positions · each row is one position computed formula
Every horizontal stripe is the pattern added at that position. In this plot the faster-changing dimensions are on the left and the slower ones are on the right. The formula can produce values beyond the training length; that does not guarantee the trained model will use those positions well.

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.

Two questions to keep separate

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:

RoPE · one 2-D frequency pair simplified
This displays one 2-D coordinate pair. A real head contains many pairs rotating at different frequencies. In the attention dot product, the positional rotation contributes through the relative offset between Query and Key positions.
Jargon checkRoPE

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.

Long-context benchmarks have found “lost in the middle” behavior in some models and tasks: relevant evidence may be used less reliably when placed between the beginning and end. Treat that as a measured failure mode, not a law of every model or a guarantee that repeating instructions will help.
Sources & limits
04

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.

Q · K · V — three learned projections conceptual
The Q, K, V transforms are learned matrices, so training decides what each token should look for and what it should offer. The same token plays all three roles simultaneously.
Jargon checkQ, K, V

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.

Jargon checkDot product

Multiply corresponding components and add the results. If vector lengths are controlled, a larger result often indicates stronger directional alignment.

Jargon checkSoftmax

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:

Attention · click a query token illustrative weights
Walk the example through, step by step

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.

Causal mask · the attention grid mask exact · weights illustrative
Rows are Queries, columns are Keys. The blacked-out upper triangle is the future — scores there are forced so low that softmax gives them ~zero weight. Brighter cells = more attention. Notice the gold-ringed cell where were looks back at keys.
Jargon checkCausal masking

The blindfold over future positions. A token that's predicting what comes next isn't allowed to peek at it.

Induction heads are a well-studied circuit in small and medium Transformer models: they can continue patterns resembling A B … A → B. They provide concrete evidence that particular attention circuits can implement an in-context copying algorithm. They are not established as a complete explanation of in-context learning in frontier systems.

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.

Full-sequence attention comparisons computed scaling
For full attention over a sequence, the score grid has T×T entries before accounting for causal masking or optimized kernels. This plot is about comparison count, not total model latency.
Sources & limits
05

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.

One hidden state → head projections → recombined architectural
Every head sees a different learned view of the same token (not a different piece of it). Each runs its own attention pass; the outputs are concatenated and passed through a final learned linear layer that mixes them back into one full-size vector.

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.

Jargon checkAttention head

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.

Jargon checkKV cache

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:

Multi-head vs Grouped-Query Attention configuration example
Jargon checkGQA

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.

Sources & limits
06

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:

Project wider → activate or gate → project back common dense FFN
The original Transformer used a two-layer ReLU FFN with an inner width 4× the model width. Gated variants such as SwiGLU use two input projections and an elementwise gate before projecting back. Exact widths and activations are configuration choices.

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.

Why the bend matters

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.

Jargon checkNon-linearity

The bend between linear layers. Without it any stack of layers flattens into one; with it, depth actually buys expressive power.

The non-linearity, iterated over the years

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.

Features found by interpretability methods conceptual examples
Sparse-autoencoder studies can extract features associated with topics such as the Golden Gate Bridge; these learned features are combinations of model activations, not necessarily individual biological-style “neurons.” Labels are interpretations based on examples that activate a feature.
Model-editing methods such as ROME have demonstrated targeted changes to some factual associations in GPT-style models. That is evidence that particular FFN computations can causally affect recall—not proof that every fact occupies one location. Reliability, specificity, paraphrase generalization, and side effects all have to be evaluated.

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 · router picks 2 of 8 Mixtral-style example
Mixtral 8×7B has 8 experts per layer and activates only 2 per token — 46.7B total parameters but only ~12.9B used per token. You grow capacity without growing compute in proportion.
Jargon checkMoE

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.

Sources & limits
07

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.

The residual stream · a running sum down the layers architectural sketch
Attention and FFN branches read from the current state and add updates back to the residual stream. The final normalization and output projection read the final state to produce logits; the output projection does not write another residual update.
Jargon checkResidual connection

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.

Why normalization · controlled toy recurrence conceptual
Jargon checkLayer normalization

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.

Jargon checkRMSNorm

RMSNorm scales by the root mean square of the components and a learned gain. Unlike LayerNorm, it does not subtract the component mean.

Residual paths and normalization are two separate design choices that strongly affect trainability. The diagram isolates scale behavior for intuition; it is not a claim that every unnormalized network must diverge.
Sources & limits
08

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.

Jargon checkLogits

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.

From illustrative logits to probabilities computed softmax
Jargon checkTemperature

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.

The generation loop
Predict → append → predict → append, until the model emits an end-of-sequence token or hits a length limit.
The one idea to take away

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.

One common chat serialization pattern illustrative
one flat token streamthe whole chat
<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
why is the sky blue?<|im_end|>
<|im_start|>assistant
This resembles one family of templates; exact tokens and roles vary. Tokenizer and API rules normally reserve control tokens so ordinary user text cannot accidentally create an equivalent trusted role boundary. Generation may stop on an end-of-turn token or on application-configured stop conditions.

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

Jargon checkSpecial tokens

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.

Jargon checkSpeculative decoding

Draft several tokens cheaply, verify them with the target model in parallel, accept a valid prefix, and resample correctly at the first rejection.

Sources & limits
09

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.

What's commonly shared vs what can differ design-space map
The boxes are recurring concepts, not proof that implementations are identical. Architecture, learned weights, tokenizer, data mixture, objectives, post-training, inference strategy, and product scaffolding can all affect behavior.
  1. Representation and architecture: tokenizer, width and depth, attention variant, position encoding, FFN or MoE design, modalities.
  2. Learned parameters: weights shaped by the data mixture, ordering, objectives, optimization, and compute budget.
  3. Post-training and inference: supervised tuning, preference or RL objectives, tool formats, decoding, quantization, and serving choices.
  4. The product around the model: system instructions, retrieval, memory, tools, permissions, and safety enforcement.
Jargon checkWeights

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:

Recurring choices in several 2023-era open models historical examples
These choices accumulated after the 2017 Transformer and are common, not universal. Hover a choice to connect it to the corresponding lesson.
ModelQuery headsKV headsFFNTotal paramsActive / token
LLaMA-2 70B648 (GQA)dense SwiGLU70B70B
Mistral 7B328 (GQA)dense SwiGLU7B7B
Mixtral 8×7B328 (GQA)MoE · 8 experts, 2 active46.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.

10
What came before, what's circling back

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:

Gradient through time — scalar toy model simplified
0.88
toy signal from k steps back  =  (scalar factor)k  ·  real RNNs multiply matrices and activation derivatives instead

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.

Three sequence-model trade-offs — tap a row high-level comparison
Each architecture makes different trade-offs in parallelism, state size, interaction cost, and how past information is compressed. No finite-state model provides lossless “unbounded lookback.”
State space models: the RNN, resurrected

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.

One image-to-language path (LLaVA-style) architecture example
A LLaVA-style system encodes image patches with a vision tower, projects the resulting features into the language model's width, and inserts them into the sequence. The number of visual tokens depends on preprocessing and architecture. Qwen2-VL instead describes dynamic-resolution visual tokens and multimodal rotary positions spanning temporal, height, and width dimensions.
Sources & limits
→

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:

Eight questions this walkthrough gives you tools to ask
Represent the input · create learned states · encode order · move information between positions · run multiple computations · transform each position · keep optimization stable · produce and decode outputs.

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.

Brought to you with ❤ by Olivier Laflamme