Embeddings: Turning Token IDs into Vectors the Model Can Learn
Building a Transformer from Scratch, Part 4

The tokenizer turns text into token IDs. But token IDs are just integers, and a neural network can't learn anything from an index on its own. This post is about the first layer of the model, the one that turns those IDs into vectors it can actually learn.
From token IDs to vectors
Right now, after tokenization, we get token IDs like:
"I love AI" → Tokenizer → [45, 891, 72]
These token IDs are nothing but indexes. For example, the word "cat" having token ID 454 does not mean that this integer has some mathematical relationship with the meaning of the word, or that token 455 has a similar meaning. They are just positions in the fixed vocabulary.
What is an embedding?
Suppose our vocabulary only contains 10 tokens, and we decide that every token will be represented by a vector of size d_model = 4. Then we create a matrix:
embedding dimensions
↓ ↓ ↓ ↓
token 0 [ 0.2 0.7 -0.1 0.4 ]
token 1 [ -0.3 0.1 0.8 0.2 ]
token 2 [ 0.6 -0.5 0.3 0.9 ]
token 3 [ 0.1 0.4 0.2 -0.7 ]
...
token 9 [ -0.2 0.8 0.1 0.5 ]
This is the embedding matrix. So:
embedding matrix = vocabulary size × embedding dimension
For a real model we might have a vocabulary of 50,000 and an embedding dimension of 768. That's 50,000 × 768 = 38.4 million learnable parameters, just in the token embedding matrix.
How do tokens become vectors?
Suppose we have the tokens [2, 3, 9]. The embedding layer simply looks up those rows in the embedding matrix, E[2], E[3] and E[9]:
[2, 3, 9]
↓ embedding lookup
[[ 0.6, -0.5, 0.3, 0.9],
[ 0.1, 0.4, 0.2, -0.7],
[-0.2, 0.8, 0.1, 0.5]]
Now the sequence has gone from 3 token IDs to 3 vectors: shape (3) → (3, d_model).
Mathematically
Suppose we have a vocabulary of size 10 and we take token ID 3. We could represent it as a one-hot vector:
[0 0 0 1 0 0 0 0 0 0]
If our embedding matrix is E ∈ R^(10×4), then multiplying the one-hot vector x by E gives us exactly row 3:
$$xE = E_{3}$$
So for token ID 3 we get row 3 of the embedding matrix, which is equivalent to just looking up row 3. We don't actually build the one-hot vector, because creating a giant one-hot vector (32,768 entries in my model) just to pick out one row would be wasteful. Instead: embedding = E[token_id].
Where do these numbers come from?
Initially, the embedding matrix is filled with small random values. So "cat" might start as [0.012, -0.034, 0.008, 0.021, ...]. The model doesn't know that cat and kitten are related, or that dog and puppy are.
During training, the embedding values are updated using backpropagation:
Token → Embedding → Transformer → Prediction → Loss → Backpropagation → Embedding gets updated
The embedding vectors learn statistical representations that capture useful relationships between tokens, as a consequence of the training objective.
An embedding does not convert a token into its meaning
The embedding assigns each token a learnable, continuous vector representation. Any meaning or relationships in those vectors emerge through training, and later, the transformer contextualizes these representations.
So the word "bank" has one initial token embedding. In both "I deposited money in the bank" and "I sat beside the river bank", "bank" starts with exactly the same vector. It's the transformer's contextual processing (attention) that lets the representation of "bank" become context-dependent.
Making it learnable
First, a plain version with a random matrix, V = 10 and d = 4:
import torch
vocab_size = 10
embedding_dim = 4
E = torch.randn(vocab_size, embedding_dim)
print(E.shape) # torch.Size([10, 4])
token_ids = [2, 3, 4]
embeddings = E[token_ids]
print(embeddings.shape) # torch.Size([3, 4])
Every token gets a vector of size 4: E[3] gives row 3 of the embedding matrix, E[4] gives row 4, and so on. The important thing is the structure.
But right now E is just random values. How does training know E is something it should update? During training: E → forward pass → loss → gradients → update E → repeat. So E has to be a learnable parameter, and in PyTorch we mark it with nn.Parameter. Then PyTorch knows this tensor should receive gradients and be updated during training.
A toy training step
This is not how a transformer is trained, just a simple toy example to understand the mechanics:
import torch.nn as nn
E = nn.Parameter(torch.randn(vocab_size, embedding_dim))
output = E[2] # look up row 2
loss = output.sum() # a toy "loss"
loss.backward()
print(E.grad)
- We take token ID 2.
- We use it to get row 2 of the token embedding matrix. output = row 2, the initial vector for token 2.
- We compute a toy loss,
loss = output.sum(). - We propagate the loss backwards with
loss.backward().
For a parameter w, the gradient ∂L/∂w tells us how much the loss changes with respect to w. Gradient descent then does:
$$w_{new} = w_{old} - \eta , \frac{\partial L}{\partial w}$$
where η is the learning rate. If the gradient is positive, the parameter moves down; if it's negative, the parameter moves up.
Now the interesting part. The forward pass only accessed E[2], so gradients exist only for the part of E that contributed to the loss:
tensor([[0., 0., 0., 0.], # row 0
[0., 0., 0., 0.], # row 1
[1., 1., 1., 1.], # row 2 ← used
[0., 0., 0., 0.], # row 3
...])
It's 1 because loss = output.sum(), so L = e0 + e1 + e2 + e3, and the gradient of L with respect to each of them is 1. In real training it's the same idea: text comes in batches of token IDs, the IDs look up rows in the embedding matrix, and only the rows of tokens that appeared in the batch get updated.
If a token ID appears twice, its gradients accumulate, because each occurrence contributes. With E[[2, 4, 2]], row 2 would get [2, 2, 2, 2].
Updating the embedding
So now that we have gradients, how does the embedding actually change? Suppose one value is E[2][0] = 0.50, and after backpropagation E.grad[2][0] = 0.20. With η = 0.1:
$$E_{new} = 0.50 - (0.1)(0.20) = 0.48$$
The value moves from 0.50 to 0.48, down, because the gradient was positive. In code:
learning_rate = 0.1
with torch.no_grad():
E -= learning_rate * E.grad
We use torch.no_grad() because the update is not part of the network's forward computation. Otherwise PyTorch would try to track the update itself as another differentiable operation.
Important: after updating E, we need to clear the old gradients, because PyTorch accumulates gradients by default. loss.backward() gives us E.grad, and if we call loss.backward() again, PyTorch adds the new gradient to the existing one. So the loop is always:
optimizer.zero_grad()
loss.backward()
optimizer.step()
Letting PyTorch update the weights
What I did above, E -= learning_rate * E.grad, is basic gradient descent. In a real transformer we use an optimizer, and a common choice is AdamW. The mechanics first, with Adam:
optimizer = torch.optim.Adam([E], lr=0.001)
Here [E] tells the optimizer: you're responsible for updating this parameter. Later, inside a real nn.Module, we won't pass parameters by hand; PyTorch can discover the module's parameters itself.
Running the same toy step with Adam:
Gradient for embedding at index 2: tensor([1., 1., 1., 1.])
Before: tensor([ 0.1991, -0.1293, -1.5014, 2.5783])
After: tensor([ 0.1981, -0.1303, -1.5024, 2.5773])
Each value moved by exactly 0.001, which looks like plain gradient descent. It isn't, though. Adam keeps running averages of each parameter's gradients and of their squares, and divides one by the other, so on its very first step every parameter moves by about the learning rate times the sign of its gradient, whatever the gradient's size. Here the gradient happened to be exactly 1, so the two give the same answer. With a gradient of 0.2, plain gradient descent would move by 0.0002, but Adam's first step would still be 0.001. Over many steps the averages build up, and each parameter effectively gets its own step size:
Gradient
↓
AdamW
├── tracks gradient statistics
├── adapts the update size per parameter
├── uses the learning rate
└── applies weight decay (the "W")
↓
Parameter update
For the real training I used AdamW, with weight decay on the weight matrices (including the embedding) but not on biases or LayerNorm parameters.
The TokenEmbedding module
The embedding layer has to handle a single sequence, a batch, correct shapes, trainable parameters, and the device (CPU or GPU). My first version:
class TokenEmbedding(nn.Module):
def __init__(self, vocab_size, d_model):
super().__init__()
self.vocab_size = vocab_size
self.d_model = d_model
self.embedding = nn.Parameter(torch.randn(vocab_size, d_model))
def forward(self, token_ids):
return self.embedding[token_ids]
We use nn.Module to make it a proper PyTorch module. That lets PyTorch handle things like model.parameters() and model.to(device) automatically, and later torch.optim.AdamW(model.parameters(), ...) finds the embedding by itself.
With vocab_size = 10 and d_model = 6, five token IDs give an output of shape (5, 6). And a batch of 2 sequences of 4 tokens gives:
torch.Size([2, 4, 6]) → (batch_size, sequence_length, d_model)
That's the shape everything in the transformer works with from here on.
For the final implementation I switched to PyTorch's built-in layer, which does the same lookup:
self.embedding = nn.Embedding(vocab_size, d_model, padding_idx=pad_id)
(The padding_idx part comes up in the next section.)
Design choices I came back to
I marked these in my notes as "to visit later again", and I came back to every one of them when I implemented the full model. The same code is used for both my models, the 110M and the 336M.
Initialization
nn.Embedding uses PyTorch's default initialization, which draws every value from a normal distribution with standard deviation 1. So for, say, a vocabulary of 50,000 and d_model = 512, every token starts with a random vector, but a fairly large one. And if these vectors are too large, then:
Embedding → Q/K/V projections → attention → FFN → loss
can start with unnecessarily large activations and gradients. A common transformer practice is therefore to initialize weights with a relatively small variance. There are many strategies to choose from, and whichever one we pick should be followed by all the learnable layers.
I found out how much this matters the hard way. The first time I ran the full model, the initial loss was 56. A model that knows nothing should be guessing uniformly across the vocabulary, which gives a loss of about ln(vocabulary size): for the 1,000-token test vocabulary I was using, that's ln(999) ≈ 6.91. After switching to GPT-2-style initialization (normal with standard deviation 0.02 for the embedding and every weight matrix), the initial loss became 6.90. Exactly where it should be.
The final choice, which my test suite checks:
- Embedding and weight matrices: standard deviation 0.02.
- The two projections that write into the residual stream in every block (the attention output and the second FFN layer): 0.02 / √(2 × number of layers), so the residual stream doesn't grow as blocks are added.
- Biases: 0.
Weight tying
At the end, the model produces hidden states of shape [batch, seq_length, d_model], and we need to predict the next token, [batch, seq_length, vocab_size]. Normally we'd use an output head:
output_head = nn.Linear(d_model, vocab_size)
which has its own weight matrix, of the same shape as the embedding matrix. So instead of a separate matrix, we can reuse the embedding:
$$\text{logits} = H E^{T}$$
Suppose vocab_size = 50,000 and d_model = 512. That's 25.6 million parameters per matrix:
- Without tying: embedding 25.6M + output head 25.6M = 51.2M
- With tying: embedding 25.6M, and the output head is the same 25.6M
I tied the weights in both models. In the 110M model that's 25.2M parameters (32,768 × 768) shared between the input and output instead of 50.3M, and in the 336M model 33.6M (32,768 × 1,024) instead of 67.1M.
The PAD row
One thing my notes didn't have yet, which I only ran into when building the full model: what happens to the [PAD] token's row?
padding_idx=pad_idmakesnn.Embeddingstart the PAD row at zero and never give it a gradient from lookups. So padding positions feed a zero vector in and never train it.- But with weight tying, the same matrix is also the output layer, so the PAD row can still get gradients from the output side: every time the model gives
[PAD]some probability, the loss pushes on that row. - So I also mask the
[PAD]logit to −∞. The model can never predict[PAD], so it gets no gradient from either side, and AdamW's weight decay shrinks a zero row to zero. One of my tests runs 5 AdamW steps with weight decay and PAD inputs and targets, and checks the PAD row is still exactly zero.
This is also why the starting loss to aim for is really ln(vocabulary size − 1): one token, [PAD], can never be predicted.
With the tokens turned into vectors, the next thing the model needs is to know where each token is. That's positional encoding, in the next post.
Previous: Part 3: Byte-Level BPE
Next: Part 5: Positional Encoding (coming soon)
This post is part 4 of the series "Building a Transformer from Scratch". Code: GitHub · Results: technical report (PDF)
About the author
- I’m Yash, a final-year Computer Science student specializing in AI and ML. I like understanding how things work underneath, so I built a GPT-style transformer from scratch, tokenizer included, and trained it at 110M and 336M parameters. I write about what I learn along the way. Interested in NLP, LLMs, interpretability and healthcare AI.
Comments
Join the discussionNo comments yet. Be the first to comment.
Building a Transformer from Scratch
I built a GPT-style decoder-only transformer from scratch, tokenizer included, and trained it at two sizes, 110M and 336M parameters, on FineWeb-Edu. This series follows the whole journey one stage per post: tokenization, embeddings, RoPE, attention, LayerNorm, the feed-forward network, training and evaluation, mistakes included.




