GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing bernsteinbear.com — Compiling ML models to C for fun Compiling ML models to C for funSeptember 19, 2023
I had a nice chat with my friend Chris recently. He walked me through the basics of machine learning while I was looking at Andrej Karpathy’s micrograd. If you are unfamiliar, micrograd is a very small implementation of a scalar-valued neural network (as opposed to vectors or matrices as the computational unit) in pure Python, which uses no libraries. Micrograd is a combination of a couple of different and complementary parts:
(If you don’t know what a MLP is, don’t worry too much. This post should give you a bit of background, especially if you are already comfortable with Python. You may want to go through and read and think about the micrograd source code before coming back. And maybe look at this interactive guide too. Or not! Your call. Playing with micrograd helped me a lot. Chris suggested trying to make a network learn XOR.) Together, these three major components let you write code that looks like this: And summon a neural network from thin air. The thing that got me the first time I read it was that I thought the building blocks were the network. In this library, no. Using a building analogy, they are more like blueprints or scaffolding. With each evaluation of the network, the connective tissue (intermediate computation graph) is constructed anew. In compiler terms, the building blocks are kind of like the front-end and the expression graph is a sort of intermediate representation (IR). You may be sitting there wondering why I am telling you this. I normally blog about compilers. What’s this? It’s because once I untangled and understood the three pieces in micrograd, I realized:
Which means… it sounds like a great opportunity for a compiler! This is why projects like PyTorch and TensorFlow have compilers (TorchScript/TorchDynamo/AOT Autograd/PrimTorch/TorchInductor/Glow, XLA, etc). Compiling your model speeds up both training and inference. So this post will not contain anything novel—it’s hopefully a quick sketch of a small example of what the Big Projects do. We’re going to compile micrograd neural nets into C. In order, we will
Let’s go! How micrograd does neural networksFirst, a bit about multi-layer perceptrons. MLPs are densely connected neural networks where input flows in one direction through the network. As it exists in the upstream repository, micrograd only supports MLPs. In case visual learning is your thing, here is a small diagram: In this image, circles represent data (input or intermediate computation
results) and arrows are weights and operations on the data. In this case, the
Karpathy implements this pretty directly, with each neuron being an instance of
the Below is the entire blueprint code for a multilayer perceptron in micrograd
(we’ll come back to the You can ignore some of the clever coding in But this neural network is not built just with floating point numbers. Instead
Karpathy uses this Intro to the expression builderI said that one of micrograd’s three components is an expression graph builder. Using the expression builder looks like a slightly more complicated way of doing math in Python: The But it’s a little different than normal math. It’s different first because it
has this It’s not visible in the normal string representation, though. They also have a hidden operator field: This means that we have two operands to the I said you could think about it like an AST but it’s not quite an AST because it’s not a tree. It’s expected and normal to have more of a directed acyclic graph (DAG)-like structure. Here It is assumed that the graph won’t have cycles in it2. So what does creating the graph look like in code? Well, the The But why do we have these expression graphs? Why not just use math? Who cares about all the back pointers? Let’s talk about grad(ient)Training a neural network is a process of shaping your function (the neural network) over time to output the results you want. Inside your function are a bunch of coefficients (“weights”) which get iteratively adjusted during training. The standard training process involves your neural network structure and also
another function that tells you how far off your output is from some expected
value (a “loss function”). A simple example of a loss function is
If you are trying to get some expected output, you want to minimize the value of your loss function as much as possible. In order to minimze your loss, you have to update the weights. To figure out which weights to update and by how much, you need to know how much each weight contributes to the final loss. Not every weight is equal; some have significantly more impact than others. The question “how much did this weight contribute to the loss this round” is
answered by the value of the grad (gradient) of that weight—the first
derivative—the slope at a point. For example, in To compute the grad, you need to traverse backwards from the loss5 to do something called reverse mode automatic differentiation (reverse mode AD). This sounds scary. Every article online about it has scary notation and squiggly lines. But it’s pretty okay, actually, so keep on reading. Fortunately for us, reverse mode AD, like evaluating an AST top to bottom, it is a graph traversal with some local state. If you can write a tree-walking interpreter, you can do reverse mode automatic differentiation. Reverse mode AD and backpropagationInstead of building up a parallel graph of derivatives (a sort of “dual” to the
normal expression graph), reverse mode AD computes local derivatives at each
node in the But how do you compose all those local derivatives? There’s no way it’s simple, right? Taking derivatives of big math expressions is scary… It turns out, calculus already has the answer in something called the chain rule. The chain ruleI am not going to pretend that I am a math person. Aside from what I re-learned in the last couple of weeks, I only vaguely remember the chain rule from 10 years ago. Most of what I remember is my friend Julia figuring it out instantaneously and wondering why I didn’t get it yet. That’s about it. So please look elsewhere for details if this section doesn’t do it for you. I won’t be offended. A quick overviewThe chain rule tells you how to compute derivatives of function composition.
Using the example from Wikipedia, if you have some function For example, if you have To take a look at the proof of this and also practice a bit, take a look at this short slide deck (PDF) from Auburn University. Their course page table of contents has more slide decks6. Also make sure to check out the list of differentiation rules on Wikipedia. It turns out that the chain rule comes in handy for taking derivatives of potentially enormous expression graphs. Nobody needs to sit down and work out how to take the derivative of your huge and no doubt overly complex function… you just have your building blocks that you already understand, and they are composed. So let’s apply the chain rule to expression graphs. Applying this to the graphWe’ll start with one Where Instead of just setting
To make this more concrete, let’s take a look at Karpathy’s implementation of
the derivative of This means that for each of the children, we will use the other child’s data
and (because of the chain rule) multiply it by the parent expression’s Now we have a function to do one derivative step for one operation node, but we need to do the whole graph. But traversing a graph is not as simple as traversing a tree. You need to avoid
visiting a node more than once and also guarantee that you visit child nodes
before parent nodes (in forward mode) or parent nodes before children nodes (in
reverse mode). The tricky thing is that while we don’t visit a node more than
once, visiting updates the node’s children (not the node itself), and nodes may
share children, so children’s For that reason, we have topological sort. Topological sort and graph transformationsA topological sort on a graph is an order where children are always visited before their parents. In general this only works if the graph does not have cycles, but—thankfully—we already assume above that the graph does not have cycles. Here is a sample topological sort on the To get a feel for how this works, we can do a topological sort of a very simple
expression graph, The topological sort says that in order to calculate the value Now that we have a way to get a graph traversal order, we can start doing some backpropagation. Applying this to backpropagationIf we take what we know now about the chain rule and topological sort, we can
do backpropagation on the graph. Below is the code straight from micrograd. It
first builds a topological sort and then operates on it in reverse, applying
the chain rule to each The If you are wondering why we set Putting it all togetherI am not going to get into the specifics, but here is what a rough sketch of
very simplified training loop might look like for MLP-based classifier for the
MNIST digit recognition
problem. This code is not
runnable as-is. It needs the image loading support code and a loss function.
The hyperparameters (batch size, etc) are completely arbitrary and untuned.
The full training
code
and corresponding engine
modifications
to add In this snippet, constructing the Here is a diagram I made to explain “adding loss on top” to someone: A sketch-like illustration of a model’s computation graph and loss. The model outputs one value, but how do we know how good it is? Well, we feed it into another subgraph—the loss function—which takes in a second input (the expected value) and itself outputs one value. I made this in Excalidraw. Then we have the backward pass, where we call Then we adjust all of the weights by their gradients. And remember to zero your gradients, folks!
This is nice and simple—thank you, Andrej—but is it fast enough to be usable? Let’s find out. Performance problemsUh oh, running this with CPython is slow. It looks like computing a forward pass for one image takes about a second. And then we have to do a backward pass, too. And we have to do several epochs of all 60,000 images. That is going to take way too long! Well, let’s do what everyone always suggests: try with PyPy. Oh neat, a couple images per second. Unfortunately, that is still not fast enough.
If I had to guess, my hypothesis for the pain points for all of the runtimes is:
But if I have learned anything at all over the years, instead of optimizing blindly in the dark, we should first measure. Checking with a profilerEmery Berger and his team have released an excellent Python profiling tool
called Scalene. To use it, you can
run I ran Scalene on our little micrograd MNIST and this is what it looks like.
A screenshot of the Scalene profiler’s view of micrograd. It looks
like there is a lot of It looks like in the memory column, the line is going up and to the right,
which is not what we want. It also looks like a huge amount of time is being
spent in creating the If you are old school and don’t trust new profiling tools, you can even confirm
these observations using
If you remove the Another easy enough fix is to add Last, we could also try to remove the nested function allocation (as we tried
above for Skybison/PyPy). This will remove And none of these little fixes changes the overall architecture of the program, which involves doing so much work to do a little math and a little graph walking7. So what’s to be done? SolutionsAs I like to say, the best way to make a program faster is to do less. Too much GC? Allocate less. Too much recursion? Topo sort less. Too much overhead? Interpret less. In more detail, my proposed solutions are:
This checks out with what we already know about compilers: if you can freeze some of the dynamism in the allowable semantics of a program, you get a performance benefit. Since the graph shape is static, this sounds like a fine idea. Let’s write a compilerThe goal with this compiler is to write something very small that fits reasonably cleanly into micrograd as it already is—not to re-architect anything. We could write a compiler to a kind of bytecode. This would get rid of all of the function calls and repeated tree traversals and pointer chasing. It would probably be faster. But unfortunately we would still have an interpreter loop, and that interpreter would be written in Python—would have a lot of overhead. Instead, we will go further and compile that straight line code to C. The end
goal is to make a Python C extension that we can The original version of this project compiled the For this reason, we are writing compilers for ForwardSince we have a topological sort, we might as well use it both forward and
backward. Then we only need to write a compiler that works one (Where it is assumed that Look, there it is! A neat little linearization of the graph. It’s kind of like
the topo sort we saw earlier, but in C code. This strategy works because we
don’t have loops and we don’t have re-definitions of We could have done this similarly to the interpreted version, where each kind
of operation has its own method ( The other operators are not so different. See if you can figure out how to
implement You may notice that this compilation strategy requires assigning identifiers to
My complete compiler implementation for all of the operations is about 40 lines and it even includes some small on-the-fly optimizations. But this compiler does forward passes. What about backward passes? We need to train faster, too. Backward has to be much more complicated, right? BackwardActually, it’s about the same complexity. We need only do a line-by-line
translation of the backpropagation functions (all the For example, we can revisit the backpropagation for (Like the forward version, assume for now that Let’s see how it works in practice. Huh, that’s weird. Why is there no backpropagation code for My complete backward pass compiler implementation is about 30 lines! Shorter than the forward pass, even. That’s pretty neat. You have just finished writing a compiler. Congratulations! Seriously, the
most involved and complicated bit is over. The rest is small details and Python
C-API specifics that you can skip if you like. All we’re missing is UpdateOnce we have done the backward pass (potentially multiple in a row), we need to adjust the weights by their gradients. Code generation for this is a fairly mechanical translation of the Python code into C. For comparison, here is the interpreted version: It loops over the model parameters at run-time and adjusts them. By contrast, the compiled version does the iteration at compile-time and has straight-line subtractions at run-time: It’s even the same length as the Python equivalent, if you exclude the
Setting the inputGetting input from Python code into C++ is a little tricky when it’s not simple data types like integers and floats. Ideally our generated ML code would be able to share memory with Python to avoid copying data back and forth, but that wouldn’t be as simple an implementation10, so we’re doing something slightly sillier. We’re going to have a function In this case, Note that the In order to use this C code from Python, we’ll have to make a Python C extension using the C-API. A Python C extensionHaving a bunch of free-floating code to update Most of this is straightforward (literally For example, here is a snippet of the wrapper code around the It is an example of a fastcall C-API function, meaning it takes its arguments in an array. We have to register it as such: And then make a Python-importable module description so that we can create a
And then we can create this magic That’s mostly it! Now we can use all of our hard work in model training and inference. Did it work? Is it faster?These are two separate questions and performance doesn’t mean anything if your code produces wrong output. CorrectnessTesting compilers can be tricky. There are a lot of parts and they all have to work on their own and also together. Thankfully in this case, we have a very small compiler with very few basic operations. This makes it not too difficult to write unit tests about the generated C code. It’s also probably worth having some side-by-side tests on the output numbers of the interpreted and compiled versions of the same code. If they are with some error margin, we can consider the compiler correct. I don’t recommend doing MNIST, though; the interpreted version is too slow and unit tests should be fast. Maybe try XOR. Thankfully, CPython uses the host system floating point implementation for its
PerformanceOn my machine, training goes from 1 image per second (interpreted) to >1000 images per second (compiled). This is at least a THOUSAND TIMES speed increase! It comes with an up-front cost, though; you have to compile the C code. If you use TCC, a very fast C compiler, you get pretty reasonable performance. I saw about half second compile times and 45 seconds per epoch. If you use Clang, a much slower C compiler, you get even better performance. Take a look at this handy dandy tradeoff table:
Either way, this is a pretty big win. I think we did it! Check out the full compiler code and compiler wrapper and training code on GitHub. ConclusionNeural networks are represented by static data-flow graphs which are executed in both forward and backward directions. This means they are kind of like tree-walking interpreters. It also means that compiling the tree to a lower-level representation makes the program faster. On a more serious note: I have traditionally been very uninterested in applying ML because it is oft-used to either harm people (surveillance, recommender systems siloing people, etc) or make software worse (several large companies recently mucked up their chronological feeds, etc). I learned about machine learning and wrote this post to understand the theory my friends geek out about regularly. I implore you, potential ML practitioner, to use your skills for Good. Massive thanks to Chris and Bianca for providing significant feedback on this post and to Tom for (naturally) finding and fixing a bug. More thoughts and further readingThere’s a lot more work to do if you are interested and have the time. I might follow-up on these later. I might not. Linearizing but still using PythonHow much faster can we make the Python version? If we only build the graph once and only topo sort once and just re-set the input every time, do we get faster? I think probably yes. My preliminary numbers show ~100-200x speedup on CPython and ~800x speedup on PyPy. And we didn’t even have to write a compiler! A
|
| Compile time (s) | Time per epoch (s) | Speedup | |
| Interpreted | 0 | 60,000 | 1x |
| TCC | 0.5 | 45 | 1333x |
TCC with Dot |
0.2 | 14 | 4300x |
Clang -O1 |
~379 | 8 | 7500x |
Clang -O1 with Dot |
~330 | 3.5 | 17,000x |
Clang -O2 -march=native with Dot |
~730 | 3 | 20,000x |
Note that we even get better compile times for TCC and Clang -O1 than without
Dot. And it really helps with the preliminary PyPy numbers, bringing those up
to ~3300x. Wow, very nice. Great success.
Right now our compilation strategy works for both training and inference. This is great, because it does make both of them faster than before, but it comes with a tradeoff: inference is slightly slower.
If, post training, you freeze the weights and make their immutability known, things get a lot more efficient. Right now we have so many memory loads and stores and it’s hard for the C compiler to prove anything about the properties of the numbers when it is trying to optimize. It probably also prevents use of SIMD instructions. If we can inline the weights as double constants in the generated C code, we can probably get much better machine code.
We managed to remove a lot of the overhead for the program we had, but the
overall architecture did not improve much. To do that, we need to move from
scalar-valued to tensor-valued Values.
It’s kind of like programming in assembly (scalar) vs a higher level (tensor)
language. It’s much harder to make optimizations directly on the assembly. If
you have semantically bigger and more descriptive operations in your AST
(matmul, etc), the compiler can better understand what you mean and optimize
that.
It also brings better data locality (matrix is stored densely and in either
row-major or column-major order) and we can get some vectorized math instead of
millions of mulsd.
From what I can tell, optimizing linear algebra IRs is an ongoing area of research.
PyPy is a JIT compiler for Python, but it also includes a general-purpose programming language called RPython. The neat thing is, if you write an interpreter in RPython, PyPy will turn your interpreter into a tracing JIT compiler. So this brings up some questions:
What if you wrote micrograd in RPython? Would PyPy make an effective JIT out of the tree-walking interpreter… even if it allocated all the AST nodes on the fly? Would it blow the trace length limit?
What if you generated Python code or bytecode? This doesn’t even require
writing the interpreter in RPython, but it does require writing a compiler from
Value graphs to Python (bytecode). Could PyPy compile this effectively?
I wrote a second post about compiling ML! It’s about automatically vectorizing the scalar IR.
See also Differentiable Programming from Scratch.
An activation function is supposed to mimic the behavior of biological neurons when receiving an impulse or something like that. See this blog post for an explanation of why they are necessary. There are other kinds of activation functions, like sigmoid and tanh, but for Math Reasons I Am Too Computer To Understand Right Now, people tend to use ReLU. ↩
Apparently even recurrent neural networks (RNNs) are “loop unrolled” meaning they copy and paste the structure in the IR instead of having an actual looping structure. ↩
Kind of. This is an oversimplification of Python semantics. If you want to learn more, check out Brett Cannon’s excellent blog post. ↩
Another kind of loss function is Cross-Entropy Loss, which is
best for (multi-class) classification problems. Adding Cross-Entropy Loss
required supporting other fundamental operations on Value and in the
compiler. ↩
There is also forward mode automatic differentiation but I don’t know much about it and haven’t seen it used in my limited search. ↩
Side note, I have never seen navigation in a PDF like that. It’s so neat. ↩
Daniel Lemire has a great blog post about the myth that performance problems are largely in a few concentrated hotspots. ↩
I initially wanted to write the whole pipeline down to machine code by hand. It would still be pretty small, all things considered, but then I would have to do register allocation. Decided to avoid that for now. ↩
This makes it SSA form by definition! ↩
I think it would be longer, anyway. With our current data and
grad array design, we might have to special-case storage for the input
data in the compiler—read from a different global variable or something
like that. If you use the Python buffer C-API it might not be so bad,
actually. Maybe I’ll leave it as an exercise for the reader. ↩