TExcelTAD

Embeddings

Neural networks need vectors, but words, tokens, users and products are discrete symbols. An embedding maps each symbol to a learned dense vector. Mathematically it is just a matrix whose rows are looked up by index, which is the same as multiplying a one-hot vector by a weight matrix. Training places related symbols near each other, so that geometry (dot products, cosine similarity) carries meaning.

A lookup is a matrix product

With a vocabulary of size VV and embedding dimension dd, the embedding matrix is E∈RV×dE \in \mathbb{R}^{V \times d}. The embedding of token ii is row ii:

ei=ET1i=E[i,:]\mathbf{e}_i = E^T\mathbf{1}_i = E[i, :]

where 1i\mathbf{1}_i is the one-hot vector. Multiplying by a one-hot vector would waste VV multiplications per token, so frameworks implement it as indexing. The gradient follows: only the rows that were looked up receive gradient (a sparse gradient), and a row used several times in a batch accumulates them.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
V, d = 6, 3
E = rng.normal(size=(V, d))
tokens = np.array([2, 5, 2])
onehot = np.eye(V)[tokens]
print("lookup equals one-hot product:", np.allclose(E[tokens], onehot @ E))
G = np.ones((3, d))                                 # upstream gradient for the 3 positions
dE = np.zeros_like(E); np.add.at(dE, tokens, G)     # scatter-add into the looked-up rows
print("gradient rows (token 2 used twice):\n", dE)
print("same as one-hot^T @ G:", np.allclose(dE, onehot.T @ G))
lookup equals one-hot product: True
gradient rows (token 2 used twice):
 [[0. 0. 0.]
 [0. 0. 0.]
 [2. 2. 2.]
 [0. 0. 0.]
 [0. 0. 0.]
 [1. 1. 1.]]
same as one-hot^T @ G: True

Similarity

The usual measure is the cosine similarity cos⁡(u,v)=uTv∥u∥ ∥v∥\cos(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u}^T\mathbf{v}}{\lVert\mathbf{u}\rVert\,\lVert\mathbf{v}\rVert} (Angles and Orthogonality), insensitive to vector length. Retrieval systems normalize embeddings to unit length so that the dot product is the cosine. Famous word-embedding results show linear structure: eking−eman+ewoman≈equeen\mathbf{e}_{\text{king}} - \mathbf{e}_{\text{man}} + \mathbf{e}_{\text{woman}} \approx \mathbf{e}_{\text{queen}}, because a consistent relation corresponds to a consistent direction.

python · try it yourself
import numpy as np

# Hand-built 4-D embeddings with dimensions (royal, male, female, food)
E = {"king": [0.9, 0.8, 0.1, 0.0], "queen": [0.9, 0.1, 0.8, 0.0], "man": [0.1, 0.9, 0.1, 0.1],
     "woman": [0.1, 0.1, 0.9, 0.1], "apple": [0.0, 0.1, 0.1, 0.9]}
E = {w: np.array(v) for w, v in E.items()}
cos = lambda a, b: a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
target = E["king"] - E["man"] + E["woman"]
for w in E:
    print(f"cos(king - man + woman, {w:5s}) = {cos(target, E[w]):+.3f}")
cos(king - man + woman, king ) = +0.585
cos(king - man + woman, queen) = +0.995
cos(king - man + woman, man  ) = +0.154
cos(king - man + woman, woman) = +0.772
cos(king - man + woman, apple) = +0.078

How embeddings are learned

  • As the first layer of a model: a language model's input embedding is trained by backpropagation with everything else.
  • By prediction (word2vec): make the dot product uwTvc\mathbf{u}_w^T\mathbf{v}_c large for words that co-occur, small for random pairs; the result implicitly factorizes a matrix of word-context statistics.
  • By contrast (sentence and image embeddings): a softmax cross-entropy over a batch where the matching pair is the correct "class" (InfoNCE):
ℓi=−log⁡exp⁡(uiTvi/τ)∑jexp⁡(uiTvj/τ)\ell_i = -\log\frac{\exp(\mathbf{u}_i^T\mathbf{v}_i/\tau)}{\sum_j\exp(\mathbf{u}_i^T\mathbf{v}_j/\tau)}

with temperature τ\tau. CLIP trains image and text encoders this way so that their embeddings share one space.

Embeddings in a transformer

A transformer's token embedding maps ids to dmodeld_{\text{model}}-vectors; the output layer maps final hidden states back to VV logits, often with the same matrix (weight tying: logits =Eh= E\mathbf{h}), which saves VdVd parameters. For a 50k vocabulary and d=768d = 768, the table alone has 38.6M parameters (Counting Parameters). Position information must be added separately (Positional Encodings).

In software

  • nn.Embedding(V, d) (with padding_idx, and sparse=True for sparse gradients); F.normalize for unit vectors.
  • Vector databases index normalized embeddings for fast approximate nearest-neighbor search.
  • See Generative AI and LLMs for embedding APIs and retrieval-augmented generation.

Exercises

Exercise 1: Table size

How many parameters does an embedding table for V=32,000V = 32{,}000 and d=4096d = 4096 have, and how much memory in bf16?

Answer

131,072,000 parameters, about 262 MB.

Solution

32,000⋅4096=1.31×10832{,}000 \cdot 4096 = 1.31 \times 10^8; times 2 bytes ≈2.62×108\approx 2.62 \times 10^8 bytes.

Exercise 2: Cosine similarity

Compute the cosine similarity of (1,2,2)(1, 2, 2) and (2,1,2)(2, 1, 2).

Answer

8/9≈0.8898/9 \approx 0.889.

Solution

Dot product 2+2+4=82 + 2 + 4 = 8; both norms are 3.

Exercise 3: InfoNCE (code)

For a batch of 3 pairs with unit-vector embeddings, compute the InfoNCE loss with τ=0.1\tau = 0.1 when every ui\mathbf{u}_i equals its vi\mathbf{v}_i and the pairs are orthogonal to each other.

Answer

About 9.1×10−59.1 \times 10^{-5}: nearly perfect.

Solution

Similarities are 1 on the diagonal and 0 elsewhere, so each loss is −log⁡e10e10+2-\log\frac{e^{10}}{e^{10} + 2}.

python · try it yourself
import numpy as np
U = V = np.eye(3)
S = U @ V.T / 0.1
loss = np.mean(np.log(np.exp(S).sum(1)) - np.diag(S))
print(f"{loss:.2e}")
9.08e-05

Test yourself

An embedding lookup E[i]E[i] is equivalent to…

  1. a softmax
  2. multiplying the one-hot vector of ii by EE
  3. a convolution
  4. sorting the vocabulary

Which rows of an embedding table receive gradient in a training step?

  1. All rows
  2. Only the rows of tokens that appeared in the batch
  3. Only the first row
  4. None

Weight tying in a language model means…

  1. all layers share weights
  2. the input embedding matrix is reused as the output projection
  3. embeddings are frozen
  4. the vocabulary is shared between languages