Backpropagate through an embedding lookup

Why it matters Token embedding gradients in every LLM are this scatter-add, and sparse updates rely on it.

An embedding layer is a table lookup, so its gradient is a scatter-add: every row used gets the sum of the gradients flowing into it.

Write embedding_grad(ids, dout, vocab). ids is an int array of any shape, dout has shape ids.shape + (d,). Return the (vocab, d) gradient of the table.

Signaturedef embedding_grad(ids, dout, vocab)

Example

ids [0, 2, 0], dout [[1, 1], [2, 2], [3, 3]], vocab 3 gives [[4, 4], [0, 0], [2, 2]].

Understand the idea

An embedding layer just looks up rows of a table, one row per token id. In the backward pass each gradient vector flows back to the row it came from. If the same id appears several times, its row must receive the sum of all those gradients, like adding up every bill charged to the same room. Worked example: ids = [1, 3, 1], dout = [[1, 0], [0, 2], [5, 5]], vocab 4. Row 1 is used twice, so it gets [1, 0] + [5, 5] = [6, 5]. Row 3 gets [0, 2]. Rows 0 and 2 were never used, so they stay [0, 0]. Result: [[0, 0], [6, 5], [0, 0], [0, 2]]. Rule: start from a (vocab, d) zero array, flatten ids to one dimension and dout to (number of ids, d), then scatter-add each dout row into the row named by its id. In NumPy plain grad[ids] += dout keeps only one copy of a repeated id, so use an unbuffered accumulating add. ids can have any shape, such as (batch, time). Used in: training token embeddings in every language model.

Shapes and data flow

ids (B, T), dout (B, T, d)
flatten -> (B*T,), (B*T, d)
scatter-add -> dW (V, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleembedding_grad([0, 2, 0], [[1, 1], [2, 2], [3, 3]], 3)
  • Sample 2: batchembedding_grad(_ids, _dout, 6)
  • Test 3: unused rows zerofloat(embedding_grad([[1, 1]], [[[1.0], [2.0]]], 4)[[0, 2, 3]].sum())