This is a small C implementation of Andrej Karpathy's micrograd, based on his spelled-out intro to neural networks and backpropagation video.
It is a learning project, not a production autodiff library.
Build
cmake --preset debug
cmake --build --preset debug
ctest --preset debug
./build/debug/micrograd_basic
Documentation
cmake --preset docs
cmake --build --preset docs
open build/docs/html/index.html
The documentation target requires Doxygen. HTML output uses the vendored Doxygen Awesome CSS theme in docs/doxygen-awesome.
Example
bool mg_backward(mg_graph *g, mg_value *out)
Compute gradients for all values that contribute to an output value.
float mg_grad(const mg_value *v)
Get the gradient of a value.
struct mg_graph mg_graph
Opaque owner of a linked list of mg_value nodes.
Definition value.h:22
void mg_graph_free(mg_graph *g)
Free a graph and all values it owns.
mg_value * mg_scalar(mg_graph *g, float data)
Create a new scalar value.
mg_value * mg_mul(mg_graph *g, mg_value *a, mg_value *b)
Multiply two values.
struct mg_value mg_value
Opaque scalar node in a computation graph.
Definition value.h:30
mg_graph * mg_graph_new(void)
Create a new graph.
float mg_data(const mg_value *v)
Get the scalar data of a value.
See examples/basic.c for a small MLP training example.
Notes
mg_graph owns all mg_values. Neurons, layers, and MLPs own their arrays, but not scalar values; free them before freeing the graph.
mg_backward resets gradients before backprop. Hidden MLP layers use tanh; the output layer is linear. mg_pow supports exponent gradients for positive bases.