← Back to Projects

MiniTorch-OCaml

Reverse-mode autodiff in OCaml.

Spring 2026 · In progress

  • OCaml
  • Autodiff
  • Computation Graphs
  • Gradient Checking
  • SGD/Adam

Key outcomes

  • Graph nodes with values, grads, parents, and op metadata for reverse-mode
  • Backward rules for arithmetic, activations, reductions, transpose, and matmul
  • Central-difference gradchecks before I believe any training curve

Project overview

Backprop flow

MiniTorch is reverse-mode autodiff in OCaml. Forward ops grow a graph, and the backward pass walks the parents and fills in gradients. A tiny MLP with SGD and Adam is there to see whether the pieces still connect. I trust the finite-difference check when the loss moves.

System architecture

MiniTorch computation graph overview
Each op records parents so reverse-mode can propagate local derivatives.

Inputs → forward ops (graph grow) → scalar loss → reverse traversal → parameter gradients → optimizer step.

Tensor / graph nodes
Hold values, gradients, parents, and operation tags that define the local backward rule.
Forward ops
Elementwise arithmetic, activations, reductions, transpose, and matmul that extend the graph.
Reverse engine
Topological reverse traversal that applies local gradients and accumulates into parents.
Gradcheck
Central-difference numerical checks that catch calculus bugs types cannot see.

Engineering decisions

DecisionAlternativeWhy
OCaml for an autodiff enginePython/NumPyOCaml.
Reverse-mode versus forward-modeForward-modeReverse-mode.
Eager graph buildingDefine-and-run static graphEager recording.
Gradcheck as the operator gateTrust training lossRequire forward + backward + gradcheck when adding operators.

Results and future work

Reverse-mode engine. Forward builds a graph; backward fills gradients for supported ops including matmul and common activations. Numerical checks. Central-difference gradcheck exercises analytic gradients for the implemented ops. Training smoke signal. Toy MLP with SGD/Adam shows loss decrease when autodiff and updates agree.

Still open. No GPU backend, convolutions, or production framework surface.

  • Broader operator set with broadcasting rules.
  • Vectorized backend once correctness is boring.
  • Richer optimizers and serialization for experiment replay.
Full engineering log

Motivation

Why I started this

What pulled me in, and what I wanted to get better at.

Why I built it

I was tired of treating PyTorch as a calculator I did not understand. I wanted to write backpropagation myself.

What interested me

Calling backward() is easy. Keeping parent links and local derivatives correct when a node is reused is not. Wrong grads still train for a bit, which is worse.

What I wanted to learn

OCaml made the graph nodes explicit. Gradcheck against finite differences is what actually caught my calculus mistakes.

System Overview

How the system fits together

MiniTorch is reverse-mode autodiff in OCaml. Forward ops grow a graph, and the backward pass walks the parents and fills in gradients. A tiny MLP with SGD and Adam is there to see whether the pieces still connect. I trust the finite-difference check when the loss moves.

01

Tensor / graph nodes

Hold values, gradients, parents, and operation tags that define the local backward rule.

02

Forward ops

Elementwise arithmetic, activations, reductions, transpose, and matmul that extend the graph.

03

Reverse engine

Topological reverse traversal that applies local gradients and accumulates into parents.

04

Gradcheck

Central-difference numerical checks that catch calculus bugs types cannot see.

05

Training demo

Toy MLP with SGD/Adam showing loss decrease when autodiff is correct.

Data flow

Inputs → forward ops (graph grow) → scalar loss → reverse traversal → parameter gradients → optimizer step.

Control flow

Forward is eager graph building. Backward is an explicit reverse walk. Gradcheck samples perturbations around a point and compares analytic vs numerical derivatives.

Computation graph
MiniTorch computation graph overview

Each op records parents so reverse-mode can propagate local derivatives.

Engineering Breakdown

Broken down by discipline

Each block is the requirement, how that part works, what I checked, and what is still open.

01Graph Construction

Graph Construction

Goal

Make every forward operation an explicit node that records enough metadata for a correct local backward rule.

Design

Typed graph nodes store value, grad, parents, and op. Arithmetic, activations (ReLU, Tanh, Exp, Log, Sigmoid, Pow), Sum, Transpose, and MatMul each extend the graph during the forward pass instead of mutating values in place without history.

Challenges

  • API surface had to stay small while remaining extensible for new ops.
  • Shape and broadcasting mistakes look like training instability rather than type errors.
  • Forgetting a parent edge produces silent zero gradients.

Iterations

  • Scalar-friendly arithmetic nodes.
  • Activations with simple local derivatives.
  • Reductions and matmul once multi-dimensional training demos mattered.

Final implementation

A forward API that grows a directed graph suitable for reverse-mode accumulation without hiding parent structure.

Forward pass
Forward pass building the computation graph

Ops append nodes; values alone are not enough for backward.

02Reverse-Mode AD

Reverse-Mode AD

Goal

Propagate gradients from a scalar loss back to parameters with correct local Jacobians.

Design

Seed the loss gradient, walk parents in reverse, and apply each op's local rule. Accumulation must respect multiple consumers of the same node. This is the systems core: autodiff as graph algorithm plus calculus tables.

Challenges

  • Gradient bugs rarely show up in forward outputs.
  • Shared subgraphs require careful accumulation, not overwrite.
  • Matmul and reductions have local rules that are easy to transpose wrong.

Iterations

  • Elementwise reverse rules.
  • Activation derivatives.
  • Reduction and matmul reverse paths used by the MLP demo.

Final implementation

A reverse engine that fills .grad fields from parent references so optimizers see usable parameter updates.

Backprop
Reverse-mode gradient propagation

Reverse traversal applies local rules and accumulates into parents.

03Numerical Validation

Numerical Validation

Goal

Prove analytic gradients against finite differences before trusting a training curve.

Design

Central-difference gradcheck in the demo harness compares engine gradients to numerical estimates. New operators are expected to ship with forward, backward, and a check. Types catch structure; numerics catch calculus.

Challenges

  • Finite differences are noisy near non-smooth points like ReLU kinks.
  • Passing a loss curve without gradcheck can still hide a wrong op that rarely activates.
  • The current harness prints check output; hardening toward asserted CI tests is future work.

Iterations

  • Manual derivative spot checks.
  • Central-difference sweeps for core ops.
  • Training-loop smoke tests as an integration signal, not a substitute for gradcheck.

Final implementation

A gradcheck workflow used whenever operators change, plus demo training that shows loss decrease when the engine is healthy.

Gradcheck
Gradient checking against finite differences

Numerical agreement is the proof types cannot provide.

Key Design Decisions

Design decisions

DecisionAlternativeWhy
OCaml for an autodiff enginePython/NumPyOCaml. Exhaustiveness on ops is part of the safety story.
Reverse-mode versus forward-modeForward-modeReverse-mode. One scalar loss to many parameters is the target workload.
Eager graph buildingDefine-and-run static graphEager recording. Debuggability beat premature graph compilers.
Gradcheck as the operator gateTrust training lossRequire forward + backward + gradcheck when adding operators.
Notes on these decisions

OCaml for an autodiff engine

Which language keeps graph nodes explicit without drowning in boilerplate?

Python is the ML default and soft on invariants. OCaml makes node variants and exhaustive matches hard to leave incomplete.

OCaml. Exhaustiveness on ops is part of the safety story.

Reverse-mode versus forward-mode

Which AD mode matches neural training?

Forward-mode scales with inputs; reverse-mode scales with outputs. Training needs reverse.

Reverse-mode. One scalar loss to many parameters is the target workload.

Eager graph building

When is the graph constructed?

Static graphs optimize earlier; eager graphs match how students debug PyTorch-style code.

Eager recording. Debuggability beat premature graph compilers.

Gradcheck as the operator gate

How do you know a new op is correct?

Loss curves are necessary but insufficient. Gradcheck is slower and catches silent calculus bugs.

Require forward + backward + gradcheck when adding operators.

Results & Validation

What held up

What worked in the end, what I can show for it, and where it's still limited.

Reverse-mode engine

lib/tensor.ml operator set and reverse traversal

Forward builds a graph; backward fills gradients for supported ops including matmul and common activations.

Validation
Gradcheck evidence visual

Finite differences keep reverse-mode honest.

Numerical checks

Gradcheck path in the demo harness

Central-difference gradcheck exercises analytic gradients for the implemented ops.

Training smoke signal

Demo training loop in main.ml

Toy MLP with SGD/Adam shows loss decrease when autodiff and updates agree.

Limitations

  • No GPU backend, convolutions, or production framework surface.
  • test/ is still thin; gradcheck prints today rather than a full asserted suite.
  • Broadcasting and operator coverage are intentionally incomplete.
Bench notes

The longer design notes, the timeline, and the revisions. The sections above are the system and what I measured.

Evolution

How it got here

The steps I can put in order from the notes. A clip opens from its still.

  1. Stage 1

    Core tensor nodes

    Values, grads, parents, and arithmetic ops that prove the graph idea.

  2. Stage 2

    Activations and reductions

    Local derivatives beyond +, *, and the first non-elementwise paths.

  3. Stage 3

    Matmul + MLP demo

    Enough linear algebra for a tiny network and optimizer loop.

  4. Next

    Hardened tests and broader ops

    Asserting gradchecks in CI, richer broadcasting, and a vectorized backend once the operator set is stable.

Reflection

Looking back

What surprised me, what I'd redo, and questions I'm still chewing on.

What surprised me

  • Most bugs were local Jacobian mistakes that still produced plausible forward values.
  • Types prevented structural holes more than calculus holes.

What I would redesign

  • Asserted gradcheck CI for every op.
  • Clearer shape error messages at op construction time.
  • Separate pure math tables from graph mutation code.

Future improvements

  • Broader operator set with broadcasting rules.
  • Vectorized backend once correctness is boring.
  • Richer optimizers and serialization for experiment replay.

Questions that emerged

  • Where should broadcasting live: op nodes or a lowering pass?
  • How do frameworks keep reverse-mode fast without losing debuggability?

Notes

  • Autodiff bugs hide in forward outputs. Gradcheck is the plant test.
  • A tensor without parent metadata is just an array; reverse-mode needs the graph.
  • Loss curves confirm integration; they do not replace operator-level numerical proofs.