- Notifications
You must be signed in to change notification settings - Fork2.2k
A tiny scalar-valued autograd engine and a neural net library on top of it with PyTorch-like API
License
karpathy/micrograd
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A tiny Autograd engine (with a bite! :)). Implements backpropagation (reverse-mode autodiff) over a dynamically built DAG and a small neural networks library on top of it with a PyTorch-like API. Both are tiny, with about 100 and 50 lines of code respectively. The DAG only operates over scalar values, so e.g. we chop up each neuron into all of its individual tiny adds and multiplies. However, this is enough to build up entire deep neural nets doing binary classification, as the demo notebook shows. Potentially useful for educational purposes.
pip install micrograd
Below is a slightly contrived example showing a number of possible supported operations:
frommicrograd.engineimportValuea=Value(-4.0)b=Value(2.0)c=a+bd=a*b+b**3c+=c+1c+=1+c+ (-a)d+=d*2+ (b+a).relu()d+=3*d+ (b-a).relu()e=c-df=e**2g=f/2.0g+=10.0/fprint(f'{g.data:.4f}')# prints 24.7041, the outcome of this forward passg.backward()print(f'{a.grad:.4f}')# prints 138.8338, i.e. the numerical value of dg/daprint(f'{b.grad:.4f}')# prints 645.5773, i.e. the numerical value of dg/db
The notebookdemo.ipynb provides a full demo of training an 2-layer neural network (MLP) binary classifier. This is achieved by initializing a neural net frommicrograd.nn module, implementing a simple svm "max-margin" binary classification loss and using SGD for optimization. As shown in the notebook, using a 2-layer neural net with two 16-node hidden layers we achieve the following decision boundary on the moon dataset:
For added convenience, the notebooktrace_graph.ipynb produces graphviz visualizations. E.g. this one below is of a simple 2D neuron, arrived at by callingdraw_dot on the code below, and it shows both the data (left number in each node) and the gradient (right number in each node).
frommicrogradimportnnn=nn.Neuron(2)x= [Value(1.0),Value(-2.0)]y=n(x)dot=draw_dot(y)
To run the unit tests you will have to installPyTorch, which the tests use as a reference for verifying the correctness of the calculated gradients. Then simply:
python -m pytest
MIT
About
A tiny scalar-valued autograd engine and a neural net library on top of it with PyTorch-like API
Resources
License
Uh oh!
There was an error while loading.Please reload this page.

