We’ve gotten to the point with our tensor library that it’s probably a good time to add autograd: We have basic math functionality, we have the ability to test in Python, and we have a flexible class framework that can be expanded to handle autograd. In this post, we’ll build out the most basic version of autograd, before building to something capable of training an MLP in future posts. We’ll find out that autograd is a lot more complicated than it looks: Karpathy makes it look simple in micrograd, and indeed it is, but to implement it in C++ and for practical networks of two or more dimensions, implementation complexity jumps significantly. I will try to focus on the conceptual learning, as staring at huge blocks of code doesn’t do much for most people. The full code, including commit history, is available on GitHub. This post roughly covers commits 612c4d6-80e0e99

To implement automatic backpropagation of the gradient (autograd), we will need to build a function that creates a topological map of a given model or function, starting at the output and working its way backwards, and then calculates the gradient at each step along the same path. To do this, we need to add a bunch of features:

  • Nodes
    • Operation type
    • Previous: what tensors were used for this operation
    • Gradient function: the specific backward function(s) for that operation
    • Output/next: the tensor storing the result of this operation. Rather than storing a pointer to out, the node gets attached to the output tensor; this way, the node can be found from the output tensor, useful for moving backwards through the graph
  • Gradient function definitions for each operation type, i.e.:
    • For a matmul operation between a and b, we need to define how the gradient flows back to both a and b via the chain rule, for example: grad@a = g*transpose(b), grad@b = transpose(a)*g
  • A graph building function
    • This starts at the end(output) of a function or network and works its way backwards, building a topological map as it goes

Once we have these all written, we should be able to call backward on the output of the network, and have it automatically build a graph and backpropagate the gradient through it. There are, however, some complications that come up when implementing all this in C++ and for 2D matrices:

  1. We’re working with matrices, not scalars: this means we need to add a framework to handle shape, and the backpropagation math is significantly more complicated. We’ll cover this in the next post.
  2. Memory handling: In Python, memory and object identity are handled automatically, but we will have to build ours out manually.
  3. Graph building off: Micrograd never needs to switch graph building off, but we will need to in a number of situations to avoid things like calculating our gradient creating its own graph whenever it uses a tensor class operation(like a * b).

Nodes:

To implement autograd, we first need to add a concept to our library: Nodes.

Nodes connect tensors together through the operations they represent.
Nodes connect tensors together through the operations they represent.

Where we have, up until now, only been dealing with tensors, which are basically a data class, we now need to add the concept of nodes: A record of how our Tensors are connected together through mathematical operations. Nodes will store an operation: Operation type, input tensors, output tensors, and a backwards function generated for that node. It’s important that we don’t bring our thinking of a neuron and confuse it with a node. Where neurons are sometimes called nodes in other material, here the nodes are explicitly NOT a data-holding neuron; rather, they are the connective tissue between neurons: Nodes store functions and connections, whereas a Tensor/Neuron stores data.

Gradient functions:

For each operation type that may have a gradient, we need to define how the gradient flows through it. If we looked at this based on tensors alone, it would be nearly impossible: there are infinite ways to combine tensors. Autograd implies that we dynamically compute the chain rule for each tensor. That’s not really the case. Instead, we compute the chain rule-based gradient function for every operation type. If we have nodes connecting our tensors together, we have a record of the inputs that created each tensor. We can then combine our nodes with the gradient function associated with that operation, thereby automatically defining the gradient function for any tensor produced by a tensor operation. This means that, even when an expression is more complex, say:

x=a∗b∗c∗dx=a*b*c*d

We don’t have a chain rule-based gradient function defined for this expression, but we can use our tensor operations to break this down into:

e=a∗be=a*b
f=c∗df=c*d
x=e∗fx=e*f

Once the expression is broken down, we can then use our predefined gradient functions. The only catch is that we need a way to ensure a record of how a given expression was broken down so we know how the gradient should flow back through it. To achieve this, we’ll use graph building and nodes.

Graph building function:

Having the gradient defined for a given operation between tensors is only half the picture. We also need to map out the whole expression/network, so that we know what sequence to call our global backwards function. For example, in the expression from before:

e=a∗be=a*b
f=c∗df=c*d
x=e∗fx=e*f

Trying to calculate the gradient at A before we’ve found it at E will be impossible. To ensure we have the correct sequence, we need to build a topological mapping function. I’ll go further in depth in a future post about topological mapping, because it’s super cool, but for this post we can look to Micrograd’s implementation of this for inspiration:

topo = []
visited = set()
def build_topo(v):
if v not in visited:
visited.add(v)
for child in v._prev:
build_topo(child)
topo.append(v)
build_topo(self)

This function simply starts at a given location and moves backward through the expression, adding every location as it goes. The function also keeps track of the locations already visited, so nothing gets visited twice. This is key because a single location may be connected to multiple downstream locations, and we want to ensure no location is added to the list twice. The final output of this function should be a list holding every location in the expression, ordered from the inputs to the output, with no duplicates. Our C++ implementation will do the same thing:

std::vector<Tensor> topo;
std::unordered_set<TensorImpl*> visited;
std::function<void(const Tensor&)> build = [&](const Tensor& t) {
if (!visited.insert(t.impl()).second) return;// if already visited return
if (t.impl()->grad_fn)
for (const Tensor& input : t.impl()->grad_fn->inputs) build(input);
topo.push_back(t);
};
build(*this);

Notice that to be able to handle the recursive nature of our movement through the graph, we need to call the function within its own declaration. While it was a surprise to me, calling a function within its own declaration is ok in C++ as long as it’s done correctly.

Memory and identity:

Now we need to handle memory tracking and identity. We need to create a shared handle object that only has a pointer to tensor data(like values, shape, and gradient). Put another way: We need to ensure that copying a tensor only copies a handle to the tensor, rather than creating an independent set of data. Our data already works this way, but we need to make all the tensor values(such as shape and grad, etc.) work the same way.
To implement this, we do the same as PyTorch: Create a thin handle with the Tensor name that points to a shared implementation that has everything else:

struct TensorImpl {
std::shared_ptr<float> data;
std::vector<int> shape;
//more tensor data will go here
};

We also refactor the existing tensor class to point to a TensorImpl:

Tensor::Tensor(const std::vector<int>& shape) : impl_(std::make_shared<TensorImpl>()) {
impl_->shape = shape;
impl_->data = std::shared_ptr<float>(ptr, [](float* p) { cudaFree(p); });
float* data() const { return impl_->data.get(); }
const std::vector<int>& shape() const { return impl_->shape; }
private:
std::shared_ptr<TensorImpl> impl_;
};

There are a couple more details to this refactor, but the main part is there. Now any call to tensor asking for data simply goes through the shared TensorImpl, and new “Tensors” are new handles to the same data, rather than being an unlinked copy. This will be especially useful for when multiple copies are accessing the same gradient:

Before and after: Adding a thin handle to handle tensor identity.
Before and after: Adding a thin handle to handle tensor identity.

When do we record gradients/build graphs:

While we might assume that we always want to record a gradient, in reality there are a number of situations where it is either necessary or efficient to have requires_grad set to off. Some classic examples are inputs which don’t need a gradient because we can’t change them, or when we’re creating tensors to store a gradient itself, which obviously doesn’t need a gradient, and would create a recursive loop if we didn’t have a way to turn it off. We therefore need to add a flag to the tensorImpl that tells whether a given tensor needs a gradient:

struct TensorImpl {
std::shared_ptr<float> data;
std::vector<int> shape;
bool requires_grad = false; //this is our requires grad flag
std::shared_ptr<TensorImpl> grad;
std::shared_ptr<Node> grad_fn;
};

On top of a local flag, we also want a global flag that is used as a default when creating new tensors. This lives in Tensor.cu’s namespace:

namespace {
bool g_gradEnabled = true;
}

Finally, we want to add a guard that gives us an easy way to temporarily turn grad off, so we don’t create recursive loops:

class NoGradGuard {
public:
NoGradGuard();
~NoGradGuard();
private:
bool prev_;
};

This grad guard will be used whenever we do operations for which we don’t want to record nodes to the graph, for example when using tensor operations to calculate the gradient during backpropagation.

Let’s Test!:

Now that we have all the basics set up, we can create a test script in Python to test our graph generation and gradient accumulation:

import operator
import numpy as np
import pytest
import minitensor as mt
# Helpers
def scalar(value, requires_grad=True):
"""Make a 0-dimensional (shape []) tensor holding one value."""
t = mt.Tensor.from_numpy(np.array(value, dtype=np.float32))
t.requires_grad = requires_grad
return t
def value_of(t):
"""Read a single-element tensor back as a Python float."""
return float(t.to_numpy())
SCALAR_CASES = [
# a*b + c: d/da = b, d/db = a, d/dc = 1
("a*b+c", {"a": 2.0, "b": 5.5, "c": 3.0},
lambda v: v["a"] * v["b"] + v["c"],
14.0, {"a": 5.5, "b": 2.0, "c": 1.0}),
# more cases here, cut for conciseness
]
@pytest.mark.parametrize("name,inputs,fn,expected_value,expected_grads",
SCALAR_CASES, ids=[c[0] for c in SCALAR_CASES])
def test_scalar_examples(name, inputs, fn, expected_value, expected_grads):
tensors = {k: scalar(v) for k, v in inputs.items()}
out = fn(tensors)
assert value_of(out) == pytest.approx(expected_value)
out.backward()
for k, expected in expected_grads.items():
assert tensors[k].grad is not None, f"{k}.grad was never set"
assert value_of(tensors[k].grad) == pytest.approx(expected), f"wrong gradient for {k}"

The full test script is much more thorough than this snippet, but I wanted to highlight this part as a reminder that, while it’s definitely useful to have an AI agent write many of your boilerplate tests, it’s critical to verify that the test set is testing the cases you want correctly. The addition of a hand-checkable test case can be a great sanity check whenever possible.
Now that we’ve implemented basic autograd, in the next post we’ll move on to adding everything else we need for an MLP trainer: unbroadcasting, functions like softmax and ReLU, more math operations like exponentiation and transpose, all eventually building towards an SGD function.

Posted in

Leave a Reply