Compute the gradient of a tied input and output embedding

Why it matters GPT-2 and many small LLMs tie the embedding and output head to save V*d parameters, and every framework must sum both gradient paths.

With weight tying, one matrix E (V, d) is both the input embedding and the output layer, so its gradient has two parts.

Write tied_grad(E, ids, targets) for the smallest tied model: h = E[ids] (n, d), logits = h @ E.T (n, V), loss = mean over the n rows of cross-entropy with the given targets. Return (loss, dE), where dE (V, d) adds BOTH paths: through the output layer and through the embedding lookup. ids may repeat.

Signaturedef tied_grad(E, ids, targets)

Example

E = [[1, 0], [0, 1]], ids = [0], targets = [1] gives loss 1.3133 and dE = [[1.4621, -0.7311], [-0.7311, 0.0]].

Understand the idea

Weight tying uses the same matrix E twice: to turn input ids into vectors, and, transposed, to turn the final hidden vector into scores over the vocabulary. When one variable is used in two places, its gradient is the sum of the gradients from each use, like a shared bank account receiving two deposits.

Tiny case: E = [[1,0],[0,1]], input id 0, target 1. h = [1,0], logits = [1,0], softmax = [0.731, 0.269], loss = -ln 0.269 = 1.313. dlogits = [0.731, -0.731]. Output path: dlogits.T @ h puts [0.731, 0] in row 0 and [-0.731, 0] in row 1. Input path: dh = dlogits @ E = [0.731, -0.731], added to row 0. Row 0 becomes [1.462, -0.731].

Rule: dE = dz.T @ h + scatter_add(rows = ids, values = dz @ E), with dz = (p - onehot) / n.

Frameworks handle this automatically, but custom kernels and hand-written training loops must add both terms.

Shapes and data flow

E (V, d); h (n, d); logits (n, V); dz (n, V); dE = dz.T @ h (V, d) + scatter(dz @ E) into rows ids
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampletied_grad([[1.0, 0.0], [0.0, 1.0]], [0], [1])
  • Sample 2: repeated idstied_grad(E3, [1, 1, 2], [0, 2, 1])