← writeups

// explainer · llms

Token to Logit

levels 0 to 3 · 33 clips · level 3 complete

This page follows one tiny model, Pico, through everything a language model does between receiving text and choosing the next word. Pico has a vocabulary of ten words and 664 weights, small enough that every number can be checked by hand. Next to it, the same quantities are given for Llama-3-8B, so each idea is shown once at a size you can see and once at a size you would actually run.

level 0

The whole picture: one function, in a loop

What does a language model compute, what shape does the data have at each stage, and which families of models exist?

Why start here

Everything a transformer does serves one output: a list of scores, one per word in its vocabulary, for the token that should come next. Those scores are called logits. Generating text is not a second mechanism on top of that. It is the same function, called again with the chosen token added to the end of the input.

Two facts are worth carrying through everything that follows. First, the first call processes the whole prompt in parallel, and each later call processes one new token and reuses what the earlier ones computed. Second, the data keeps one shape all the way through the model, and every mechanism in the later levels is a transformation that preserves it.

The loop

Text is cut into tokens and each token becomes an integer id. Each id is swapped for a vector of numbers. A stack of identical blocks rewrites those vectors. The vector of the last token is turned into logits, a sampler picks one token from them, and the loop starts again with that token appended.

text"the cat sat"
tokeniseids [1, 2, 3]
embed[n_embd × n_tokens]
block × n_layer norm → attention → add norm → feed-forward → add shape unchanged: [n_embd × n_tokens]
norm · outputlogits [n_vocab]
samplesoftmax, pick "on"
One call of the model, left to right. The dashed line is the loop.

The clip runs that loop twice on Pico. The first call turns the cat sat into on with probability 0.345; the second, fed only the new token, produces . with probability 0.309. Watch where the logits come from: only the last column of numbers is used, and the probabilities appear one step later, in the sampler.

Clip 1. White numbers are Pico's own, or follow from them. Grey numbers inside the block are illustrative: the source prints only part of Pico's weights.

The shape to hold on to

Between the embedding and the output, the data always has the same shape: one vector of n_embd numbers per token. This is the residual stream. Every block reads a copy of it, computes something, and adds the result back. At the very end the shape changes once, to one score per vocabulary entry: [n_vocab × n_outputs], one column of scores for each token whose output was asked for.

Mathematical notation writes that shape [n_embd × n_tokens]. The code stores the same tensor as ne = [n_embd, n_tokens]: the first index is the one that varies fastest in memory, which is the feature dimension. The clips use the code's spelling.

inside the modelblocksat the end
Pico[8 × 3]1logits [10]
Llama-3-8B[4096 × n_tokens]32logits [128 256]

The next clip walks through one full pass of Pico, twenty operations, and draws every tensor to scale. The stream on the left never changes size. Inside attention it is split into heads and turned into score tables; inside the feed-forward part it is widened to 12 rows and brought back to 8. The card on the right gives the same shape for Llama-3-8B at each step.

Clip 2. Twenty steps of one forward pass. Weight matrices are drawn to scale, one dot per weight; the memory chip is the cache that the next section is about.

Prefill once, then decode

The two calls in clip 1 were not the same amount of work. The first one, the prefill, pushed the whole prompt through at once. The second one, a decode step, pushed through a single new token and reused what the earlier tokens had already computed.

prefill · the prompt, all tokens at once

thecatsat

  • n_tokens = 3, positions 0, 1, 2
  • every token attends to itself and to earlier ones
  • one matrix multiply per weight covers all three tokens
  • logits are needed only for the last token

compute-bound

decode · one token, reusing the cache

thecatsaton

  • n_tokens = 1, position 3
  • its keys and values join the cache
  • it reads all four cached positions
  • each weight is read once per token

memory-bound

Outlined tokens are computed in this call; the others come from the cache.

What is reused are the keys and values each token produced inside attention. They depend only on that token and the ones before it, so once computed they never change. The clip shows the cache filling, the attention weights of both calls with Pico's real numbers, and then counts the work with and without a cache.

Clip 3. Attention weights and cache sizes are Pico's and Llama-3-8B's. The work count runs five calls; the source computes the first two.

Three families, one set of parts

Pico is a decoder-only model, the kind used for generation. Two other families are built from the same block. What differs is small enough to list.

decoder-only

generation

block: self-attention (causal) + FFN block … block ↓ logits for the next token
mask
causal: a token reads itself and earlier ones
examples
LLAMA, MISTRAL3, QWEN3, GEMMA3, DEEPSEEK2, OPENAI_MOE (GPT-OSS) …
calls
llama_process then llama_sampler_sample
in the code
LLAMA_ATTENTION_TYPE_CAUSAL

encoder-decoder

translation, T5

encoder block encoder block bidirectional
output [n_embd × n_enc]
decoder block decoder block causal self-attn
+ cross-attn to encoder
second attention
cross-attention: every decoder block reads the encoder's output, computed once
examples
T5, T5ENCODER
calls
llama_process to encode the input once, then to decode from the start token
in the code
llama_model_has_encoder, tensors cross_attn_q/k/v, build_attn_inp_cross

encoder-only

embeddings, reranking

block: self-attention (bidirectional) block … pooling: mean / cls / last / rank ↓ one vector per sequence
mask
none: every token reads every token
examples
BERT, NOMIC_BERT, JINA_BERT_V2, GEMMA_EMBEDDING …
calls
llama_get_embeddings_seq; no sampler
in the code
LLAMA_POOLING_TYPE_*; no cache: build_attn_inp_no_cache

causal self-attention bidirectional self-attention pooling head

and without attention, or mixed. Recurrent and state-space models (MAMBA, MAMBA2, RWKV7) keep a fixed-size state per sequence instead of a growing cache. Hybrids (JAMBA, GRANITE_HYBRID, LFM2, NEMOTRON_H) interleave both (level 8).

Same parts, different wiring. Three things change: the mask, a second attention, and what becomes of the final hidden states.

The clip builds the decoder-only stack piece by piece, then changes it in two places to get an encoder, then puts one of each side by side and bridges them. The small 3 × 3 icon is the mask: a row is the token asking, a column is the token being read.

Clip 4. The decoder tokens y1 and y2 are placeholders for generated output.

The block is the same two sub-layers in every family. llama.cpp lists 180 architectures at the time of writing (150 when the source page was written), with 187 graph files under src/models/. Every one of them is a wiring of the mechanisms in levels 1 to 9.

Two models to keep in mind

Every later level uses the same two models: Pico for arithmetic you can follow, Llama-3-8B for scale. The second column gives the name llama.cpp's code uses, a field or a getter of llama_hparams (several are stored per layer), and the entry of the model file it is read from (%s stands for the architecture name). The vocabulary size is the one exception: it is the length of the token list, not a field of llama_hparams.

hyperparameterfield · GGUF entryPicoLlama-3-8Bmeaning
vocabulary size n_vocab%s.vocab_size, or the length of the token list 10 128 256 number of distinct token ids; length of the logits vector
model width n_embd%s.embedding_length 8 4 096 size of the vector carried per token through the blocks
depth n_layer%s.block_count 1 32 number of blocks
query heads n_head%s.attention.head_count 4 32 independent attention patterns per block
key/value heads n_head_kv%s.attention.head_count_kv 2 8 fewer than n_head means grouped-query attention
head size n_embd_head_k, n_embd_head_v%s.attention.key_length, %s.attention.value_length 2 128 usually n_embd / n_head
feed-forward width n_ff%s.feed_forward_length 12 14 336 hidden size of the feed-forward part, typically 2.7 to 4 × n_embd
context n_ctx_train%s.context_length 8 8 192 positions the model was trained for; n_ctx at runtime may differ
RoPE base rope_freq_base_train%s.rope.freq_base 10 000 500 000 how fast positional angles turn (level 3)
parameters sum of tensor sizes 664 8.03 B counted below

Counting the parameters

The last row of that table is the first thing worth checking by hand, because a model's size is nothing more than a sum of matrix sizes. Inside one block, attention holds four matrices (queries, keys, values, output) and the feed-forward part holds three. Around the blocks sit two matrices as tall as the vocabulary: the embedding table and the output head.

With d for the head size: the query matrix W_q is [n_embd × n_head·d]; the key and value matrices W_k and W_v are [n_embd × n_head_kv·d], which is why they are smaller; the output matrix W_o is [n_head·d × n_embd]; and each of the three feed-forward matrices is [n_embd × n_ff].

Pico 64 + 32 + 32 + 64 attention, 3 × 96 feed-forward, 2 × 80 vocabulary, 24 norm gains = 664

Llama-3-8B 16.8 M + 4.2 M + 4.2 M + 16.8 M = 41.9 M attention, 3 × 58.7 M = 176.2 M feed-forward, 218 M per block, × 32 = 6.98 B, plus 2 × 525 M vocabulary = 8.03 B

Clip 5. Each bar is scaled to its own total. Llama-3-8B's norm gains (266 k) are too thin to draw at that scale.

At both sizes the feed-forward matrices hold the largest share: 43 % of Pico and 70 % of Llama-3-8B. Attention gets the attention; the feed-forward part gets the weights.

The same loop in llama.cpp

In llama.cpp the loop is a few lines. This is the core of its simplest example, examples/simple, with error messages and printing removed. One call to llama_process runs the embedding, every block and the output head; the sampler reads the logits of the last token (index -1); the next batch is that single token. batch_set_tokens is the example's own helper, not part of the library: it empties the batch, adds the tokens with their positions and asks for the scores of the last one. The command-line tool, the server and every other example are wrappers around this loop.

examples/simple/simple.cpp · abridged
// tokenize the prompt
llama_tokenize(vocab, prompt.c_str(), prompt.size(),
               prompt_tokens.data(), prompt_tokens.size(), true, true);

// prepare a batch for the prompt
llama_batch_ext * batch = llama_batch_ext_init(ctx);
int n_tokens = n_prompt; // number of tokens in the current batch
batch_set_tokens(batch, prompt_tokens.data(), n_prompt, 0);

for (int n_pos = 0; n_pos + n_tokens < n_prompt + n_predict; ) {
    // evaluate the current batch with the transformer model
    if (llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch)) {
        return 1;
    }
    n_pos += n_tokens;

    // sample the next token
    new_token_id = llama_sampler_sample(smpl, ctx, -1);
    if (llama_vocab_is_eog(vocab, new_token_id)) { break; }

    // prepare the next batch with the sampled token
    batch_set_tokens(batch, &new_token_id, 1, n_pos);
    n_tokens = 1;
}

The clip lights that code a few lines at a time against the five stages of the loop, with the values the variables would hold for Pico's the cat sat.

Clip 6a. The Pico values annotate the code; llama.cpp did not run Pico, for which no model file exists.

Run on a real model, the example prints the prompt and the continuation, then its own timing report. The report counts the two kinds of call separately: one prefill of 4 tokens (a start token plus the three words) and 7 single-token decode runs.

Clip 6b. A real terminal session: the same example, built from the previous version of this code, running Gemma-3-270m (Q8) on the CPU. Timings vary from run to run.
conceptwhere it lives
the model: weights and hyperparameters struct llama_model (src/llama-model.h:812) with hparams (src/llama-hparams.h:60) and layers[il] (struct llama_layer, src/llama-model.h:282); loaded from a GGUF file whose keys are prefixed by the architecture name, e.g. llama.embedding_length (the key names are listed in src/llama-arch.cpp:193-538)
the call llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch) (include/llama.h:1101-1104, :308-311); the batch is a llama_batch_ext, which the caller cannot look inside and fills through llama_batch_ext_add_token or llama_batch_ext_add_embd, llama_batch_ext_set_pos and llama_batch_ext_set_output_logits (include/llama.h:1014-1096, src/llama-batch.h:102-162): per entry a token id or an embedding, its position, its sequence ids and an output flag. LLAMA_PROCESS_TYPE_ENCODE for encoder inputs
the loop's state struct llama_context (src/llama-context.h:45): the KV cache or recurrent state, the compute graph, the output buffer
reading logits, choosing a token llama_get_logits_ith(ctx, i); llama_sampler_sample(smpl, ctx, i) (include/llama.h:1148, :1666, src/llama-sampler.cpp:896)
the family switch enum llm_arch (src/llama-arch.h:13-195); each architecture's graph in src/models/<arch>.cpp, e.g. src/models/llama.cpp:98-229
the two shapes hidden state cur: ggml ne = [n_embd, n_tokens]; logits res->t_logits: [n_vocab, n_outputs] (src/models/llama.cpp:105, :227)

Names and line numbers on this page are from llama.cpp master at 94f3af3d0 (22 Nov 2026). Older code spells the call llama_decode / llama_encode with llama_batch_get_one; those are now marked deprecated.

level 1

Text to ids to vectors: tokens and embeddings

How does a string become integers, and how does an integer become the 8-number vector the block will work on?

A model cannot compute on characters, and it cannot afford one row of its tables per word of every language. A tokeniser settles this by cutting text into pieces from a fixed list of tens of thousands of entries: frequent words stay whole, rare words are spelled out in fragments. Any text can be written that way, and the list stays a fixed size. An embedding table then turns each id into a learned vector. That vector, not the id, is what the blocks transform. Ids only come back at the very end, as positions in the logits.

Clip 1.1. Pieces and ids are real: LFM2-350M (65 536 entries) and Gemma-3-270m (262 144 entries), from llama.cpp's own tokeniser. A faint dot stands for a space.

Tokenisation by merging

The most common scheme, byte-pair encoding, does not look words up in a dictionary. It starts from single characters, which are always in the vocabulary, and applies a ranked list of merges learned from a large body of text. At each step it merges the highest-ranked adjacent pair that is present, and stops when no listed pair is left.

merge list, by rank

  1. l + o
  2. lo + w
  3. e + r

lower

start: single characters, always in the vocabulary

lower

rank 1: the highest-ranked adjacent pair present

lower

rank 2

lower

rank 3: no listed pair is left, so the ids are [id("low"), id("er")]

Byte-pair encoding of "lower". The tile formed at each step is highlighted.

Encoding applies merges; decoding is simply gluing the pieces back together. Because every single byte is in the vocabulary, no text is impossible to encode. Unusual text is only expensive, because it falls apart into many small pieces.

Clip 1.2. The three-entry list is a teaching example. The second half uses LFM2-350M's real merge list; ranks are positions in that list.

Four tokeniser families cover nearly every model llama.cpp can load. They differ in how they choose the pieces, not in what comes out: a list of ids.

familyused byhow it cuts
SPMLLaMA-2 SentencePiece BPE; a ▁ marks each space; unknown characters fall back to bytes
BPEGPT-2, LLaMA-3 byte-level; a regular expression first splits the text into words and numbers, then merges run inside each
WPMBERT WordPiece: take the longest piece that matches the start of the word, then again from where it ended. BERT writes the continuation pieces with ##; llama.cpp stores them bare and marks the word start with ▁ instead
UGMT5, XLM-R Unigram: every piece has a score (a log-probability), and the most probable way to cut the whole text is found in one pass by the Viterbi algorithm

Special tokens are ids that never come out of merging. A start token (BOS, <s> in many models) is put in front of the text, an end token (EOS, </s>) stops generation, and chat formats add their own markers. The recorded run above shows one: the three-word prompt was printed as <bos>the cat sat and counted as 4 tokens.

Clip 1.3. Real cuts and ids from the vocabulary files that ship with llama.cpp. BERT's pieces are shown as llama.cpp stores them; the Unigram model is nomic-bert-moe.

Pico's vocabulary

Pico keeps this simple so the arithmetic stays readable: its vocabulary is ten whole words, and a token's id is its position in the list.

0 <s>
1 the
2 cat
3 sat
5 mat
6 dog
7 ran
8 .
9 </s>
textthecatsat id123 position012
The prompt uses ids 1, 2 and 3. Id 4, in amber, is the token the model goes on to generate. An id says which word; a position says where it stands.

The embedding table: a lookup, drawn as a matrix

The table E has one row per token id, and each row holds n_embd numbers. Embedding a list of ids means picking out their rows. No arithmetic is involved. The picked rows, stood side by side, are the first hidden state. In mathematical notation the table is [n_vocab × n_embd]; the code stores it as ne = [n_embd, n_vocab], with the row as the fastest-varying dimension.

E · 4 of its 10 rows
d0d1d2d3d4d5d6d7
E[1] the 0.20.20.2−0.7−0.1−0.20.41.0
E[2] cat 0.90.1−0.1−0.5−0.9−0.9−0.1−0.4
E[4] on 0.01.00.3−0.60.80.60.50.8
hidden state · [8 × 3]
thecat
d0 0.20.9
d1 0.20.1
d2 0.2−0.1
d3 −0.7−0.5
d4 −0.1−0.9
d5 −0.2−0.9
d6 0.4−0.1
d7 1.0−0.4
Rows of E become columns of the hidden state. The row for "on" is not used until the second call.

The highlighted vector belongs to sat, the last token of the prompt. It is the one to follow through every later stage, because the logits of the last token decide what comes next. In llama.cpp this lookup is one operation, ggml_get_rows(tok_embd, inp_tokens): the table is stored as [8, 10], the ids are [1, 2, 3], and the result is [8, 3]. For Llama-3-8B the same operation picks rows of 4 096 numbers out of a table with 128 256 rows.

↑ clip 2 opens with exactly this: rows 1, 2 and 3 of E light up and stand up as the three columns of the stream.

Clip 1.4. The rows for the, cat, sat and on are Pico's own. The other six rows are illustrative and drawn grey: the source prints only four.

Where position goes

The lookup above says which word each token is, and nothing about where it stands. The sentence order has to enter somewhere, and models differ on where.

rotary

LLaMA, Mistral, Qwen, Gemma, DeepSeek and most others

The embedding carries no position at all. Position enters later, inside attention, by rotating the query and key vectors by an angle that depends on the token's place (level 3). Only ids are looked up here.

learned absolute

GPT-2, BERT

A second table, pos_embd with shape [n_ctx_train × n_embd], is looked up by position (ggml_get_rows(pos_embd, inp_pos), as in src/models/bert.cpp) and added with ggml_add to the token's vector. A model built this way cannot see a position beyond the end of that table.

scaling

Gemma multiplies the embedding by √n_embd, and some models normalise it (tok_norm). These are details of one architecture's graph file, not separate mechanisms.

tied output

When a model file has no separate output matrix (no output tensor), the same table E is reused at the end to turn hidden states back into logits (level 6). Pico keeps the two apart so the arithmetic stays explicit.

↑ clip 2, step 06, shows the rotary case on Pico: a dial above each column turns to that position's angle, and no shape changes.

Clip 1.5. The rotations are Pico's own numbers. The position table on the right is an illustration: Pico is rotary and has none.

In llama.cpp

In llama.cpp this level lives in two places. Your program calls llama_tokenize to turn text into ids, and llama_token_to_piece to turn ids back into text. Inside the model's graph, ggml_get_rows picks the embedding rows for those ids; it is the graph's first operation.

Clip 1.6a. Both code windows are abridged from llama.cpp. The values are LLaMA-3's tokeniser on the cat sat.

Run on LLaMA-3's vocabulary, the tokeniser gives three ids for the three words and a fourth when asked for special tokens: the start token, id 128000. The second command lists what the model file stores for its tokeniser: the family, 128 256 pieces, 280 147 merges, and the ids of the start and end tokens.

Clip 1.6b. A real terminal session. tokenize is a 48-line program written for this page around llama_tokenize; gguf_dump.py ships with llama.cpp.
conceptname in the codewhere
tokeniser family enum llama_vocab_type: LLAMA_VOCAB_TYPE_SPM, BPE, WPM, UGM, and the rarer RWKV, PLAMO2, PLAMO3 (plus NONE and a TEST dummy); GGUF key tokenizer.ggml.model include/llama.h:72-82, src/llama-arch.cpp:472
vocabulary and merges GGUF keys tokenizer.ggml.tokens, tokenizer.ggml.merges, tokenizer.ggml.bos_token_id, tokenizer.ggml.eos_token_id src/llama-arch.cpp:474-480
encoding text llama_tokenize(), which calls llama_vocab::impl::tokenize; the work is done per family by llm_tokenizer_spm_session, llm_tokenizer_bpe_session, llm_tokenizer_wpm_session, llm_tokenizer_ugm_session (the first two merge; WPM takes the longest match and UGM searches for the best split), next to llm_tokenizer_spm and its siblings, which hold each vocabulary's data include/llama.h:1305, src/llama-vocab.cpp:4824, :3810, :110, :617, :876, :1059
decoding ids llama_token_to_piece(), llama_detokenize(); special ids from llama_vocab_bos(), llama_vocab_eos() include/llama.h:1319, :1333, :1269-1270, src/llama-vocab.cpp:4835, :4845
the embedding table GGUF tensor token_embd.weight, loaded as model.tok_embd, ggml ne = [n_embd, n_vocab]; optional position_embd as model.pos_embd src/llama-arch.cpp:541, :654, src/llama-model.h:841, :843
the lookup build_inp_embd(model.tok_embd) creates inp_tokens (32-bit integers, I32, [n_tokens]) and calls ggml_get_rows; when the batch carries vectors instead of ids (llama_batch_ext_add_embd; multimodal input such as images) the tensor inp_embd is selected instead src/llama-graph.cpp:2738-2906 (ggml_get_rows :2782), ggml/include/ggml.h:1558; called at src/models/llama.cpp:108
positions build_inp_pos() creates inp_pos (I32, [n_tokens], times n_pos_per_embd for rotary positions with several axes) src/llama-graph.cpp:2926-2938, src/llama-hparams.h:542

level 2

The block: a residual stream with two readers

What does one layer do to the hidden state, and why is normalisation applied before each sub-layer instead of after?

Think of the hidden state as a residual stream: one vector per token that flows straight through the whole network. A block does not replace it. It reads it, computes a correction, and adds the correction back. Each block has two readers. Attention mixes information across tokens; the feed-forward network transforms each token on its own.

Because everything is added, information on the way forward and gradients on the way back during training both have an untouched path from the first block to the last. That is what lets models stack 32, 80 or 100 blocks. Pre-normalisation rescales each reader's input to a standard size, so the corrections stay comparable however large the stream has grown.

Clip 2.1. The dashed frame is one block; it folds into the small glyph used for the 32 blocks of Llama-3-8B. The squares carry no numbers here.

One token through the block

Here is the vector for sat going through Pico's single block. Every row has the same eight columns, so any addition can be checked by reading down a column.

x = E[3] −0.2000.8000.1000.100−0.500−1.000−0.300−0.700
RMSNorm · gain g_attnblk.0.attn_norm · mean square 0.316 · × 1.778 −0.3561.4230.1780.178−0.889−1.778−0.533−1.245
attentionreads all tokens · level 3 0.1700.1560.095−0.0700.8970.6070.876−0.700
⊕ x₁ = x + a −0.0300.9560.1950.0300.397−0.3930.576−1.400
RMSNorm · gain g_ffnblk.0.ffn_norm −0.0451.4340.2930.0460.595−0.5890.864−2.099
feed-forwardeach token alone · level 5 0.032−0.5810.453−0.215−0.2560.788−1.073−0.507
⊕ x₂ = x₁ + f 0.0020.3750.648−0.1850.1410.395−0.496−1.908

→ next block, or the final norm and output head (level 6)

Blue rows are the stream; indented rows are what a reader sees or returns. First column: −0.200 + 0.170 = −0.030. Second column: 0.956 + (−0.581) = 0.375.

The stream is never normalised in place. The normalised copy only feeds the reader, and what the reader returns is added to the raw stream. The shape stays [8 × 3] for the three prompt tokens; the figure follows the third column.

Clip 2.3. The figure above, in motion: a copy leaves the stream, RMSNorm stretches it, the reader hands back a correction, and the correction lands on the stream. The second norm's numbers (0.445, 1.500) are computed from the printed vectors.

RMSNorm, with the numbers

Normalising does not squeeze values between 0 and 1. It rescales the whole vector so that the mean of its squares is 1, and then multiplies each coordinate by a learned gain.

x̂ᵢ = xᵢ / √( (1/n) · Σⱼ xⱼ² + ε ) · gᵢ

square and sumthe eight squares of x add up to 2.53
mean2.53 / 8 = 0.316
1 / √1 / √0.316 = 1.778
scale, then gain0.8 × 1.778 = 1.423 · gain 1.0 in Pico
RMSNorm of the vector for sat, one step at a time.

The gain vector g is the learned part, one number per feature; Pico sets all of them to 1.0. The small constant ε (1e-5 or 1e-6) only prevents a division by zero on an all-zero vector. LayerNorm, used by GPT-2 and BERT (T5 uses RMSNorm), does two more things: it subtracts the mean first and adds a bias at the end, (x − μ)/σ · g + b. RMSNorm drops the centring because it costs an extra pass and turned out not to be needed.

RMSNorm of the three prompt tokens · Pico, attn_norm
tokenmean of squares× factorx̂
the (0) 0.228 2.097 0.4190.4190.419−1.468−0.210−0.4190.8392.097
cat (1) 0.359 1.670 1.5030.167−0.167−0.835−1.503−1.503−0.167−0.668
Clip 2.2. Each square's side is its bar's length, so its area is the squared value. The LayerNorm result is computed from Pico's numbers for comparison; Pico itself uses RMSNorm.
Clip 2.4. The chart is a measurement: Gemma-3-270m, last token of 'the cat sat', read from llama.cpp's own graph tensors. The readers' inputs are taken after the learned gain, so they are near 1 rather than exactly 1 (attention's input is 362 and 86 in the first two blocks). Gemma-3 also normalises each reader's output. One prompt, one token.

Variations on the block

Almost every model keeps the stream and the two readers. What varies is where the norms sit and how the corrections are added.

variantwhat changesexamples in llama.cpp
pre-norm
the default above
the norm is on the reader's input; the correction is added to the raw stream LLaMA, Mistral, Qwen, DeepSeek, GPT-2, T5 and most others
post-norm the norm comes after the addition, on the stream itself; the original transformer BERT
sandwich norm an extra norm on the reader's output, before the addition (attn_post_norm, ffn_post_norm) Gemma-2, Gemma-3, GLM-4
parallel block attention and feed-forward both read the same normalised input and both add to the stream; one norm per block Falcon, Command-R
scaled residual the correction is multiplied by a constant before the addition (f_residual_scale), or the embedding is scaled Granite; Gemma for the embedding
QK-norm a norm on the query and key vectors inside attention (level 3) Qwen3, Gemma-3, OLMo-2 with learned gains (attn_q_norm, attn_k_norm); Llama-4 without a gain (use_kq_norm; all but its 128-expert model)
Clip 2.5. Each variant starts from the default wiring and changes one piece, drawn in red with its name in llama.cpp. Falcon is the single-norm form when its optional second norm is absent, as in Falcon-7B.

In llama.cpp

conceptname in the codewhere
the block loop for (int il = 0; il < n_layer; ++il) with inpL as the stream and inpSA the saved copy; the two additions are plain ggml_add(ctx0, cur, inpSA) and ggml_add(ctx0, cur, ffn_inp) src/models/llama.cpp:126-212 (inpSA :129, the additions :166 and :204)
norm gains GGUF tensors blk.%d.attn_norm.weight, blk.%d.ffn_norm.weight, loaded as layer.attn_norm, layer.ffn_norm, ggml ne = [n_embd]; optional biases such as attn_norm_b src/llama-arch.cpp:548, :555, src/llama-model.h:284-285, :346-347
epsilon hparams.f_norm_rms_eps, GGUF %s.attention.layer_norm_rms_epsilon; LayerNorm's f_norm_eps, %s.attention.layer_norm_epsilon src/llama-hparams.h:146-147, src/llama-arch.cpp:309-310
the norm operation build_norm(cur, w, b, LLM_NORM_RMS, il) calls ggml_rms_norm(cur, eps), then ggml_mul by the gain and ggml_add of the bias if there is one; LLM_NORM uses ggml_norm; LLM_NORM_GROUP for grouped variants src/llama-graph.cpp:1943-1976; enum llm_norm_type in src/llama-graph.h:78-82; the two ops are declared at ggml/include/ggml.h:1227 and :1217
tensor names in a debug dump attn_norm-0, attn_out-0, ffn_inp-0, ffn_norm-0, ffn_out-0, l_out-0: the callback cb(cur, name, il) formats "%s-%d". ffn_out-0 is given twice, to the feed-forward output and again to the stream after the second addition src/llama-context.cpp:3217-3224; the names are given at src/models/llama.cpp:135, :160, :167, :175, :183, :205, :208
shape through the block cur stays ne = [n_embd, n_tokens]; the attention reader temporarily reshapes to heads; the feed-forward reader temporarily widens to [n_ff, n_tokens] levels 3 and 5
Clip 2.6a. The block loop of src/models/llama.cpp, abridged: wrapped calls are joined onto one line and omissions are marked. Each cb(cur, name, il) line is where a tensor gets its name in a debug dump.
Clip 2.6b. Recorded, not typed in. First the six norm tensors Gemma-3-270m stores for block 0, then that block's graph tensors in the order they are computed, with the mean of squares of the last token. Gemma-3 is the sandwich variant, so its names differ from the default loop above: attn_post_norm, sa_out and ffn_post_norm. The second command is a small measuring program written for this page.

level 3

Attention, dimension by dimension

How does a token read other tokens? Follow one head of Pico from the normalised input to the attention output, with every intermediate number.

Attention is a learned lookup by content. Each token sends out three things: a query (what am I looking for), a key (what I contain, for matching) and a value (what I hand over if matched). A token's output is the average of all values, weighted by how well its query matches each key. The weights are made to sum to one by a softmax, and the causal mask restricts them to earlier positions.

Several heads run this in parallel on small slices of the vector, so that different heads can learn different relations. Position has to be put in somewhere, because the lookup itself does not see order. Rotary embeddings do it by turning queries and keys by an angle proportional to their position.

Reading the drawings · a list of numbers as an arrow

The clips of this part draw queries and keys as arrows inside a circle. This section is not in the reference page; it explains that drawing before it is used. The drawing is the ordinary way to picture a list of two numbers, and Pico's heads are exactly 2 numbers wide (n_embd_head = 2). That is the only reason it is possible here. A real head is 64 or 128 numbers wide; what remains true there is in the second half.

Two numbers are one arrow

Take the first number as a distance to the right (to the left if it is negative) and the second as a distance up (down if negative). The arrow runs from the centre to the point you reach. Nothing is lost and nothing is added: the two numbers can be read back from the arrow as its two legs. The ring is only a frame, like the edge of a map. The tick marks at 1 and 2 are the scale, and every dial of a clip uses the same scale, so arrows can be compared from one dial to the next.

two numbers → one arrow k of cat [1.523, 0.550] → 12 1.523 across 0.550 up length 1.619 · direction 19.9° Pico's three keys, at one scale the [−0.524, −2.327] cat [1.523, 0.550] sat [0.119, −0.943]
Left: the two numbers of cat's key are the two legs of its arrow. Right: the three keys that clips 3.1 to 3.4 use, already turned for position. A negative number goes left or down.

The arrow shows two things at a glance that the two numbers hide. Its length, √(a² + b²), says how large the list is as a whole: for cat's key, √(1.523² + 0.550²) = 1.619. Its direction says what kind of list it is, whatever its size.

Two arrows: how much they agree is the score

Attention scores a query against a key with a dot product: multiply the numbers pair by pair and add, q·k = q₀k₀ + q₁k₁. Drawn as arrows, the same number is length of q × length of k × cos(angle between them). So two arrows that point the same way give a large positive score, two arrows at a right angle give zero, and two arrows that point opposite ways give a negative score. Another way to see it: drop the key straight onto the line of the query. The piece it covers there is its shadow, and the dot product is the query's length times that shadow.

1 k of cat q of sat angle between42.8° length of q1.038 shadow of k on q1.188 1.038 × 1.1881.234 pair by pair: 0.477·1.523 + 0.922·0.5501.234 ÷ √2 (step 3)score 0.873 q of sat against each key the · 165.3° score −1.695 cat · 42.8° score 0.873 sat · 145.5° score −0.575
Left: sat's query and cat's key. The pale bar is the shadow of the key on the query's line. Both routes give 1.234, the number in the check of step 3. Right: the same query against all three keys. The wider the angle, the lower the score.
q of sat = [0.477, 0.922], length 1.038, against each key · computed from the printed arrows
keylength of kangle to qcos1.038 × length × cospair by pairscore = ÷ √2
the2.385165.3°−0.967 −2.395−2.395−1.695
cat1.61942.8°0.734 1.2341.234
sat0.950145.5°−0.824 −0.813−0.813−0.575

The last column is the printed score of step 3. The two columns before it are the same number reached by the two routes; they differ from the printed score × √2 only in the third decimal, because the arrows are printed to three decimals.

Clip 3.0a. What the dials of the next clips are: a 2D vector (a list of 2 numbers) drawn as an arrow, its length and direction, and the agreement of two arrows, which is the score. The part where the key is turned by hand is not Pico's data. The end shows more dimensions: the third number of the 3D arrow is made up (grey); the 8-number vectors are the page's x̂ of cat and sat, their length and angle computed for the clip; the 64 dials of a real head are drawn empty.

More than two numbers

With three numbers the arrow leaves the page: right, up, and towards you. It is an arrow in space, and it still has one length and one direction. With four numbers or more there is nothing left to draw, but none of the arithmetic above used the fact that there were two.

list ofdrawinglengthdot productangle between two
2 numbers
a Pico head
an arrow in a plane√(a₀² + a₁²)a₀b₀ + a₁b₁always from cos = a·b / (length of a × length of b)
3 numbersan arrow in space√(a₀² + a₁² + a₂²)a₀b₀ + a₁b₁ + a₂b₂
d numbers
128 in a Llama-3-8B head
none√ of the sum of the d squaresthe sum of the d products

So a query of 128 numbers is still "an arrow": it has a length, and it makes an angle with every key. Level 2 already used this without the word. RMSNorm rescales a vector so that the mean of its squares is 1, which is the same as setting its length to √n_embd: the normalised x̂ of sat has length √8 = 2.828.

Three things carry over from the dials to a real head, and one does not.

  • One query and one key can always be drawn. Two arrows, however many numbers they have, lie in one flat sheet. Inside that sheet they are two ordinary arrows with their true lengths and their true angle, and the shadow picture gives their true dot product. What is lost is the single dial for everything: each pair of arrows has its own sheet, so three keys can no longer be compared in one drawing as they are for Pico.
  • The score is still agreement. q·k is large when the two point the same way and both are long, zero at a right angle, negative when they oppose.
  • A wide head is many dials side by side. Rotary position (step 2) cuts a head of d numbers into d/2 pairs. Each pair is a 2-number arrow in its own dial, turned at its own speed, and the head's dot product is the sum of the dot products of its pairs. Pico's head is the case of one dial; a head of 128 numbers is 64 of them, added up.
  • What does not carry over: how random arrows meet. In a plane two arrows picked at random can make any angle. In a wide space almost all pairs are close to a right angle, so a clearly positive score is rare and means something. The same count explains the division by √d in step 3: the raw dot product of two random lists grows like √d.
10 000 pairs of random lists (each number drawn from a bell curve of spread 1) · computed for this page
numbers per listwhereangle between, middle 90 % of pairstypical size of a·b√d
2a Pico head8.5° to 171.2°1.411.41
325.7° to 154.4°1.721.73
8Pico's n_embd54.8° to 125.4°2.812.83
128a Llama-3-8B head81.7° to 98.5°11.3411.31
4 096Llama-3-8B's n_embd88.5° to 91.5°64.0364.00
Clip 3.0b. Random arrows in more dimensions: the angle between two random lists crowds towards 90° as they get longer, because their products cancel; their dot product still grows like √d, which is why the score is divided by √d. The ranges and typical sizes are the ones in the table above (10 000 random pairs per width); the ticks are a smaller sample. The last weights, with scores 11.3 times larger, are a what-if.
Clip 3.1. The whole attention reader for sat, from x̂ to a, with the step in progress lit. Keys and queries are drawn as arrows because Pico's heads are 2 numbers wide; a real head is far wider (128 numbers in Llama-3-8B). The arrows shown are already turned for position (step 2 below). Head 1's query and scores are derived from the printed numbers and drawn muted.

Step 1 · Projections and heads

Three matrices turn one 8-vector into 4 queries, 2 keys and 2 values. The normalised input x̂, [n_embd × n_tokens] = [8 × 3], is multiplied by W_q [8 × n_head·d] = [8 × 8], W_k [8 × n_head_kv·d] = [8 × 4] and W_v [8 × 4]. The resulting rows are then read as heads: a query row of 8 is four heads of 2 numbers, and a key row of 4 is two key/value heads of 2.

W_q, columns for heads 0 and 1 (of 4) · rows are input features
h0·q0h0·q1h1·q0h1·q1
d0−0.50.40.3
d1−0.3−0.30.5
d20.5−0.10.3
d30.5−0.60.3
d40.2−0.1−0.5
d50.3−0.5−0.2
d60.30.40.2
d7−0.10.4−0.4
W_k and W_v, columns for kv-head 0 (of 2)
k0k1v0v1
d00.6−0.3−0.5−0.4
d1−0.60.10.00.0
d2−0.6−0.4−0.30.5
d30.00.6−0.10.0
d4−0.3−0.1−0.10.0
d50.10.40.4−0.2
d6−0.10.00.1−0.3
d7−0.1−0.5−0.60.2
Results before rotation · one row per token
tokenq · head 0q · head 1k · kv 0v · kv 0
the (0) [0.147, −0.985][2.285, −0.461][−0.524, −2.327][−1.509, 0.294]
cat (1) [1.352, −2.037][1.636, 1.519][1.286, −0.985][−0.685, −0.467]
sat (2) [−0.427, 1.903][−0.907, 0.285][0.178, 0.498]

check · q head 0, token 2, first coordinate = x̂₂ · W_q[:,0] = (−0.356)(0.1) + (1.423)(0.2) + (0.178)(−0.3) + (0.178)(−0.5) + (−0.889)(−0.4) + (−1.778)(0.1) + (−0.533)(0.5) + (−1.245)(−0.5) = 0.640

Grouped-query attention means several query heads share one key/value head. Pico has n_head 4, n_head_kv 2 and head size d 2, so the group size is n_gqa = 2: heads 0 and 1 use kv-head 0, heads 2 and 3 use kv-head 1.

q row · 8 numbers
head 0head 1 head 2head 3
k row · 4 numbers
kv 0kv 1
v row · 4 numbers
kv 0kv 1
Drawn to scale: every cell is 2 numbers wide. The kv-head for query head h is h / n_gqa = h · n_head_kv / n_head, in integer division.
how many key/value heads?ruleexamples
MHA
multi-head
n_head_kv = n_head: every head has its own K and VLLaMA-2 7B and 13B, GPT-2
GQA
grouped-query
1 < n_head_kv < n_head: a group of queries shares K and VLLaMA-3, Mistral, Qwen
MQA
multi-query
n_head_kv = 1: all queries share one K and VFalcon-7B, PaLM
MLA
latent
keys and values are stored as one small latent (kv_lora_rank plus the rotary dimensions) and re-expanded per head, or the query is absorbed into the latentDeepSeek-V2 and V3

The cache stores n_head_kv heads (level 4). The compute is unchanged, because every query head still does its own dot products, only against shared rows: hparams.n_gqa(il) = n_head / n_head_kv, and the kernels broadcast K over the group. In ggml the query after the split has ne = [n_embd_head, n_head, n_tokens] = [2, 4, 3], the key and the value [2, 2, 3]. For Llama-3-8B a query row of 4096 is 32 heads of 128, and a key row of 1024 is 8 kv-heads of 128: groups of 4.

Clip 3.2. Step 1 of the attention reader, opened up: x̂ times three matrices, the rows read in slices of 2, two query heads per key/value head. Grey cells and arrows are illustrative: the reference page prints only heads 0 and 1 of W_q and kv-head 0 of W_k and W_v. The arrows are not yet turned for position. Gemma-3-270m's 4 → 1 is read from its file; LLaMA-2 7B's 32 → 32 is its published configuration.

Step 2 · Rotary position

Each query and key is turned by an angle that grows with its position. RoPE treats a head's d numbers as d/2 two-dimensional pairs and rotates pair i of the token at position m by θᵢ·m, with θᵢ = base^(−2i/d). Low-index pairs turn fast (fine position), high-index pairs slowly (coarse position).

It works because a rotated query dotted with a rotated key depends only on the difference of their positions: R(m)q · R(n)k = q · R(n−m)k. Attention therefore learns relative offsets, and the vectors themselves keep their length. Pico's heads have d = 2: a single pair with θ₀ = 1, so the angle is simply the position, in radians.

Angles for Pico · base 10000, d 2, θ₀ = 1
posanglecossin
001.0000.000
110.5400.841
22−0.4160.909
33−0.9900.141
(a, b) → (a·cos − b·sin, a·sin + b·cos)
tokenq head 0, beforeafterk kv 0, beforeafter
the (0) [0.147, −0.985] [−0.524, −2.327]
cat (1) [1.352, −2.037] [1.286, −0.985]
sat (2) [0.640, −0.818] [−0.907, 0.285]

check · token 1: 1.352·0.540 − (−2.037)·0.841 = 0.730 + 1.713 = 2.444; 1.352·0.841 + (−2.037)·0.540 = 1.137 − 1.100 = 0.037

Values are not rotated; only the match is positional. Variations:

  • Which coordinates form a pair. NORMAL pairs neighbours, (0,1), (2,3) and so on; NEOX pairs coordinate i with i + d/2. It is the same mathematics on a reordered vector, but weights trained one way cannot be run the other.
  • Contexts longer than training use scaling: linear (divide the positions), YaRN (stretch the low frequencies, keep the high ones, damp attention by a factor), or a table with one factor per frequency (Llama-3's rope_freqs).
  • Partial RoPE. Some models rotate only the first n_rot of the d coordinates.
  • Several axes. M-RoPE gives image tokens two or three positions.
Clip 3.3. Each token's q and k arrows are turned by its position, 1 radian per position in Pico; v is left alone. Two tokens that keep their distance keep their angle and their score (0.873); the scores at distance 2 and 3 are computed from the printed arrows, not printed by the reference page. The 64 hands at the end are the pairs of a head of 128 numbers with base 10000, llama.cpp's default; real files often store another base.

Step 3 · Scores, mask, softmax

Every query is held against every key. For head h, the score of token i reading token j is sᵢⱼ = qᵢ·kⱼ / √d. The √d keeps the dot products of random unit-scale vectors near unit variance, so the softmax does not saturate; for Pico it is 1/√2 = 0.7071.

The causal mask sets sᵢⱼ = −∞ for j > i: a token never reads the future, which is what makes the same weights usable for generating one token at a time. The softmax over each row then turns scores into weights that sum to one.

head 0 · scores S = Q·Kᵀ / √2 · row reads column
i \ jthe (0)cat (1)sat (2)
the (0)1.567−0.2250.669
cat (1)−0.9682.6480.180
sat (2)
head 0 · P = softmax(S), row by row
i \ jthe (0)cat (1)sat (2)
the (0)1.00000
cat (1)0.0260.9740
sat (2)
head 0 · O = P·V · V rows are kv 0
tokenV rowO row
the (0)[−1.509, 0.294][−1.509, 0.294]
cat (1)[−0.685, −0.467][−0.706, −0.448]
sat (2)[0.178, 0.498]

check · s₂₁ = (0.477·1.523 + 0.922·0.550) × 0.7071 = 1.234 × 0.7071 = 0.873 · softmax: e^(−1.695−0.873) : 1 : e^(−0.575−0.873) = 0.077 : 1 : 0.235 → /1.312 → 0.058, 0.762, 0.179 · O₂ = 0.058·(−1.509) + 0.762·(−0.685) + 0.179·0.178 = −0.578

Struck-through scores are the ones the mask replaces by −∞. The first token can only read itself, so its output is exactly its own value row. Head 1 reads the same keys and values (kv-head 0) with its own queries and lands on a different pattern: for sat it puts 0.858 on the, 0.008 on cat and 0.134 on itself, and its output is [−1.277, 0.315]. Same rows, a different question.

Clip 3.4. Steps 2 to 4 for all three tokens, as one grid in which each row reads the columns: scores, the mask above the staircase, the softmax row by row, and the weights mixing the values. The heights e^score (0.184, 2.394, 0.563) and their sum 3.140 are computed for the clip; the reference page writes the same softmax as ratios to the largest.

Step 4 · Merge heads, project back

The four 2-vectors of a token are put side by side and multiplied by W_o.

Token 2 · heads concatenated → [n_head·d] = [8]
h0h0h1h1h2h2h3h3
−1.2770.315−0.1920.1580.1060.169
W_o [8 × 8] · rows are the concatenated head features, columns the output features
o0o1o2o3o4o5o6o7
00.2−0.6−0.1−0.10.0−0.40.1
1−0.3−0.20.5−0.50.3−0.40.1
20.00.3−0.1−0.5−0.5−0.50.4
30.60.2−0.60.20.30.30.0
4−0.10.4−0.30.00.00.50.4
50.4−0.2−0.30.0−0.3−0.10.2
60.10.4−0.5−0.20.6−0.4−0.1
7−0.50.50.60.2−0.4−0.2−0.3
Attention output for token 2 · the correction a that level 2 adds to the stream
0.1560.095−0.0700.8970.6070.876−0.700

check · o0 = (−0.578)(0.4) + (−0.250)(−0.5) + (−1.277)(−0.1) + (0.315)(0.2) + (−0.192)(−0.2) + (0.158)(0.5) + (0.106)(0.5) + (0.169)(−0.5) = 0.170

W_o is where heads talk to each other: each output feature is a mix of all heads. In ggml the concatenation is a permute followed by ggml_cont_2d back to [n_embd, n_tokens], then a matrix multiply with wo.

Clip 3.5. Each head ends with a pair of numbers for sat; W_o gives every head two rows. A head's pair times its rows is its part of the output, 8 numbers wide, and the four parts add up to a, which lands on the stream as in clip 2.3. The weights of heads 2 and 3 in the opening panels are illustrative (grey): the reference page does not print them. Each head's part is computed for the clip from the printed pairs and W_o.

The masks, and the knobs on the scores

The mask is data, not code. The same attention arithmetic runs under every mask: llama.cpp builds a mask tensor for each batch on the CPU and adds it to the scores inside the softmax. A cell holds 0 where reading is allowed and −∞ where it is forbidden. With ALiBi an allowed cell holds the distance −|i−j| instead of 0, and the softmax multiplies it by the head's slope m: that is how the bias −m·|i−j| of the table below reaches the scores.

causal

j ≤ i
decoders

sliding window

i − j < n_swa, here 3
Gemma-2, Gemma-3

chunked

same chunk of n_swa, here 3
Llama-4

bidirectional

everything
encoders, embeddings

Rows are the reading token i, columns the token j being read, six tokens. Filled: 0, allowed. Hatched: −∞, forbidden.

A window of n_swa bounds how far back a layer can read, which also bounds its cache (level 4). In llama.cpp's source, Gemma-2 windows every second layer (n_swa = 4096), Gemma-3 windows 5 layers out of every 6 and Llama-4 chunks 3 out of every 4 (with n_swa = 8192); the layers in between read everything. The source page also names Mistral for the sliding window; llama.cpp's Mistral graphs set none. There is a third rule, a symmetric window that looks both ways (LLAMA_SWA_TYPE_SYMMETRIC). The mask is [n_kv, n_tokens], stored as 16-bit floats when flash attention is on.

knobwhat it does to the scoresexamples
scales = q·k / √d, or a per-model f_attention_scale (GGUF %s.attention.scale)the default; a per-model value in Granite, Gemma-3 and others
soft-caps = c·tanh(s/c) keeps scores bounded (f_attn_logit_softcapping, c = 50)Gemma-2
ALiBino RoPE; a slope m per head adds −m·|i−j| to the scores (f_max_alibi_bias)BLOOM, MPT
QK-norman RMSNorm on q and k before the dot product (use_kq_norm, or attn_q_norm and attn_k_norm); level 2Llama-4, Qwen3, Gemma-3
sinksone learned extra logit per head joins the softmax and absorbs weight, so that no real token has to (attn_sinks)GPT-OSS
temperature tuning (temperature scaling)the query is multiplied by log(⌊(pos + offset) / n⌋ + 1) · scale + 1, a factor that grows with position, so far tokens are not diluted. The source page writes it log(1 + pos/n)Llama-4
interleaved windows (iSWA)windowed layers alternate with full onesGemma-3: 5 of 6 windowed
Clip 3.6a. The mask is a grid of 0 and −∞ added to the scores; on six tokens it takes five shapes (causal, sliding window, chunked, symmetric, bidirectional), and a model may use different ones in different layers. The rules and the layer patterns are read from llama.cpp's source; Gemma-3-270m's 18 layers and window of 512 from its file. The 6 × 6 grids are structure only: no scores are invented.
Clip 3.6b. Six of the seven knobs of the table above (interleaved windows are in clip 3.6a), each shown where it sits on the path from q and k to the weights, and by what it does to sat's row from clip 3.4. Every changed number is a what-if computed for the clip on Pico's row (Pico itself uses none of these knobs); the sink's value is made up. Rules and users were checked against llama.cpp's source: there, Llama-4 applies temperature tuning in its layers without RoPE.

Flash attention, checked by hand

For a long context the score matrix is [n_kv × n_tokens] per head and would not fit in fast memory. Flash attention never builds it. It walks the keys in blocks and keeps, for each query, a running maximum m, a running denominator l and an unnormalised output o. When a new block raises the maximum, the old sums are rescaled by e^(m_old − m_new). The result equals the full softmax exactly.

Pico's decode step (level 4) gives an example with four keys for head 0, processed in two blocks of two.

Online softmax · head 0 at decode · scores [−0.104, 0.033, −0.040, 0.042] · V rows of kv 0
blockscoresm_newrescale e^(m_old − m_new)p = e^(s − m_new)lo, unnormalised
0[−0.104, 0.033]0.033—[0.872, 1.000]1.872[−2.000, −0.212]
1[−0.040, 0.042]0.0420.991[0.921, 1.000]1.872·0.991 + 1.921 = 3.776[−2.283, 0.311]

check · block 0: o = 0.872·(−1.509, 0.294) + 1.000·(−0.685, −0.467) = (−2.001, −0.211) · the full softmax gives probabilities [0.229, 0.262, 0.244, 0.265] and the same output [−0.605, 0.082]

Two consequences matter for an implementation. Memory per head drops from quadratic to linear in the context. And the kernel needs K and V in their natural layout, not transposed, which is why llama.cpp stores V differently depending on whether flash attention is on.

Clip 3.7. The table above, in motion: the keys arrive two at a time, and only the largest score so far, a running sum and a running output are kept. When block 1 brings a larger score, the old sums shrink by 0.991, a change of under one percent that the numbers show better than the bars. The fourth key and value belong to the token on, from the decode step of level 4, which this page does not cover yet.

In llama.cpp

Line numbers are for llama.cpp master at commit 94f3af3d0 (22 Nov 2026) and were looked up for this page; the source page lists the same places at an older commit, where the numbers differ.

conceptname in the codewhere
projection weights GGUF blk.%d.attn_q.weight, attn_k, attn_v, attn_output, loaded as layer.wq, wk, wv, wo; a fused attn_qkv as wqkv; ggml wq: ne = [n_embd, n_head·d], wk: [n_embd, n_head_kv·d], wo: [n_head·d, n_embd] src/llama-arch.cpp:549-552, :649, src/llama-model.h:307-313
head counts, head size, group hparams.n_head(il), n_head_kv(il), n_embd_head_k(il), n_embd_head_v(il), n_gqa(il), n_embd_k_gqa(il) = n_head_kv·d; GGUF %s.attention.head_count, %s.attention.head_count_kv, %s.attention.key_length src/llama-hparams.h:92, :112-113, :491-522, src/llama-arch.cpp:303-307
the projection and the head split build_qkv(layer, cur, n_embd_head, n_head, n_head_kv, il): three build_lora_mm (a ggml_mul_mat) and ggml_reshape_3d to [d, n_head, n_tokens]; views into one tensor when the weights are fused src/llama-graph.cpp:1979, :1993, called from src/models/llama.cpp:140-141
RoPE build_rope(Qcur, inp_pos, il), which calls ggml_rope_ext(ctx, cur, pos, factors, n_rot, type, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow), or ggml_rope_multi for several axes; modes GGML_ROPE_TYPE_NORMAL, NEOX, MROPE, VISION, IMROPE; hparams.rope_type, n_rot(il), rope_freq_base_train, yarn_ext_factor; GGUF %s.rope.freq_base, %s.rope.dimension_count, %s.rope.scaling.type; the per-frequency table rope_freqs.weight src/llama-graph.cpp:1778-1799, called from src/models/llama.cpp:143-144; ggml/include/ggml.h:77-81, :1700, :1745, src/llama-hparams.h:169, :178, :440, :506, src/llama-arch.cpp:392-400, :546
scores and softmax, without flash attention build_attn_mha: ggml_permute(q, 0, 2, 1, 3) (the same for k and v), then kq = ggml_mul_mat(k, q) giving [n_kv, n_tokens, n_head], then ggml_soft_max_ext(kq, kq_mask, kq_scale, f_max_alibi_bias), then kqv = ggml_mul_mat(v, kq), a second ggml_permute and ggml_cont_2d back to [n_embd, n_tokens] src/llama-graph.cpp:3106 (permute :3128-3130, ggml_mul_mat :3185, softmax :3217, kqv :3227, merge :3236-3239)
flash attention ggml_flash_attn_ext(q, k, v, mask, scale, max_bias, logit_softcap), called with kq_mask, kq_scale, hparams.f_max_alibi_bias and f_attn_logit_softcapping (or 0 when attn_soft_cap is off); sinks through ggml_flash_attn_ext_add_sinks; switched by llama_context_params.flash_attn_type (-fa on the command line) src/llama-graph.cpp:3156-3161, ggml/include/ggml.h:2254-2262, :2291, include/llama.h:193, :392
the mask input tensor kq_mask, [n_kv, n_tokens], F16 with flash attention and F32 without, filled on the host from positions and sequence ids; the window rule is is_masked_swa(n_swa, swa_type, p0, p1); hparams.n_swa, swa_type; GGUF %s.attention.sliding_window src/llama-graph.cpp:644-648, :1150, src/llama-kv-cache.cpp:1701-1876, src/llama-hparams.h:192-194, :563-597, src/llama-arch.cpp:321
score knobs kq_scale (1/√d or f_attention_scale); f_attn_logit_softcapping with attn_soft_cap; f_max_alibi_bias; use_kq_norm, which applies ggml_rms_norm to Q and K; attn_q_norm and attn_k_norm weights; layer.attn_sinks (blk.%d.attn_sinks) src/models/llama.cpp:122, :150-156, src/llama-hparams.h:153, :270, :276, :286-287, src/llama-arch.cpp:265, :305, :328, :567-568, :879
output projection build_attn(inp, wo, wo_b, wo_s, Q, K, V, …, kq_scale, il) ends with build_lora_mm(wo, cur), a ggml_mul_mat src/llama-graph.cpp:3275-3336 (:3324)
MLA (DeepSeek) wq_a, wq_b, wkv_a_mqa, wkv_b; n_lora_q, n_lora_kv, n_embd_head_k_mla(); GGUF %s.attention.q_lora_rank, %s.attention.kv_lora_rank src/llama-model.h:315-318, src/llama-hparams.h:102, :122-123, :547, src/models/deepseek2.cpp
Clip 3.8a. The attention lines of llama.cpp against the steps of clip 3.1: build_qkv, build_rope and build_attn in the block loop, then build_attn_mha with one group of lines per step, the flash attention branch, and the product with W_o. The code is from llama.cpp's source, abridged where marked. build_lora_mm is the matrix product with W_o; it also applies a LoRA adapter when one is loaded, and handles a few weight formats.
Clip 3.8b. Recorded, not typed in. First the four attention matrices Gemma-3-270m stores for block 0 (640 wide, 4 query heads of 256, 1 key and value head). Then block 0's tensors whose name contains kq, for a 4-token prompt: without flash attention the scores, the weights and the mix exist; with it only the merged output is left. In kq the first 256 is the number of cache cells the mask is padded to, not the head size, which happens to be 256 too. The first command takes a few seconds to answer. attn-shapes is a small measuring program written for this page.

Adapted from the reference page "Token to Logit", levels 0 to 3. Level 3 has its text and figures and all of its clips. Levels 4 to 10 are not on this page yet.