Forward and backward through one neuron#
Reverse-mode autodiff in Value.backward#
Tasks in code#
| Task | Code |
|---|
| Central difference | numerical_derivative(f, x, h=1e-7) |
|---|
| Gradient of many inputs | numerical_gradient(f, point, h=1e-7) |
|---|
| Hessian of f(x, y) | hessian_2d(f, x, y, h=1e-5) |
|---|
| Check an autodiff gradient | gradient_check(build_expr, x_val, h=1e-7) |
|---|
| XOR network, 4 hidden | model = MLP([2, 4, 1]) |
|---|
| Run an optimizer | optimize(optimizer, func, grad_func, start) |
|---|
| Test convexity by sampling | check_convexity(f, dim) |
|---|
| Newton steps in 2D | newtons_method(grad_f, hessian_f, x0) |
|---|
Optimizers from scratch#
GradientDescent(lr=0.001)w = w - lr * gradient
SGDMomentum(lr=0.001, momentum=0.9)v = beta * v + gradient
Adam(lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8)two moments per weight
m_hat = [m / (1 - self.beta1 ** self.t) for m in self.m]bias correction
p - self.lr * mh / (vh ** 0.5 + self.epsilon)per-weight step size
adam_history = optimize(Adam(lr=0.01), rosenbrock, rosenbrock_gradient, start)
Autograd and optimizers in PyTorch#
x = torch.tensor(2.0, requires_grad=True)
y = x ** 2 + 3 * x + 1
y.backward()reverse mode through the recorded graph
print(x.grad)7.0 = 2*x + 3
sgd = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
adam = torch.optim.Adam(model.parameters(), lr=0.001)
adamw = torch.optim.AdamW(model.parameters(), lr=0.001, weight_decay=0.01)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(adam, T_max=100)
Tips#
- Use a learning rate schedule for runs longer than a few epochs.
- Cosine annealing and warmup suit transformers and large models.
- Newton's method solves a quadratic in one step.
- Gradient checks cost 2 forward passes per parameter. Do not run them in production training.
- A Hessian with mixed eigenvalue signs at a critical point marks a saddle.
- Flat minima generalize better than sharp minima.