22/32
Part 5 of 6 · Prove it with a gradient checkLearn and do

Check every entry of every parameter

Here is the check on every parameter of the practice network. numeric_grad is the part you write next:

_, grads = forward_backward(params, x, y)
for name, p in params.items():
    num = numeric_grad(lambda w: forward_backward({**params, name: w}, x, y)[0], p.copy())
    assert grads[name].shape == p.shape, name
    assert np.allclose(grads[name], num, rtol=1e-5, atol=1e-7), name

How it works:

  • numeric_grad(f, w) measures the slope of f along every entry of w, one entry at a time: a central difference for each.
  • np.ndindex(w.shape) gives every index of an array of any shape, so one loop visits every entry.
  • The lambda takes an array w, runs forward_backward with w in place of that one parameter, and keeps item [0], the loss.
  • np.allclose passes when every entry is within atol + rtol * abs(num) of the numerical value.
  • Callable[[np.ndarray], float], in the stub, is the type of a function that takes an array and returns a float.

Three things to watch:

  • Kinks. A nudge that carries pre across 0 crosses ReLU's corner, and the check can fail on correct code. PyTorch's gradcheck docs warn about the same thing at points with no derivative. In the test network the pre value nearest zero is 0.16 away, far beyond any 10−610^{-6} nudge.
  • Cost. Two loss evaluations per entry: 86 for the test network, two billion for a billion-parameter model. On a real model, check a random sample of entries.
  • Coverage. Check every parameter, and check its shape before its values.

In the editor, write numeric_grad(f, x, eps): the central difference of f along every entry of x, for any function and any array.