karpathy/micrograd
A tiny scalar-valued autograd engine and a neural net library on top of it with PyTorch-like API
🧠 A 100-line autograd engine that fits in a tweet thread
Karpathy's micrograd builds a full neural net library on a scalar-valued reverse-mode autodiff engine — in under 150 lines total.
Andrej Karpathy released micrograd as a minimal educational Autograd engine. It implements backpropagation over a dynamically built DAG, operating only on scalar values. Each neuron is broken into tiny adds and multiplies, but enough to train deep neural nets for binary classification. A PyTorch-like API sits on top, keeping the whole thing readable and hackable.
✨ Highlights
- Scalar-valued DAG: chops neurons into individual adds and multiplies, building a graph node per operation
- Reverse-mode autodiff: computes gradients via backpropagation through the dynamically built graph
- PyTorch-like API:
Valueclass supports+,*,**,relu,/,+=, and.backward()for gradient computation - Neural net library:
micrograd.nnmodule includesNeuron,Layer, andMLPclasses for building networks - Demo notebook: trains a 2-layer MLP binary classifier on the moon dataset using SVM max-margin loss and SGD
- Graph visualization:
draw_dotfunction generates graphviz diagrams showing data and gradients per node - Unit-tested: gradients verified against PyTorch as reference
- Dependency-free core: only PyTorch required for tests, not for the engine or nn library itself
💡 Why it matters
Most autodiff engines are large and complex. micrograd strips everything down to the essentials, making reverse-mode autodiff approachable for students and curious developers. It trades performance for clarity — scalar operations are slow, but the code is short enough to read in one sitting.
It's not built for production training, but ideal for learning how backpropagation works under the hood. The companion project microgpt extends the idea into a full GPT-2-like transformer, showing how the minimal engine scales up.
#Autograd #NeuralNetworks #DeepLearning #Education #TiniX