InterviewPrepKit

Home / Coding / Machine Learning Coding / Neural Net Internals / ReLU Forward and Backward

ReLU Forward and Backward

easy 00:00
Solving tips
  • Forward is elementwise max(0, x); reach for np.maximum(0, x), not a Python loop or np.max (which reduces).
  • Backward is a gated pass-through: the local derivative is 1 where x > 0 and 0 elsewhere, so dX = dOut * (x > 0).
  • Gate on the layer INPUT x, not the output. At exactly x == 0 the derivative is undefined; the common convention is to use 0.

Implement the ReLU (Rectified Linear Unit) activation, the most common nonlinearity in deep networks, in both directions. The forward pass clamps negatives to zero; the backward pass routes the upstream gradient through only the units that were active. Interviewers use this to check that you can turn a piecewise function into vectorized NumPy and that you gate the gradient on the layer’s input rather than its output.

Definition

ReLU is applied elementwise:

relu(x) = max(0, x)

Its derivative is the indicator that the input was positive:

d relu / d x = 1 if x > 0 else 0     (undefined at x == 0; use 0 by convention)

By the chain rule, the gradient flowing back to the input is the upstream gradient multiplied by that local derivative:

dX = dOut * (x > 0)

Task

Complete two functions, fully vectorized with NO Python loops and NO deep-learning framework (NumPy only):

  • relu(x) returns max(0, x) applied elementwise, same shape as x.
  • relu_backward(dOut, x) returns the gradient with respect to x: it passes dOut through where x > 0 and returns 0 where x <= 0. Gate on x (the forward input), not on the forward output.

Example

x = np.array([[-1.0, 0.0, 2.0],
              [ 3.0, -4.0, 5.0]])
relu(x)
# -> array([[0., 0., 2.],
#           [3., 0., 5.]])

dOut = np.array([[0.1, 0.2, 0.3],
                 [0.4, 0.5, 0.6]])
relu_backward(dOut, x)
# -> array([[0. , 0. , 0.3],
#           [0.4, 0. , 0.6]])

The gradient at position (0, 2) survives as 0.3 because x = 2.0 > 0; the gradient at (0, 0) is zeroed because x = -1.0, and at (0, 1) it is zeroed because x = 0.0 is not strictly positive.

Constraints

  • x and dOut are float arrays of identical shape (any dimensionality); use vectorized NumPy, no Python loop over elements.
  • At x == 0 the derivative is taken to be 0 (gate on x > 0, strictly greater).
  • Do not modify dOut or x in place; return a new array.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug