Reduce a broadcast gradient back to the input's shape

MediumAutograd

When a bias of shape (d,) is added to activations of shape (n, d), NumPy broadcasts it. In the backward pass the incoming gradient has shape (n, d) but the bias gradient must have shape (d,): every broadcast copy contributes, so you sum. Every array autograd engine needs this helper.

Write unbroadcast(grad, shape) where grad is an array produced by broadcasting an input of the given shape (a tuple) to grad.shape under NumPy rules. Return an array of exactly that shape by summing over:
- extra leading axes that the input did not have, and
- axes where the input had size 1 but grad has size > 1 (keep them as size 1).
If shape is (), return a 0-d array holding the total sum.

Signaturedef unbroadcast(grad, shape)

Example

grad of shape (2, 3) filled with ones and shape (3,) gives [2.0, 2.0, 2.0].

Understand the idea

Broadcasting quietly copies a small array to match a bigger one, like one bias row being reused for every example in a batch. In the backward pass each copy received its own gradient, so the input's gradient is the sum over all the copies. Copies are made in two ways: new leading axes the input never had, and axes where the input had size 1. Worked example: grad = [[1, 2, 3], [4, 5, 6]] of shape (2, 3). For an input of shape (3,), sum over the leading axis: [5, 7, 9]. For an input of shape (2, 1), keep the axis count but sum over axis 1 with size kept as 1: [[6], [15]]. For shape (), add everything: 21. Rule: first sum away the extra leading axes until the number of dimensions matches, then for every axis where the target size is 1 and the grad size is larger, sum along it and keep the dimension. The output must have exactly the requested shape. Every array autograd engine calls a helper like this after add, mul and other broadcasting ops.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleunbroadcast(np.ones((2, 3)), (3,))
  • Sample 2: bias over batch and timeunbroadcast(_g, (4,))
  • Test 3: column vectorunbroadcast(_g, (3, 1))
  • Test 4: middle size-1 axisunbroadcast(_g, (2, 1, 4))
  • Test 5: scalarfloat(unbroadcast(_g, ()))
  • Test 6: no broadcastunbroadcast(_g, (2, 3, 4))
  • Test 7: shape checklist(unbroadcast(_g, (1, 1)).shape)