// explainer · llms
Token to Logit
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.
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.
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 model | blocks | at the end | |
|---|---|---|---|
| Pico | [8 × 3] | 1 | logits [10] |
| Llama-3-8B | [4096 × n_tokens] | 32 | logits [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.
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
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.
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
- mask
- causal: a token reads itself and earlier ones
- examples
- LLAMA, MISTRAL3, QWEN3, GEMMA3, DEEPSEEK2, OPENAI_MOE (GPT-OSS) …
- calls
llama_processthenllama_sampler_sample- in the code
LLAMA_ATTENTION_TYPE_CAUSAL
encoder-decoder
translation, T5
output [n_embd × n_enc]
+ cross-attn to encoder
- second attention
- cross-attention: every decoder block reads the encoder's output, computed once
- examples
- T5, T5ENCODER
- calls
llama_processto encode the input once, then to decode from the start token- in the code
llama_model_has_encoder, tensorscross_attn_q/k/v,build_attn_inp_cross
encoder-only
embeddings, reranking
- 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).
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.
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.
| hyperparameter | field · GGUF entry | Pico | Llama-3-8B | meaning |
|---|---|---|---|---|
| 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
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.
// 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.
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.
| concept | where 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.
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
- l + o
- lo + w
- 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")]
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.
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.
| family | used by | how it cuts |
|---|---|---|
SPM | LLaMA-2 | SentencePiece BPE; a ▁ marks each space; unknown characters fall back to bytes |
BPE | GPT-2, LLaMA-3 | byte-level; a regular expression first splits the text into words and numbers, then merges run inside each |
WPM | BERT | 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 |
UGM | T5, 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.
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.
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.
| d0 | d1 | d2 | d3 | d4 | d5 | d6 | d7 | ||
|---|---|---|---|---|---|---|---|---|---|
| E[1] | the | 0.2 | 0.2 | 0.2 | −0.7 | −0.1 | −0.2 | 0.4 | 1.0 |
| E[2] | cat | 0.9 | 0.1 | −0.1 | −0.5 | −0.9 | −0.9 | −0.1 | −0.4 |
| E[3] | sat | −0.2 | 0.8 | 0.1 | 0.1 | −0.5 | −1.0 | −0.3 | −0.7 |
| E[4] | on | 0.0 | 1.0 | 0.3 | −0.6 | 0.8 | 0.6 | 0.5 | 0.8 |
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.
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.
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.
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.
| concept | name in the code | where |
|---|---|---|
| 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.
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.
→ next block, or the final norm and output head (level 6)
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.
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ᵢ
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.
| token | mean of squares | × factor | x̂ | |||||||
|---|---|---|---|---|---|---|---|---|---|---|
| the (0) | 0.228 | 2.097 | 0.419 | 0.419 | 0.419 | −1.468 | −0.210 | −0.419 | 0.839 | 2.097 |
| cat (1) | 0.359 | 1.670 | 1.503 | 0.167 | −0.167 | −0.835 | −1.503 | −1.503 | −0.167 | −0.668 |
| sat (2) | 0.316 | 1.778 | −0.356 | 1.423 | 0.178 | 0.178 | −0.889 | −1.778 | −0.533 | −1.245 |
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.
| variant | what changes | examples 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) |
In llama.cpp
| concept | name in the code | where |
|---|---|---|
| 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 |
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.
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.
| key | length of k | angle to q | cos | 1.038 × length × cos | pair by pair | score = ÷ √2 |
|---|---|---|---|---|---|---|
| the | 2.385 | 165.3° | −0.967 | −2.395 | −2.395 | −1.695 |
| cat | 1.619 | 42.8° | 0.734 | 1.234 | 1.234 | 0.873 |
| sat | 0.950 | 145.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.
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 of | drawing | length | dot product | angle 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 numbers | an 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 squares | the 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·kis 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
dnumbers intod/2pairs. 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
√din step 3: the raw dot product of two random lists grows like√d.
| numbers per list | where | angle between, middle 90 % of pairs | typical size of a·b | √d |
|---|---|---|---|---|
| 2 | a Pico head | 8.5° to 171.2° | 1.41 | 1.41 |
| 3 | 25.7° to 154.4° | 1.72 | 1.73 | |
| 8 | Pico's n_embd | 54.8° to 125.4° | 2.81 | 2.83 |
| 128 | a Llama-3-8B head | 81.7° to 98.5° | 11.34 | 11.31 |
| 4 096 | Llama-3-8B's n_embd | 88.5° to 91.5° | 64.03 | 64.00 |
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.
| h0·q0 | h0·q1 | h1·q0 | h1·q1 | |
|---|---|---|---|---|
| d0 | 0.1 | −0.5 | 0.4 | 0.3 |
| d1 | 0.2 | −0.3 | −0.3 | 0.5 |
| d2 | −0.3 | 0.5 | −0.1 | 0.3 |
| d3 | −0.5 | 0.5 | −0.6 | 0.3 |
| d4 | −0.4 | 0.2 | −0.1 | −0.5 |
| d5 | 0.1 | 0.3 | −0.5 | −0.2 |
| d6 | 0.5 | 0.3 | 0.4 | 0.2 |
| d7 | −0.5 | −0.1 | 0.4 | −0.4 |
| k0 | k1 | v0 | v1 | |
|---|---|---|---|---|
| d0 | 0.6 | −0.3 | −0.5 | −0.4 |
| d1 | −0.6 | 0.1 | 0.0 | 0.0 |
| d2 | −0.6 | −0.4 | −0.3 | 0.5 |
| d3 | 0.0 | 0.6 | −0.1 | 0.0 |
| d4 | −0.3 | −0.1 | −0.1 | 0.0 |
| d5 | 0.1 | 0.4 | 0.4 | −0.2 |
| d6 | −0.1 | 0.0 | 0.1 | −0.3 |
| d7 | −0.1 | −0.5 | −0.6 | 0.2 |
| token | q · head 0 | q · head 1 | k · kv 0 | v · 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.640, −0.818] | [−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.
| how many key/value heads? | rule | examples |
|---|---|---|
| MHA multi-head | n_head_kv = n_head: every head has its own K and V | LLaMA-2 7B and 13B, GPT-2 |
| GQA grouped-query | 1 < n_head_kv < n_head: a group of queries shares K and V | LLaMA-3, Mistral, Qwen |
| MQA multi-query | n_head_kv = 1: all queries share one K and V | Falcon-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 latent | DeepSeek-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.
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.
| pos | angle | cos | sin |
|---|---|---|---|
| 0 | 0 | 1.000 | 0.000 |
| 1 | 1 | 0.540 | 0.841 |
| 2 | 2 | −0.416 | 0.909 |
| 3 | 3 | −0.990 | 0.141 |
| token | q head 0, before | after | k kv 0, before | after |
|---|---|---|---|---|
| the (0) | [0.147, −0.985] | [0.147, −0.985] | [−0.524, −2.327] | [−0.524, −2.327] |
| cat (1) | [1.352, −2.037] | [2.445, 0.037] | [1.286, −0.985] | [1.523, 0.550] |
| sat (2) | [0.640, −0.818] | [0.477, 0.922] | [−0.907, 0.285] | [0.119, −0.943] |
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.
NORMALpairs neighbours, (0,1), (2,3) and so on;NEOXpairs coordinateiwithi + 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_rotof thedcoordinates. - Several axes. M-RoPE gives image tokens two or three positions.
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.
| i \ j | the (0) | cat (1) | sat (2) |
|---|---|---|---|
| the (0) | 1.567 | −0.225 | 0.669 |
| cat (1) | −0.968 | 2.648 | 0.180 |
| sat (2) | −1.695 | 0.873 | −0.575 |
| i \ j | the (0) | cat (1) | sat (2) |
|---|---|---|---|
| the (0) | 1.000 | 0 | 0 |
| cat (1) | 0.026 | 0.974 | 0 |
| sat (2) | 0.058 | 0.762 | 0.179 |
| token | V row | O 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] | [−0.578, −0.250] |
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.
Step 4 · Merge heads, project back
The four 2-vectors of a token are put side by side and multiplied by W_o.
| h0 | h0 | h1 | h1 | h2 | h2 | h3 | h3 |
|---|---|---|---|---|---|---|---|
| −0.578 | −0.250 | −1.277 | 0.315 | −0.192 | 0.158 | 0.106 | 0.169 |
| o0 | o1 | o2 | o3 | o4 | o5 | o6 | o7 | |
|---|---|---|---|---|---|---|---|---|
| 0 | 0.4 | 0.2 | −0.6 | −0.1 | −0.1 | 0.0 | −0.4 | 0.1 |
| 1 | −0.5 | −0.3 | −0.2 | 0.5 | −0.5 | 0.3 | −0.4 | 0.1 |
| 2 | −0.1 | 0.0 | 0.3 | −0.1 | −0.5 | −0.5 | −0.5 | 0.4 |
| 3 | 0.2 | 0.6 | 0.2 | −0.6 | 0.2 | 0.3 | 0.3 | 0.0 |
| 4 | −0.2 | −0.1 | 0.4 | −0.3 | 0.0 | 0.0 | 0.5 | 0.4 |
| 5 | 0.5 | 0.4 | −0.2 | −0.3 | 0.0 | −0.3 | −0.1 | 0.2 |
| 6 | 0.5 | 0.1 | 0.4 | −0.5 | −0.2 | 0.6 | −0.4 | −0.1 |
| 7 | −0.5 | −0.5 | 0.5 | 0.6 | 0.2 | −0.4 | −0.2 | −0.3 |
| 0.170 | 0.156 | 0.095 | −0.070 | 0.897 | 0.607 | 0.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.
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
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.
| knob | what it does to the scores | examples |
|---|---|---|
| scale | s = 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-cap | s = c·tanh(s/c) keeps scores bounded (f_attn_logit_softcapping, c = 50) | Gemma-2 |
| ALiBi | no RoPE; a slope m per head adds −m·|i−j| to the scores (f_max_alibi_bias) | BLOOM, MPT |
| QK-norm | an RMSNorm on q and k before the dot product (use_kq_norm, or attn_q_norm and attn_k_norm); level 2 | Llama-4, Qwen3, Gemma-3 |
| sinks | one 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 ones | Gemma-3: 5 of 6 windowed |
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.
| block | scores | m_new | rescale e^(m_old − m_new) | p = e^(s − m_new) | l | o, unnormalised |
|---|---|---|---|---|---|---|
| 0 | [−0.104, 0.033] | 0.033 | — | [0.872, 1.000] | 1.872 | [−2.000, −0.212] |
| 1 | [−0.040, 0.042] | 0.042 | 0.991 | [0.921, 1.000] | 1.872·0.991 + 1.921 = 3.776 | [−2.283, 0.311] |
| final | o / l | [−0.605, 0.082] | ||||
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.
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.
| concept | name in the code | where |
|---|---|---|
| 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 |
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.