Build a Tiny Backpropagation Engine Over Torch Tensors
Machine LearningModel answerLast 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 asNone.
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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reverse-mode differentiation works in two phases.
- Forward: each operation computes its output values and stores a reference to its input tensors plus a closure that knows the local derivative.
- Backward: starting from a scalar output with gradient 1, visit nodes so that each node is processed only after everything that depends on it. Each node pushes
upstream_grad * local_derivativeinto its parents, adding to whatever is already there.
This is the chain rule applied along the graph, in the direction that makes one pass sufficient for a scalar output.
Local rules
Let g be the gradient of the final scalar with respect to the node's output.
| Op | Parent gradient contributions |
|---|---|
a + b | g to a, g to b |
a * b | g * b.data to a, g * a.data to b |
A @ B | g @ B.T to A, A.T @ g to B |
relu(a) | g * (a.data > 0) to a |
sum(a) | g (a scalar) expanded to a's shape |
The matmul shapes check out: g is (n, p), B.T is (p, m), giving (n, m), which is A's shape. Likewise A.T is (m, n) times g (n, p) gives (m, p), B's shape.
Implementation
import torch
class Tensor:
def __init__(self, data, requires_grad=False, _parents=(), _backward=None):
self.data = data
self.requires_grad = requires_grad
self.grad = None
self._parents = _parents
self._backward = _backward # fn(g) -> tuple of grads, one per parent
@staticmethod
def _make(data, parents, backward_fn):
rg = any(p.requires_grad for p in parents)
if not rg:
return Tensor(data, False)
return Tensor(data, True, parents, backward_fn)
def __add__(self, other):
return Tensor._make(self.data + other.data, (self, other),
lambda g: (g, g))
def __mul__(self, other):
a, b = self.data, other.data
return Tensor._make(a * b, (self, other),
lambda g: (g * b, g * a))
def __matmul__(self, other):
A, B = self.data, other.data
return Tensor._make(A @ B, (self, other),
lambda g: (g @ B.T, A.T @ g))
def relu(self):
mask = (self.data > 0).to(self.data.dtype)
return Tensor._make(self.data * mask, (self,),
lambda g: (g * mask,))
def sum(self):
shape = self.data.shape
return Tensor._make(self.data.sum(), (self,),
lambda g: (g.expand(shape).clone(),))
def backward(self):
assert self.data.numel() == 1, "backward needs a one-element output"
# iterative topological sort
order, seen = [], set()
stack = [(self, False)]
while stack:
node, done = stack.pop()
if done:
order.append(node)
continue
if id(node) in seen:
continue
seen.add(id(node))
stack.append((node, True))
for p in node._parents:
if p.requires_grad and id(p) not in seen:
stack.append((p, False))
grads = {id(self): torch.ones_like(self.data)}
for node in reversed(order):
g = grads.get(id(node))
if g is None:
continue
if node._backward is None: # leaf
node.grad = g if node.grad is None else node.grad + g
continue
for parent, pg in zip(node._parents, node._backward(g)):
if parent.requires_grad:
pid = id(parent)
grads[pid] = pg if pid not in grads else grads[pid] + pg
Gradients are kept in a dictionary during the pass and written to leaves at the end, so intermediate nodes do not keep stale .grad values and repeated calls to backward() on a fresh graph accumulate into leaves the way PyTorch does. Using reversed(order) from a post-order DFS guarantees every node is handled after all its consumers.
Why accumulation matters
In b = a * a + a, the node a is a parent three times. The multiply gives g*a twice (once per operand position) and the add gives g once, so the total is 2a + 1 = 7 at a = 3. If you assigned instead of adding, you would get a wrong answer such as 3 or 1.
Complexity
- Time: O(V + E) for the topological sort, plus the cost of each local rule. Backward costs roughly the same order as the forward pass; matmul backward is two matrix products, about 2x the forward FLOPs.
- Memory: O(V) for the graph and the gradient dictionary, plus the saved activations (the closures hold references to inputs and masks).
Testing
- Compare against
torch.autogradon random inputs withtorch.allclose, usingfloat64for tight tolerances. - Run finite-difference checks: perturb each input element by
eps, compare(f(x+eps) - f(x-eps)) / (2 eps)with the analytic gradient. - Cover edge cases: a tensor used twice in one op, a diamond-shaped graph, ReLU at exactly 0 (gradient 0 under the
> 0convention, matching PyTorch), a constant input withrequires_grad=False(its.gradshould remainNone), and non-square matmul shapes to catch transposition mistakes.
Common mistakes
- Assigning rather than accumulating gradients.
- Running the backward pass in insertion order or with naive recursion, which can process a node before all its consumers have contributed, or visit shared nodes repeatedly (exponential time on diamonds).
- Swapping the transposes in matmul, which passes for square matrices but fails on rectangular ones.
- Forgetting to expand the scalar gradient in
sum, or returning a gradient with the wrong shape. - Using recursion for the topological sort, which hits Python's recursion limit on deep graphs.
Extensions to mention
Broadcasting would require summing the gradient over broadcast dimensions to restore the operand's shape. Non-scalar outputs would need an explicit upstream gradient argument. Freeing the graph after backward, a no_grad mode, and wrapping each op as a torch.autograd.Function are other natural follow-ups.