← Questions

Neural network forward and backward pass from scratch

0
AnthropicCodingLast asked Sep 2025

A coding interview question asked in Anthropic's coding round, last asked Sep 2025. It tests neural networks, backpropagation and ml coding.

Build a tiny neural network for binary classification by hand, with no autodiff library: one hidden layer, a cross-entropy loss, the forward pass, and the backward pass that gives the gradient of the loss for every parameter. Derive each gradient, use them for gradient descent, and prove they are right with a finite-difference check.

Interface

Unless you agree on a different interface with the interviewer, assume (NumPy allowed, no autograd):

  • init(n_in: int, n_hidden: int, seed: int) -> dict — parameters W1 (n_in x n_hidden), b1, W2 (n_hidden), b2.
  • forward(params, X) -> tuple[np.ndarray, dict] — X is (batch, n_in). Hidden layer h = tanh(X @ W1 + b1), logit z = h @ W2 + b2. Returns z and whatever the backward pass needs.
  • loss(z, y) -> float — mean binary cross-entropy on logits, computed stably.
  • backward(params, cache, y) -> dict — gradients with the same keys and shapes as params.
  • train(X, y, lr, steps) -> dict — plain gradient descent.
  • grad_check(params, X, y, eps=1e-6) -> float — the largest relative difference between your gradients and central differences.

Example

dL/dz  = (sigmoid(z) - y) / batch                 # per example
dW2    = h.T @ dz,           db2 = sum(dz)
dh     = outer(dz, W2)
da     = dh * (1 - h**2)                          # tanh' = 1 - tanh^2
dW1    = X.T @ da,           db1 = sum(da, axis=0)

grad_check(...)  -> tiny (around 1e-7 or less in float64) for correct gradients;
                    1e-2 or worse means a bug
loss(z=[0.0], y=[1])  -> 0.6931   # log 2: a logit of 0 is a coin flip

Constraints

  • Shapes must work for any batch size, including 1.
  • The loss must not overflow or return nan for logits like z = 1000 or z = -1000.

Clarifying questions

  • Which hidden activation: tanh, sigmoid or ReLU?
  • Mean or sum over the batch (it scales the gradients and the learning rate)?
  • Is NumPy allowed, or plain Python lists?
  • Is regularization (weight decay) wanted?

What a strong answer covers

  • The chain rule written out once, by hand, and the code following it line by line with shapes annotated.
  • The stable loss: log(1 + e^z) - y * z computed as logaddexp(0, z) - y * z, and why the combined sigmoid and cross-entropy gradient is just sigmoid(z) - y.
  • Central-difference gradient checking with a relative error, run on a few random parameters in float64.
  • Initialization: small random weights (not zeros, which keeps hidden units identical), scaled by fan-in.
  • How batch size changes the variance of the gradient and what that means for the learning rate.

Follow-ups

  • Switch to ReLU. What changes in the backward pass, and what is the gradient at 0?
  • Extend to multi-class with softmax; derive softmax - one_hot and keep it stable with log-sum-exp.
  • Add a second hidden layer and write the backward pass as a loop over layers.
  • Add momentum or Adam, and L2 regularization.

Where it's asked

  • Anthropic · Coding · Last asked Sep 202555 min · Live coding on a realistic, multi-part problem, a different one from the screen · No AI

What it tests

neural networks · backpropagation · ml coding

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding