KatInterview

Build a Tiny Backpropagation Engine Over Torch Tensors

Machine LearningModel answer
HardModel answerMachine Learningautogradbackpropagationreverse-mode-differentiation

Last updated

Design a small tensor class that records a computation graph for add, mul, matmul, ReLU and sum, then runs reverse-mode differentiation to give correct gradients for every input.

Write the core of a reverse-mode automatic differentiation system. You may use PyTorch tensors purely as numeric storage, but every gradient must come from backward rules that you write yourself. Do not use PyTorch's own autograd to produce results. You may use it in tests to verify yours.

Implement a Tensor wrapper with this interface:

import torch

class Tensor:
    def __init__(self, data: torch.Tensor, requires_grad: bool = False): ...
    # self.data : torch.Tensor  -- the values
    # self.grad : torch.Tensor | None  -- populated by backward()

    def __add__(self, other): ...      # elementwise
    def __mul__(self, other): ...      # elementwise
    def __matmul__(self, other): ...   # 2-D matrix product, (n, m) @ (m, p)
    def relu(self): ...
    def sum(self): ...                 # sum of all elements -> one-element tensor
    def backward(self): ...            # called on a one-element output

Each operation should return a new Tensor that remembers how it was produced. Calling backward() on a final scalar must fill in .grad for every tensor in the graph that requires gradients.

Examples:

x = Tensor(torch.tensor([[1.0, 2.0]]), requires_grad=True)             # (1, 2)
W = Tensor(torch.tensor([[1.0, -1.0], [0.5, -2.0]]), requires_grad=True)  # (2, 2)
y = (x @ W).relu().sum()      # x @ W = [[2.0, -5.0]]  ->  y = 2.0
y.backward()
# x.grad == [[1.0, 0.5]]
# W.grad == [[1.0, 0.0], [2.0, 0.0]]

a = Tensor(torch.tensor(3.0), requires_grad=True)
b = a * a + a                 # 12.0
b.backward()
# a.grad == 7.0   (derivative 2a + 1)

Rules:

  • The computation forms a directed acyclic graph. A tensor may feed several operations, or feed the same operation twice (as in a * a).
  • Every gradient has exactly the shape of the tensor it belongs to.
  • A result requires gradients if at least one of its inputs does.
  • Assume + and * take operands of identical shape (no broadcasting), backward() is called on a one-element output, and a leaf's gradient starts as None.

Describe your design, give the code, state its complexity, and explain how you would test it.

Hints

Hint 1

Give each result a list of its parent tensors and a small function that, given the gradient flowing into the result, returns the gradient contribution for each parent.

Hint 2

A tensor used in several places receives several contributions, so always add into its gradient rather than assigning. Process nodes in reverse topological order so a node's gradient is complete before it is pushed to its parents.

Hint 3

For C = A @ B, the contributions are dA = dC @ B.T and dB = A.T @ dC. For ReLU, multiply the upstream gradient by a mask of where the input was positive. For sum, broadcast the scalar upstream gradient to the input's shape.