The BPE tokenizer hands me integers. For the sentence I love AI I get [15, 824, 391]. Most explanations stop there and jump to transformer diagrams. I did the same for months and treated nn.Embedding as a black box. Then I built AL-1 in pure NumPy and had to implement the layer myself. It is a lookup table: row $i$ is the vector for token ID $i$. What needs explaining is why a lookup table is the right design, what the rows become after training, and why gradients update only the rows a batch actually used.
This post bridges “text as numbers” and “text the model can reason over”. If the model used the raw ID, token ID $824$ would be a bigger scalar than $391$, which would imply love > AI in some numeric sense. That has no meaning. I need each ID to become a vector I can do geometry on, where distance carries meaning and cat lands near dog but far from car. A scalar ID cannot do that. A learned row in a matrix can.
flowchart LR
TXT["'I love AI'"] --> TOK["BPE tokenizer"]
TOK --> IDS["IDs [15, 824, 391]"]
IDS --> EMB["Embedding lookup"]
EMB --> VEC["Vectors (3, d_model)"]
VEC --> TR["Transformer blocks"]
Why can’t the model use token IDs directly?
A token ID is a name, not a quantity. The tokenizer assigned love → 824 and AI → 391 by merge order during BPE training, not by meaning. If I feed raw integers into a matrix multiply, the network reads $824$ as “4.7× bigger than $175$” and starts fitting spurious magnitude relationships. The IDs carry no semantic structure: cat and kitten could be $82$ and $49{,}001$, as far apart as any two random numbers.
Instead, each token becomes a vector in $\mathbb{R}^{d}$, where $d$ is the model width. Distances should mean something, and co-occurring tokens should end up near each other after training. A scalar cannot do that, so I map every ID to its own learned vector and let gradient descent arrange them.
What is a token embedding?
An embedding is a learned vector attached to each token in the vocabulary. Stack all of them and you get the embedding matrix $W$:
Here $V$ is vocabulary size and $d$ is d_model. Row $i$ is the vector for token ID $i$. In GPT-2 small:
Parameter count:
That is almost 39 million parameters before attention, and the single largest weight in a small GPT. With weight tying it is reused as the output projection, the lm_head that maps hidden states back to vocabulary logits. It has the same shape $V \times d$ and ties “what a token means going in” to “how likely it is coming out”.
Take a toy vocabulary of three tokens with $d = 4$:
Row $0 \to$ dog. Row $1 \to$ cat. Row $2 \to$ car. Rows are tokens, columns are features.
How does the embedding lookup work?
Here is the entire layer from zyn/nn.py, give or take:
class Embedding:
def __init__(self, vocab_size, d_model, std=0.02):
w = np.random.randn(vocab_size, d_model) * std
self.weight = Tensor(w) # trainable
def forward(self, indices): # indices: (B, T) int array
return self.weight.gather(indices, dim=0) # (B, T, d_model)
gather is fancy indexing: weight[indices]. Given a tiny matrix:
And indices:
The output stacks rows $2$, then $0$, then $1$:
There is no multiplication and no activation. The input shape is $(B, T)$: a batch of $B$ sequences with $T$ tokens each. The output shape is $(B, T, d)$, because every integer becomes a $d$-dimensional vector, and the first transformer block consumes that tensor. For a real batch of shape $(32, 1024)$ with $d = 768$, the output is $(32, 1024, 768)$ floats.
I drew $W$ and the output for the indices above, $[2, 0, 1]$. Position 0 has ID 2, so output row 0 is a copy of row 2 of $W$.
Why multiply by 0.02 at initialization?
np.random.randn gives unit-variance Gaussians: values around $\pm 1$, occasionally $\pm 3$. Those are too large to start with. A row like $[1.5, -0.8, 2.1, \dots]$ fed into the residual stream inflates activations, and the first few gradient steps thrash. Scaling by $\text{std} = 0.02$ shrinks everything:
A fresh row looks like $[0.012, -0.017, 0.006, \dots]$: tiny, near the origin, with all tokens starting roughly equal. The value $0.02$ is the GPT-2 initializer. Training then nudges rows apart gradually instead of starting from large random values.
I scaled the example row $[1.5, -0.8, 2.1]$ at two settings of the std. At $0.02$ the entries are $0.030$, $-0.016$ and $0.042$.
Std $0.02$: the largest entry is $0.042$.
Std $1$: the row is unscaled.
How is lookup the same as a one-hot matrix multiply?
A row lookup is exactly a one-hot vector times the matrix. This equivalence is what made embeddings click for me. Represent token $2$ as the one-hot row:
Multiply by a $3 \times 2$ matrix:
First product entry:
Second product entry:
Result:
That is row $2$ of $W$. The zeros cancel every other row, and the single $1$ selects one. The embedding layer is a linear layer whose input is one-hot. For $V = 50257$ the multiply would involve a 50k-wide vector that is zero except for one slot. gather skips that work and reads the row directly, giving the same result without the floating-point multiplications.
I ran two tokens through the one-hot product. Token $2$ on the left reproduces $[0.9, 0.1]$.
Token $2$: $xW = [0.9, 0.1]$, which is row 2 of $W$.
Token $0$: $xW = [0.2, 0.5]$, which is row 0 of $W$.
How do embeddings learn meaning?
The rows start as random noise, and meaning arrives through gradients. Say the model reads I love and predicts the next token. The loss $L$ flows back into the embedding matrix as $\frac{\partial L}{\partial W}$, but only the rows that were used get a nonzero gradient. If the sequence touched token IDs $15$, $824$, and $391$, then rows $15$, $824$, and $391$ update. The other $50254$ rows are untouched this step. That sparsity keeps embedding updates cheap despite the parameter count.
Over millions of steps the geometry organizes itself, and tokens that appear in similar contexts get pulled together:
Nobody programmed dog ≈ cat. The next-token objective makes tokens with similar contexts converge as a side effect.
flowchart TB
subgraph space["Embedding space (schematic)"]
dog["dog"] --- cat["cat"]
cat --- lion["lion"]
car["car"] --- truck["truck"]
end
Why does d_model size matter?
With $d = 2$ each token has two numbers to encode meaning, part of speech, tense and sentiment. That is too little room, and tokens collide. At $d = 768$ each vector has 768 directions to spread information across. Wider embeddings hold more nuance, at the cost of more parameters and compute. GPT-2 small uses $768$; GPT-2 XL uses $1600$. Width is a capacity trade-off: doubling $d$ doubles this 39M-parameter layer.
Where does this fit in the AL-1 build?
Pipeline so far: autograd engine → gradient checker → BPE tokenizer → token embeddings → positional encoding → attention.
The tokenizer hands me IDs. The embedding layer turns them into the $(B, T, d)$ tensor that flows through every block. But this lookup is order-blind. The vector for cat is identical whether cat is the first token or the hundredth, because gather ignores position. A transformer with only token embeddings sees a bag of words. Positional encoding fixes that by adding a second matrix that injects “where” on top of “what”.
I implemented this by hand to remove the mystery. nn.Embedding is one line, and it hides the fact that the biggest weight in the model is a dictionary you are slowly teaching to mean something. After watching the rows drift from noise into structure, the rest of the transformer looked like a set of consequences of that table.
Full worked example: I love AI with IDs [15, 824, 391]
This walk-through covers the whole embedding layer for I love AI: lookup, one-hot equivalence, loss gradient and row update, with every arithmetic step on its own line. I use a toy width $d = 4$ so the numbers stay readable; GPT-2 small uses $d = 768$, but the mechanics are identical.
Step 1 — Token IDs from BPE
The BPE tokenizer maps:
Sequence:
Shape $(T) = (3)$ for one sentence. Batched with $B = 1$, shape is $(1, 3)$.
Step 2 — Rows in the embedding matrix
Pull the three relevant rows from $W \in \mathbb{R}^{50257 \times 4}$ (toy $d = 4$):
Step 3 — Embedding lookup via gather
gather stacks the rows in index order:
Shape $(T, d) = (3, 4)$. With batch dimension: $(1, 3, 4)$. Row $0$ of $X$ is the embedding for I. Row $1$ is love. Row $2$ is AI. This $(B, T, d)$ tensor is what the first transformer block receives.
Step 4 — One-hot equivalence for token 15 (I)
A one-hot vector for token ID $15$ in a vocabulary of size $V = 50257$ has a $1$ at index $15$ and $0$ everywhere else:
Multiply by $W$:
Only $j = 15$ contributes:
So:
Same result as gather. For love (ID $824$):
For AI (ID $391$):
Stacking all three one-hot rows and multiplying is the same as gather on $[15, 824, 391]$.
Step 5 — Loss gradient flowing back
Suppose the sentence passes through the transformer and the loss $L$ produces upstream gradients at each embedding position. After backprop through later layers, the gradient at position $0$ (I) is:
At position $1$ (love):
At position $2$ (AI):
Because $X[t] = W[\text{indices}[t]]$, the chain rule gives $\frac{\partial L}{\partial W[k]} = g_t$ when $\text{indices}[t] = k$, and $\mathbf{0}$ otherwise. Only three rows receive signal:
Every other row of $\frac{\partial L}{\partial W}$ is the zero vector. That is the sparsity I mentioned: one training step touches three rows out of $50257$.
Step 6 — Gradient matrix (schematic)
The full $\frac{\partial L}{\partial W}$ is mostly zeros. The three nonzero rows:
Step 7 — Row update with learning rate η = 0.1
SGD update: $W \leftarrow W - \eta \, \frac{\partial L}{\partial W}$. Only the used rows change.
Row 15 (I), component by component:
Updated row:
Row 824 (love), component by component:
Updated row:
Row 391 (AI), component by component:
Updated row:
Step 8 — What changed and what did not
After one SGD step on I love AI:
Rows $0$ through $14$, $16$ through $390$, $392$ through $823$, and $825$ through $50256$ are unchanged. Repeated across millions of sentences, these updates move the table from random noise into structure: tokens that share contexts get pulled together, one sparse row update at a time.
If the same token ID appears twice in one sequence, its row gradient is the sum of the per-position gradients, so repeated tokens accumulate more signal in a single step.
I ran one SGD step on the three rows at two learning rates. At $\eta = 0.1$ the new rows match Step 7.
$\eta = 0.1$: the new rows match Step 7.
$\eta = 1$: each entry moves ten times as far.
Embedding closeness is useful for semantic search, retrieval, clustering, and recommendations. But a static token row cannot distinguish two meanings of the same word — bank as a river edge vs a financial institution share one row until the transformer layers above create contextual representations. That is a different problem, solved downstream. At the embedding layer the job is to turn each integer from BPE into a vector the rest of the model can work with. Training then rearranges the rows that were used.
Support the writing
If this post helped, a coffee keeps the deep dives coming.
Buy me a coffee