Optimizers: SGD, Momentum, Adam
⛰️ What is an optimizer? An optimizer turns gradients into parameter updates. Plain gradient descent steps against the gradient; momentum keeps a running average of gradients so steps build up along consistent directions; Adam also keeps a running average of squared gradients and divides by its square root, giving every parameter its own step size.
Writing the update rules from memory, with the details that make them match a framework, is a common ML coding question for research engineers and a frequent follow-up after a hand-written backward pass.
The Prompt
The rules are short. The interviewer listens for the state each optimizer keeps, bias correction, where weight decay goes, and whether your numbers match a library.
"Implement SGD with momentum and Adam from scratch for a list of NumPy parameters. Then add weight decay the way AdamW does, and a learning-rate schedule."
Clarifying Questions
You: What is the interface? I'll take a list of parameter arrays at construction and a matching list of
gradients in step, and update the arrays in place.
Interviewer: Yes, like torch.optim.
You: Which momentum convention? PyTorch uses b = mu b + g and steps by lr * b; others use
(1 - mu) g in the average.
Interviewer: Match PyTorch, so we can compare.
You: Adam defaults: beta1 = 0.9, beta2 = 0.999, eps = 1e-8, with bias correction?
Interviewer: Yes.
You: For weight decay, do you want the L2 penalty added to the gradient, or decoupled decay?
Interviewer: Both, and explain the difference.
What You'll Build
SGD(params, lr, momentum, weight_decay)withstep(grads).Adam(params, lr, betas, eps, weight_decay, decoupled)withstep(grads);decoupled=Trueis AdamW.lr_at(step, peak, warmup, total) -> float: linear warmup, then cosine decay to zero.- A comparison harness that runs each optimizer next to its
torch.optimtwin on the same gradients.