In the last post, we added basic autograd to our library, including things like nodes, thin tensor handles, graph building functions, and a bunch of helper functions. In this post, we’ll use the framework we just created, expanding functionality to work towards a trainable MLP using stochastic gradient descent (SGD).

This post will focus on the steps we took to finish our library and how we decided on them. At this point, the codebase has reached a level of complexity that makes it prohibitively long to describe every individual change to the code, so we’re going to focus on what was added or changed from a conceptual basis instead, glossing over much of the exact code changes. As always, the code, including commit history, is available on GitHub. This post covers commits 2ecb21d-65db26f.

After the last post, we have a functional but extremely limited autograd engine. Thinking about our goal of being able to train an MLP, our next steps should be to expand our autograd functionality to all the operations we missed last time. After that, we can add more autograd and SGD support functions, add SGD, and finally build an MNIST test network. While doing this, we’ll want to be careful that we don’t let the codebase become more complex than needed, and keep adding Python bindings to ensure the codebase works for our scoped purpose of a C++ CUDA library that works in Python.

Step 1: Building out autograd

At this step, we’ll add some key autograd functions and build out missing ._backward() functions. Starting with missing functions, we’ll add:

  • Unbroadcasting
    • This is the backward function for broadcasting. It’s basically a row- or column-wise sum. There’s a more detailed walkthrough in the appendix.
    • We also added reshape to support this.
  • Transpose
    • Transpose is used across a wide number of machine learning and linear algebra functions; it’s a miracle we’ve gotten this far without it. Now we’ll need it for a bunch of operations, but particularly the backward of matmul where the chain rule gives us: gradient W = AT*G.
  • ReLU, Softmax, Cross-Entropy loss
    • These are the functions we need to transform network outputs into a useful measure of loss. They are all common machine learning support functions, and we’ll gloss over their inner workings here, as we’ve gone in depth in previous posts.
  • Missing backward functions
    • We didn’t originally add backward functions for mean, matmul, and some other minor functions. Now that we have transpose and unbroadcasting, we can easily add the missing backwards behaviours.
  • More support functions
    • zeroGrad:
      • This one is easy to forget but critical for the training to work over multiple iterations.
    • detach:
      • Creates a copy of a tensor without grad on.
    • accumulateGrad
      • This allows us to accumulate the gradient over multiple passes.

Step 2: Implementing stochastic gradient descent

Now that we’ve worked through all the supporting functionality, we can implement SGD. It should be pretty straightforward:

  • SgdKernel and wrapper
    • While it would be possible to create an SGD loop at a higher level, we can make things far more efficient by writing a CUDA kernel for it, passing the kernel learnable parameters and a learning rate.
  • SGD Tests
    • While we do tests for every change, this step merits a thorough test set, as the next step is setting up training for a real MNIST model, at which point we lose some intuitive visibility into what’s going on. For this purpose, I created a new Python test script: training_test.py.

Step 3: Train MNIST

This is it. The final step to reach code version 1.0. While we’ll do more in the future to add new features and benchmark against NumPy and PyTorch, once we have a model successfully training using our handwritten CUDA kernels, the project will be complete. Now that all of our framework has been built out, we should be able to build an MLP with just a Python script. Since I’ve built them before from scratch, I’ll let a coding agent do the heavy lifting for this script. We’ll be careful to engineer our prompt to ensure it gives us a script that fits our requirements.

  • MNIST script
    • loads MNIST
      • This example uses a cached MNIST from the local machine to keep things simple.
    • Create settings
      • Hidden layer size, batch size, learning rate, epochs, etc.
    • Create the MLP
      • Layers, weights and biases, forward function, etc.
    • Create a testing function
      • This tests the network’s performance on a separate test dataset
    • Create the main training function/loop

With all that done, we can run the main script and see if all this work paid off. We should be pretty confident, because we tested every added function very thoroughly, but we can’t be 100% sure until we run the training. We’re also going to be looking closely at the speed. In the past, MNIST MLPs running unoptimized on the CPU have taken about five minutes to train. Let’s see how our GPU kernels do:

C:\...\minitensor> py mlp_test.py
train: (60000, 784), test: (10000, 784)
before training: test accuracy 9.87% (about 10% is chance)
epoch 1: avg loss 0.3966, test accuracy 93.25%, 0.2s
epoch 2: avg loss 0.2142, test accuracy 94.75%, 0.2s
epoch 3: avg loss 0.1666, test accuracy 95.88%, 0.2s
...
epoch 20: avg loss 0.0334, test accuracy 97.86%, 0.3s

All in all, this shows great success. A test accuracy of 93.25% means the network was pretty well trained in a single epoch, and in 0.2s. This is a massive speedup compared to past iterations. I’ll post a benchmark against PyTorch and NumPy in the future, but I can spoil it now: Our tensor library is competitive with both. Once we add tensor buffering and a couple other tweaks, we’ll see even more speed improvements.

Ending Notes:

If you look at the commits this post covers, you’ll see that there were a lot of code changes behind the scenes. Most of them fall into three categories:

  • Refinements and additions to Python bindings to increase usability
    • It’s easy to look at these adds as trivial, and they are in general very easy, but the increase in usability to the Python user is huge.
  • Small functions and operations to add functionality.
    • These were not worth giving time to in the main write-up, but were useful additions nonetheless. Things like Max, Min, Exp, Log, block reduce, etc.
  • A major refactor to break up the code
    • This was a lot of work behind the scenes, but doesn’t fit in the main narrative. While implementing SGD, I realized that the main code file was getting so long I spent more time looking for code locations than actually working. To get past this problem, and as good practice to make the library more modular and better organized, I broke the C++ code into six files, mostly breaking up tensor.cu as it was close to 1000 lines. I could have easily used a coding agent to do this task, but I wanted to do it myself for the learning experience and to ensure I continued to know how the library works holistically.

Appendix:

Unbroadcasting:

First up: Unbroadcasting. Since our networks sometimes use broadcasting in tensors with grad, we need to figure out how the gradient moves backward through broadcasted operations and implement it mathematically. Since broadcasting is the function of taking a row or column and distributing it across a given matrix, unbroadcasting would be taking a given matrix and somehow representing it as a single column or row. That sounds like a summing operation, and it is, with the added twist that we’re being careful to sum individual rows or columns into a given location inside the broadcasted vector.

We’ll also add a reshape function to support unbroadcasting. This is a simple function that creates a new tensorImpl which is linked to the same data but a different shape than its source tensor. Remember, this is possible because the data of each tensor is just a contiguous block in memory; it can be split into any shape that divides the data up cleanly.

Posted in

Leave a Reply