Show that an embedding lookup is a one-hot matrix multiply

Why it matters Knowing the lookup is a matmul explains why its gradient is a scatter-add of rows, and why tied input and output embeddings share one matrix.

An embedding layer looks like a special operation, but it is just a linear layer applied to one-hot vectors.

Write onehot_embed(ids, W). ids is a 1D list of ints of length n, W has shape (V, d). Raise ValueError if any id is outside [0, V). Build the float one-hot matrix O of shape (n, V) and return the tuple (O, O @ W). The second item must equal W[ids].

Signaturedef onehot_embed(ids, W)

Example

onehot_embed([2, 0], [[1, 2], [3, 4], [5, 6]]) returns O = [[0, 0, 1], [1, 0, 0]] and O @ W = [[5, 6], [1, 2]].

Understand the idea

An embedding lookup feels like a dictionary read, but mathematically it is a matrix multiply. Think of a one-hot vector as a pointer with a single 1: multiplying it by a matrix picks out one row.

Take W = [[1,2],[3,4],[5,6]] (3 tokens, width 2) and id 2. Its one-hot vector is [0,0,1]. Then [0,0,1] @ W = 0*[1,2] + 0*[3,4] + 1*[5,6] = [5,6], the same as W[2].

Rule: O[i, j] = 1 if j == ids[i] else 0, and O @ W == W[ids].

Real frameworks use the lookup because it skips the multiply by zeros (V can be 100,000+). The matmul view still matters: the gradient of W is O.T @ grad, which is a row scatter-add, and it shows why the same matrix can serve as both the input embedding and, transposed, the output layer.

Shapes and data flow

ids (n,) -> O (n, V) @ W (V, d) -> (n, d) == W[ids]
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleonehot_embed([2, 0], [[1, 2], [3, 4], [5, 6]])
  • Sample 2: repeat idsonehot_embed([1, 1, 0], [[0.5, -1.0, 2.0], [3.0, 0.0, 1.0]])
  • Test 3: matches lookupnp.allclose(onehot_embed([3, 0, 2], np.arange(12.0).reshape(4, 3))[1], np.arange(12.0).reshape(4, 3)[[3, 0,...
  • Test 4: bad id_raises(lambda: onehot_embed([4], [[1, 2], [3, 4]]))