Sub topic 4
Embeddings: representing tokens as vectors
This chapter assumes you have read the tokenization chapter and know that text becomes a list of integer token IDs. It also assumes you can read basic NumPy and are comfortable with matrix multiplication and dot products.
Why token IDs are not enough
Tokenization produces integers such as [464, 3290, 318]. These integers are labels. ID 3290 is not "bigger" or "more similar" to ID 3291 in any meaningful way. The two tokens might be dog and an unrelated punctuation fragment. If you fed raw IDs into a neural network, arithmetic on them would mean nothing.
The network needs a representation where distance and direction carry information. An embedding gives each token ID a vector of real numbers. The model learns those numbers during training, so tokens that behave similarly in text end up with similar vectors.
The embedding matrix
An embedding layer is a single matrix E with one row per token in the vocabulary.
- Shape:
(vocab_size, d_model). vocab_sizeis the number of distinct tokens the tokenizer can produce.d_modelis the width of the model, the length of the vector that represents each token. Values from a few hundred to several thousand are common.
To embed a token, you take the row at its ID. This is a table lookup, not a computation.
import numpy as np
rng = np.random.default_rng(0)
vocab_size, d_model = 6, 4
E = rng.normal(size=(vocab_size, d_model))
token_ids = np.array([2, 5, 2, 0])
x = E[token_ids]
print(x.shape)
one_hot = np.eye(vocab_size)[token_ids]
print(np.allclose(x, one_hot @ E))The output is (4, 4) and then True. The sequence of four IDs became a (4, 4) matrix, one row per position. Note that ID 2 appears twice and produces the same row both times. At this stage the vector depends only on the token, not on its neighbors.
The second print shows an equivalent view. Multiplying a one-hot vector by E selects one row. Frameworks implement the lookup directly because multiplying by a mostly-zero matrix would waste memory and time. The matrix view is still useful, because it explains why gradients flow only into the rows that were used.
What the numbers mean
The values in E start random. Training adjusts them by gradient descent, using the same next-token loss as every other weight in the model. Nobody assigns meanings to the dimensions. Pressure from the loss shapes the vectors. If two tokens are often interchangeable in context, such as Monday and Tuesday, moving their vectors close together helps the model predict well after either one. Over billions of examples, geometric structure emerges.
Some practical consequences:
- Similarity is measured by direction. The usual measure is cosine similarity, the dot product of two vectors divided by the product of their lengths. It ranges from -1 to 1.
- Individual dimensions are not labeled. You cannot point to dimension 17 and say it means "animal". Meaning is spread across many dimensions and lies in directions, not axes.
- Relationships can appear as directions. Classic word-embedding research found offsets such as
king - man + womanlanding nearqueen. This works only roughly and only for some relations. Treat it as an illustration, not a guarantee.
import numpy as np
def cosine(a, b):
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
# Toy vectors chosen by hand to show the idea. Real vectors are learned.
cat = np.array([0.9, 0.8, 0.1])
dog = np.array([0.8, 0.9, 0.2])
tax = np.array([0.1, 0.0, 0.9])
print(round(cosine(cat, dog), 3))
print(round(cosine(cat, tax), 3))Here cat and dog score close to 1 and cat and tax score near 0.1. In a trained model the same pattern holds across thousands of dimensions.
Contextual meaning comes later
A single embedding row has one vector per token, so the word bank gets the same input vector in "river bank" and "bank account". The input embedding cannot tell them apart. What changes is the representation after each transformer layer. Self-attention mixes information from other positions into each row, so by the middle layers the vector at bank reflects its context.
It helps to separate two ideas:
| Term | Where it lives | Depends on context? |
|---|---|---|
| Token embedding | Row of `E`, at the model input | No |
| Hidden state | Output of any transformer layer | Yes |
When people say "embeddings" in the context of search or retrieval, they often mean a hidden state from a dedicated embedding model that summarizes a whole passage. That is related but different from the input embedding table covered here.
Size and cost
The embedding matrix is often a notable fraction of a model's parameters, especially for small models.
- A vocabulary of 50,000 tokens with
d_model = 768gives 50,000 × 768 = 38.4 million parameters. - A vocabulary of 100,000 tokens with
d_model = 4096gives 409.6 million parameters.
Vocabulary size is therefore a design trade-off. A larger vocabulary means fewer tokens per text, so shorter sequences and cheaper attention. It also means a bigger table, and rare tokens whose rows receive few updates and stay poorly trained.
Rare and untrained tokens
Rows for tokens that almost never appear in training get few gradient updates. Their vectors stay close to random initialization. Models can behave oddly when such tokens show up in prompts. This is one known source of strange outputs for unusual strings.
Where the embedding matrix is reused
The model's final step must turn a hidden vector back into a score for every vocabulary token. This needs a matrix of shape (d_model, vocab_size). Many models reuse E for this by transposing it. This is called weight tying.
import numpy as np
rng = np.random.default_rng(1)
vocab_size, d_model = 6, 4
E = rng.normal(size=(vocab_size, d_model))
h = rng.normal(size=(d_model,)) # stand-in for the final hidden state
logits = h @ E.T # one score per vocabulary token
print(logits.shape)
print(int(np.argmax(logits)))The output shape is (6,). Each logit is the dot product of the hidden state with one token's embedding, so the model scores a token higher when the hidden state points in the same direction as that token's vector. Tying saves vocab_size × d_model parameters and links the input and output views of each token. Other models keep separate input and output matrices, which gives more freedom at the cost of more parameters. Both designs are common.
Scaling and initialization
Embedding values need a sensible scale. In the original transformer, embeddings were multiplied by sqrt(d_model) before positional information was added, so the token signal was not swamped by it. Many modern models skip this step and rely on initialization and normalization instead. When reading a model's code, check which convention it uses. Mixing them up changes the relative size of token and position signals.
Common errors
- Index out of range. An ID greater than or equal to
vocab_sizefails in the lookup. This usually means the tokenizer and model do not match. - Wrong tokenizer for the model. Row 3290 means a particular token only for the tokenizer used in training. A different tokenizer with the same vocabulary size loads without error and produces nonsense.
- Treating embedding distance as meaning. Nearest neighbors in embedding space reflect training statistics, including biases in the data. Close vectors do not guarantee equivalent meaning.
- Resizing the vocabulary carelessly. Adding tokens requires adding rows to
E. The new rows start random and must be trained before they are useful.
Where this fits in the pipeline
The embedding step turns a list of seq_len integers into a (seq_len, d_model) matrix. Everything after it, including self-attention, positional information, and the transformer blocks, operates on that matrix. The next chapters show how attention lets these rows exchange information. Embeddings themselves carry no information about word order, which is why positional information must be added separately.
Exercise
A model has a vocabulary of 32,000 tokens and d_model = 2048. (a) How many parameters are in its embedding matrix? (b) If it uses weight tying, how many extra parameters does the output projection add? (c) A prompt of 10 token IDs is embedded. What is the shape of the result?
Show answer
(a) 32,000 × 2,048 = 65,536,000 parameters. (b) Zero. With weight tying, the output projection reuses the transposed embedding matrix. (c) (10, 2048), one row of length d_model per token.
Exercise
The word "bank" appears twice in one prompt, once meaning a riverside and once meaning a financial institution. Do the two positions have the same vector right after the embedding lookup? What about after several transformer layers? Why?
Show answer
Right after the lookup they are identical, because the lookup depends only on the token ID. After several layers they differ, because self-attention mixes in information from surrounding tokens, so each position's hidden state reflects its own context.