Before you start: four words#
| Word | Plain meaning |
|---|---|
Vocabulary (V) | The fixed list of tokens a model knows — about 128,000–260,000 for current language models. Each token has an integer ID. |
| Embedding | A list of d learned numbers that represents one token (or one user, one product…). |
| Embedding table | A matrix of shape (V, d): row i is the embedding of token i. |
| One-hot vector | A vector of V zeros with a single 1 at the token’s ID. A wasteful way to write “token 1547”. |
1. What is it?#
An embedding is a learned vector that stands for a discrete thing. The embedding table holds one row per vocabulary item:
token ID 1547 → row 1547 of the table → [0.03, -0.11, ..., 0.42] (d numbers)That is all. Looking up an embedding is an array index, not a matrix multiplication — even though it gives exactly the same result as multiplying a one-hot vector by the table.
2. Why does it exist?#
Models do arithmetic, and “the token cat” is not a number. You need a representation that is (a) made of continuous numbers, (b) large enough to encode meaning, and (c) learnable.
A one-hot vector fails (a) and is absurdly wasteful: 128,000 numbers with a single 1 among them. An embedding compresses that into a few thousand dense numbers in which geometric relationships carry meaning: tokens that are used similarly end up close together.
3. Simple analogy#
Coordinates in a library of meaning. Instead of an arbitrary shelf number, each book gets coordinates: one axis roughly fiction↔non-fiction, another technical↔popular, and thousands more that resist naming. Books about similar things sit near each other — and the model learns these coordinates itself from data.
The famous consequence from classic word embeddings is king − man + woman ≈ queen: directions in
the space carry meaning. (Inside a modern transformer the vectors change from layer to layer with
context, but the intuition holds.)
4. Tiny example#
package main
import (
"fmt"
"math/rand"
)
func main() {
const V, d = 10, 4
table := make([][]float32, V) // the embedding "matrix": V rows of d numbers
for i := range table {
table[i] = make([]float32, d)
for j := range table[i] {
table[i][j] = float32(rand.NormFloat64())
}
}
tokenIDs := []int{3, 7, 1, 3} // a sequence
embeddings := make([][]float32, len(tokenIDs))
for i, id := range tokenIDs {
embeddings[i] = table[id] // a lookup: no arithmetic at all
}
fmt.Println(len(embeddings), "x", len(embeddings[0])) // 4 x 4
fmt.Println(embeddings[0], embeddings[3]) // identical: both are token 3
}That single indexing step is the entire embedding layer. The equivalent but wasteful way:
// The same result the slow way: a one-hot vector times the table.
oneHot := make([]float32, V)
oneHot[tokenIDs[0]] = 1
slow := make([]float32, d)
for v := 0; v < V; v++ { // V*d multiplications, all but d of them by zero
for j := 0; j < d; j++ {
slow[j] += oneHot[v] * table[v][j]
}
}
fmt.Println(slow) // same as embeddings[0]The matmul version costs 2 · 10 · 4 = 80 FLOPs for one token; the lookup costs zero FLOPs and 4
memory reads. For a real model (V = 128,256, d = 4,096) the matmul version would spend about a
billion FLOPs per token to do one array lookup. Always index.
5. Technical explanation#
Size#
Embedding table: V × d parameters
Llama 3.1 8B: 128,256 × 4,096 = 525 M parameters ≈ 1.05 GB at 16 bits
Llama 3.1 70B: 128,256 × 8,192 = 1.05 B parameters ≈ 2.1 GB at 16 bits
Gemma 3 1B: 262,144 × 1,152 = 302 M parameters ← about 30% of a 1B modelFor small models with large vocabularies, the embedding table is a large share of all parameters. That matters for quantization (embeddings are often kept at higher precision) and for on-device deployment (14.e).
Weight tying#
Some models reuse the input embedding table as the output layer (lm_head):
logits = hidden @ embedding_table.T # "tied"Tying saves V × d parameters. Small models usually tie (Llama 3.2 1B and 3B, Gemma); large ones
usually do not (Llama 3.1 8B and 70B have separate input and output matrices). Check
tie_word_embeddings in the model’s config.json — getting it wrong changes a memory estimate by
gigabytes.
Positional information#
The embedding table alone has no notion of order: “dog bites man” and “man bites dog” would give the same set of vectors. Position has to be added somehow:
| Scheme | How | Used by |
|---|---|---|
| Learned absolute | add a learned vector for each position | BERT, GPT-2 |
| Sinusoidal | add fixed sine/cosine patterns | the original transformer |
| RoPE (rotary) | rotate q and k by an angle that depends on position | Llama, Mistral, Qwen, DeepSeek, Gemma — nearly all current models |
| ALiBi | add a distance-based penalty to attention scores | BLOOM, MPT |
| None in some layers (“NoPE”) | no position signal; the causal mask still implies order | interleaved with RoPE layers in some long-context models, e.g. Llama 4 |
How RoPE works, in one worked example. RoPE treats each pair of numbers in q and k as a point
on a plane and rotates it by position × θ, with a different speed θ for each pair. Take one pair,
q = (1, 0), at position 2 with θ = 30° per position: it is rotated by 60° to (0.5, 0.87). A key at
position 1 is rotated by 30°. The dot product of the two depends only on the 30° difference —
that is, on how far apart the tokens are, not on where they are. That relative-position property is
why RoPE works so well (exercise D proves it).
RoPE has direct consequences for inference:
RoPE is applied to q and k only — NOT to the value vectors, NOT to the residual stream
q_rot = rotate(q, position)
k_rot = rotate(k, position)- The KV cache stores keys that are already rotated. Reuse a cached prefix at a different position and the keys are wrong. This is one reason prefix caching (12.m) only reuses exact prefixes from position 0.
- RoPE has a base frequency,
rope_theta(500,000 in Llama 3; 1,000,000 in Qwen3), which sets how slowly the slowest pairs rotate. Context-extension methods — NTK-aware scaling, YaRN, Llama 3.1’srope_scaling— change these frequencies so a model can read further than it was trained on (12.h, 14.i). - RoPE runs at every decode step for the new token, so it must be a fast, fused kernel.
- MLA models apply RoPE to a small separate part of each key so that the rest can be cached in compressed form (12.g).
The output side: the LM head#
hidden (B, S, d) @ W_out (d, V) → logits (B, S, V) one score per vocabulary tokenFor V = 128,256, d = 4,096, one token: 2 · 4,096 · 128,256 ≈ 1.05 GFLOPs. That is about 7% of an
8B model’s FLOPs per token, in one matrix.
The output is also big. At B = 32 and S = 1 in FP32 it is 16 MB per step; during a 2,048-token prefill for the same batch it would be about 34 GB. That is why engines compute logits only for the last position during prefill. Computing them for every position is a common performance bug in custom code.
6. Under the hood#
An embedding lookup is a gather: reads from scattered rows of a large table.
Table: ~1 GB in HBM
Lookup: read d × 2 bytes = 8 KB per token, from an unpredictable row- Adjacent tokens have unrelated IDs, so there is no locality to exploit.
- But 8 KB per token is tiny, so it rarely matters for language models.
- The exception is recommendation systems with terabyte-scale embedding tables, where the gather is the bottleneck and specialised systems exist.
For language models the input lookup is a rounding error. The output projection is not.
7. Performance implications#
- Input embedding: negligible. A few KB per token.
- Output projection: significant. Around 5–10% of decode FLOPs, and a large output tensor.
- Vocabulary size is a real design parameter. Doubling V doubles the LM-head cost and the embedding memory. Vocabularies grew from 32k (Llama 2) to 128k–262k in current models, because a larger vocabulary means fewer tokens per text (12.b).
- Logit precision: sampling in FP32 is more stable but doubles the logits tensor. Engines usually compute logits in the model’s precision and convert to FP32 for the softmax (12.o).
- Vocabulary parallelism: with tensor parallelism, the vocabulary is split across GPUs so each computes a slice of the logits, followed by a gather or a distributed argmax (14.c).
8. Production implications#
- Check
tie_word_embeddingswhen estimating memory. - Compute logits only where needed: the last position during prefill; every position only if the API asked for per-token log-probabilities of the prompt.
- Keep sampling on the GPU. Copying a
(B, V)logits tensor to the CPU every step costs milliseconds (9.b). - Embeddings are often excluded from aggressive quantization: the gather is cheap and the quality cost can be disproportionate.
- Log-probability APIs are expensive. Returning top-k log-probabilities per token means keeping and sorting full logits. Price and rate-limit them accordingly.
9. Common mistakes#
Implementing the embedding as a one-hot matmul. Astronomically wasteful.
Computing logits for every prefill position. Wastes FLOPs and can run out of memory.
Forgetting weight tying in memory estimates.
Applying RoPE to the values. It goes on q and k only.
Reusing cached KV at a different position. With RoPE this gives subtly wrong outputs unless the keys are re-rotated or recomputed.
Ignoring vocabulary size when comparing models. A “3B” model with a 256k vocabulary serves very differently from a 3B model with 32k.
10. Hands-on exercise#
A. Measure the tables. For three open models of different sizes, compute the embedding table’s
share of all parameters from their config.json. Which is most embedding-heavy?
B. Gather cost. On a GPU, time table[ids] for a (128256, 4096) 16-bit table with batches of
1, 32 and 2,048 random IDs. What bandwidth do you reach? Compare with reading the same number of
bytes sequentially.
C. LM-head cost. Time the final projection for B ∈ {1, 8, 64} and compare with one transformer layer. What fraction of a decode step is the LM head?
D. RoPE. Implement RoPE for one head. Show numerically that the dot product of a query at
position i and a key at position j depends only on i − j.
E. The prefill-logits trap. Compute logits for every prefill position and measure the memory. Then compute only the last one. Report both.
11. Interview questions#
- What is an embedding table, and how large is it for a typical LLM?
- Why is an embedding lookup a gather rather than a matmul?
- What is weight tying, which models use it, and how much memory does it save?
- Explain RoPE and two of its consequences for inference.
- Why do engines compute logits only for the last position during prefill?
- How does vocabulary size affect serving cost?
- What is vocabulary parallelism and why is it used?
12. Further reading#
- [ESTABLISHED] Su et al., “RoFormer: Enhanced Transformer with Rotary Position Embedding” (2021).
- [ESTABLISHED] Peng et al., “YaRN: Efficient Context Window Extension of Large Language Models” (2023).
- [ESTABLISHED] Press et al., “Train Short, Test Long: Attention with Linear Biases” (ALiBi, 2021).
- [FUNDAMENTAL] Mikolov et al., “Efficient Estimation of Word Representations in Vector Space” (word2vec) — for embedding intuition.
- [REFERENCE] Llama 3.1 8B
config.json— a realrope_thetaandrope_scalingblock.