Manage comments

  • Building a C++ to Python Tensor Library: Adding SGD and training an MLP

    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.

  • Building a C++ to Python Tensor Library: Adding Autograd

    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.

  • Building a Tensor Library: Python That Compiles to Optimized C++

    Now that we’ve built a Tensor class that runs on the GPU in C++, we can go ahead and build out the connection to Python. This is a good time to tackle the Python bindings, because the C++ code is built out enough that the core is unlikely to change dramatically. We want to build our Python bindings as soon as possible, because it will make testing further incremental improvements much easier. Python is both easier to write and read, and we can compare our framework with the many ML tools built for Python, specifically NumPy and PyTorch. Side note: NumPy isn’t technically an ML tool, but is probably the best linear algebra code framework in existence, so it’s definitely something we want to be able to work with and compare against.

    What is nanobind?

    A bit of research shows that not only is it possible to build C++ code that can be used by Python; there are even a number of tools to make the process easier. Options include ctypes(built into Python) for using pure C code, Cython, which is a Python-like language that compiles to C and can use C++ code, and then pybind11 and Nanobind, which are both libraries that let you describe bindings in a C++ file and then call your C++ code as a library in Python. Out of those options, Nanobind is the clear winner for our use case: we can write our functions in pure, speed-optimized C++, write our binds in a single simple C++ sidecar, and then call our code from pure Python as a library, including tooltips and docstrings for IDE autocomplete and suggestions. It will turn out that getting this all working for our use case gets a bit more convoluted than just a couple of lines of bindings, but it is well worth it to have C++ speed in Python syntax.

    Before we get into the practical execution of implementing Nanobind, let’s take a look at how it actually works. To understand what Nanobind does, we need to understand a bit about how C++ and Python actually work at the low level. When code is run, it needs to get translated from the human-readable code that humans write to instructions for a processor that only uses a dozen or so operations on binary bits. C++ and Python do this translation differently.

    C++

    C++, as an older language, does things more “conventionally”: Your .cpp code file is given to a compiler, which looks at the file both as a whole and line by line, and replaces human text and function calls with the relevant machine code. More complex functions are broken down into tiny individual steps, often using a library as a guide for what steps make up a function, and the whole file is optimized by removing anything unneeded and a bunch of other tricks that modern C++ compilers know to increase speed.
    Once finished, the compiler exports the compiled machine code as an .exe or similar: this is a file that can be run directly as a process on the CPU. It can then be run from the command line without an interpreter or any helper: >.\tensor_test.exe

    Python

    If C++ is the conventional way of doing things, Python is the new kid on the block. Python scripts generally cannot be compiled into executable code, and in general are not compiled ahead of time. You may have noticed there is only one step to running Python code: rather than calling a compiler and then executing the compiled file, you simply call something like: > python your_file.py. This is because that single call launches both the compiler and execution in the same process, and because Python is never compiled to machine code. Python does have a compiler, but it is compiled into an intermediary, called bytecode, which is then run by an interpreter, which translates bytecode into machine code instructions. Python’s compiler and interpreter both run within the Python process: When a user calls python from their command line(something like py, python, python3, etc.) the system looks in its PATH for python.exe, which then, in turn, launches something like python3xx.dll. This .dll file contains the interpreter, compiler, and a bunch of other stuff needed for runtime.

    There are a number of advantages and disadvantages to both the above methods, but the ones we’re interested in are that Python is much slower for many operations, while being much easier to work with as a language. With that in mind, Python doesn’t always compile things into bytecode, because the Python interpreter can call/run machine code as well: Its whole job is to translate bytecode into machine code, so if something is already written as machine code, it simply needs to pass on the appropriate arguments(if there are any) and optionally wait while the machine code runs. Nanobind handles translating arguments into the appropriate C type, and then compiled C++ functions can run directly as machine code. Knowing that the Python interpreter can call machine code directly is something of a game changer. It means that as long as any arguments are translated correctly, pretty much anything can be run at full speed from Python. Pure C++ programs will still be slightly faster, for many reasons, but for things where the execution time is dominated by a particular operation(s), Python can be just as fast if those operations are run as compiled machine code. This also means we can run things that Python has no access to, like GPU machine code, through the same interface.
    The rest of this guide will get into the nitty-gritty of how exactly to implement nanobind, as it is fairly involved for someone new to C++, but the core understanding of how it works is the best takeaway from this whole process.

    Implementing a Python-exposed C++ library

    In order to use Nanobind, we’ll need to install it, probably through pip, although there are other ways. We will also want to make sure we know where it has been installed, as we will need to direct the C++ compiler to it.

    python -m pip install nanobind

    Note: Nanobind’s author, Wenzel Jakob, has posted a comprehensive guide to it that is very useful. I strongly suggest taking some time to read through it if you are using or thinking of using nanobind.

    We will also need to install CMake: Until now, we’ve been relying on the Visual Studio compiler, but we will now need to take manual control of the compiler, and nanobind is built to work flawlessly with CMake. CMake is pretty much the standard for compiling C++ code, especially for more complex and larger libraries of multiple files.

    To compile our code, we’ll interface with CMake through the command line and through a “CMakeLists.txt” file. The CMakeLists file will tell CMake what we’re making, what dependencies we have, and where to look for them. It’s also how we set up nanobind’s operation.

    cmake_minimum_required(VERSION 3.23)
    project(minitensor LANGUAGES CXX CUDA)
    set(CMAKE_CXX_STANDARD 17)
    set(CMAKE_CUDA_STANDARD 17)
    set(CMAKE_POSITION_INDEPENDENT_CODE ON) # required to link a static lib into a Python module
    set(CMAKE_CUDA_ARCHITECTURES 89) # compile for the GPU in this machine
    if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE)
    set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
    endif()
    find_package(Python COMPONENTS Interpreter Development.Module REQUIRED)
    find_package(CUDAToolkit REQUIRED)
    execute_process(
    COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
    OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT)
    find_package(nanobind CONFIG REQUIRED)
    add_library(tensor_core STATIC tensor.cu)
    target_link_libraries(tensor_core PUBLIC CUDA::cudart)
    target_include_directories(tensor_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
    nanobind_add_module(minitensor bindings.cpp)
    target_link_libraries(minitensor PRIVATE tensor_core)
    set_target_properties(minitensor PROPERTIES LIBRARY_OUTPUT_DIRECTORY_RELEASE ${CMAKE_SOURCE_DIR})
    add_executable(test_main tensor_test_main.cpp)
    target_link_libraries(test_main PRIVATE tensor_core)

    We’ll gloss over much of this as it is mostly boilerplate, but there are a couple of important things in the CMakeLists file:

    project(minitensor LANGUAGES CXX CUDA)
    set(CMAKE_CXX_STANDARD 17)
    set(CMAKE_CUDA_STANDARD 17)
    set(CMAKE_CUDA_ARCHITECTURES 89)

    We need to make sure CMake knows we’re compiling CUDA code, as it is technically a different language. We also need to specify which C++ standard to compile our CUDA code with, and what GPU architecture we’re on. The line: “set(CMAKE_CUDA_ARCHITECTURES 89)” would be different for different machines. This also means that, as we’re building it now, the library will have to be compiled for every different computer it runs on. We’ll likely come back and make it generic in the future, but this will be enough to get us started. Next, we need to start adding nanobind:

    execute_process(
    COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
    OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT)
    find_package(nanobind CONFIG REQUIRED)

    This block detects where nanobind is installed and imports it to CMake. I recommend having it installed as part of your local venv, as that makes it easy to find. Finally, we need to make sure CMake/nanobind knows where our bindings file is:

    nanobind_add_module(minitensor bindings.cpp)

    We’ll go more in depth on the bindings file in a moment, but it’s where all the actual custom code that describes how to call/expose the C++ functions in Python lives.

    Once we have all we need in CMakeLists, we can build our code using:

    Remove-Item -Recurse -Force build
    cmake -S . -B build
    cmake --build build --config Release

    These three PowerShell lines: remove any previous build configurations, create a build configuration using CMakeLists, and build the configuration for release, respectively. We’ve also called our build/configuration build, which is standard syntax but can be a bit confusing. Once executed, these commands will create C++ executables(as build/test_main.exe) as well as the interface for using the C++ classes and functions within Python(as a .pyd file in the main directory).

    The real magic will happen in bindings.cpp. This file contains the connectors that allow us to use our compiled C++ code from Python. We will need to write a binding in this file for any part of the C++ library we want to expose. We’ll start with the Tensor class and some class methods:

    NB_MODULE(minitensor, m){
    nb::class_<Tensor>(m, "Tensor")
    .def_static("from_list", &Tensor::fromHost)
    .def_static("from_numpy", [](CpuArray arr) {
    std::vector<int> shape;
    for (size_t i = 0; i < arr.ndim(); i++) shape.push_back((int)arr.shape(i));
    return Tensor::fromHostData(shape, arr.data());
    })
    .def("to_list", &Tensor::toHost)
    .def("to_numpy", [](const Tensor& t) {
    auto host = std::make_unique<float[]>(t.numel());
    t.copyToHost(host.get());
    std::vector<size_t> shape(t.shape().begin(), t.shape().end());
    float* raw = host.release();
    nb::capsule owner(raw, [](void* p) noexcept { delete[] static_cast<float*>(p); });
    return nb::ndarray<nb::numpy, float>(raw, shape.size(), shape.data(), owner);
    })

    Although they have strange syntax, Nanobind bindings are fairly straightforward. Now that we have the class, we can also add operator operations, for example:

        .def(nb::self + nb::self)
        .def(nb::self * nb::self)
        .def("__mul__",     [](const Tensor& a, float s) { return a * Tensor::scalar(s); })
        .def("__rmul__",    [](const Tensor& a, float s) { return Tensor::scalar(s) * a; })
        .def("__add__",     [](const Tensor& a, float s) { return a + Tensor::scalar(s); })
        .def("__radd__",    [](const Tensor& a, float s) { return Tensor::scalar(s) + a; })

    This adds addition and multiplication operations, and we also add the operator overloads for Python so that something like c = a + b works both when a and b are tensors and when one is a scalar. We can also add a wrpr function for when tensors are printed:

        .def("__repr__", [](const Tensor& t) {
            return "Tensor(shape=" + shapeToString(t.shape()) + ")";
        });

    If we build out the whole library like this, it will work. But it lacks some critical functions, specifically, tooltips and type stubs for Pylance. These are what give you suggestions, descriptions, and red error underlines in an IDE when using the library. While our library would technically work without them, they are essential for any library to be practically useful. We can add descriptions in the bindings file, and we’ll make a small addition to CMakeLists to also produce type stubs. Let’s start with the descriptions of what we’ve already bound:

    NB_MODULE(minitensor, m){
    m.doc() = "Minimal float32 tensor library backed by CUDA.";
    nb::class_<Tensor>(m, "Tensor", "A float32 tensor stored on the GPU.")
    .def_static("from_list", &Tensor::fromHost, nb::arg("shape"), nb::arg("values"),
    "Create a GPU tensor from a shape and a flat list of row-major values.")
    .def_static("from_numpy", [](CpuArray arr) {
    std::vector<int> shape;
    for (size_t i = 0; i < arr.ndim(); i++) shape.push_back((int)arr.shape(i));
    return Tensor::fromHostData(shape, arr.data());
    }, nb::arg("array"), "Create a GPU tensor by copying a C-contiguous float32 NumPy array.")
    .def("to_list", &Tensor::toHost, "Copy the tensor to the CPU as a flat list of row-major values.")
    .def("to_numpy", [](const Tensor& t) {
    auto host = std::make_unique<float[]>(t.numel());
    t.copyToHost(host.get());
    std::vector<size_t> shape(t.shape().begin(), t.shape().end());
    float* raw = host.release();
    nb::capsule owner(raw, [](void* p) noexcept { delete[] static_cast<float*>(p); });
    return nb::ndarray<nb::numpy, float>(raw, shape.size(), shape.data(), owner);
    }, "Copy the tensor to the CPU as a float32 NumPy array with the same shape.")

    And for our operator functions:

        .def(nb::self + nb::self, nb::arg("other"), "Elementwise add (2D broadcasting supported).")
        .def(nb::self * nb::self, nb::arg("other"), "Elementwise multiply (2D broadcasting supported).")
        .def("__mul__",     [](const Tensor& a, float s) { return a * Tensor::scalar(s); },
            nb::arg("scalar"), "Multiply every element by a scalar.")
        .def("__rmul__",    [](const Tensor& a, float s) { return Tensor::scalar(s) * a; },
            nb::arg("scalar"), "Multiply every element by a scalar.")
        .def("__add__",     [](const Tensor& a, float s) { return a + Tensor::scalar(s); },
            nb::arg("scalar"), "Add a scalar to every element.")
        .def("__radd__",    [](const Tensor& a, float s) { return Tensor::scalar(s) + a; },
            nb::arg("scalar"), "Add a scalar to every element.")

    We’ll now need to tell CMake to create a type stub file:

    nanobind_add_stub(
    minitensor_stub
    MODULE minitensor
    OUTPUT ${CMAKE_SOURCE_DIR}/minitensor.pyi
    PYTHON_PATH $<TARGET_FILE_DIR:minitensor>
    DEPENDS minitensor
    )

    With the above additions, we should have the full framework of our Python bindings. I will save the full bindings file code, with bindings for all our functions, for GitHub, but nothing changes from the pattern we’ve established. The only thing remaining to do is verify that our library works in Python as intended. For testing in Python, we’ll be using PyTest:

    import operator
    import numpy as np
    import pytest
    import minitensor as mt
    rng = np.random.default_rng(0)
    SHAPES = [((2, 3), (2, 3)), ((2, 3), (3,)), ((2, 3), (2, 1)),
    ((2, 1), (1, 3)), ((3,), ()), ((4, 5), (1, 1))]
    OPS = [operator.add, operator.sub, operator.mul, operator.truediv]
    @pytest.mark.parametrize("shape_a,shape_b", SHAPES)
    @pytest.mark.parametrize("op", OPS)
    def test_binary_ops(shape_a, shape_b, op):
    a = np.asarray(rng.standard_normal(shape_a, dtype=np.float32))
    b = np.asarray(rng.standard_normal(shape_b, dtype=np.float32)) + 3.0 # stay away from 0 for division
    expected = op(a, b)
    result = op(mt.Tensor.from_numpy(a), mt.Tensor.from_numpy(b.astype(np.float32))).to_numpy()
    assert result.shape == expected.shape
    np.testing.assert_allclose(result, expected, rtol=1e-6)

    When we call it from the command line, Pytest will automatically run a parametrized test set and let us know if our library differs from native Python/NumPy results:

    >pytest py_test.py

    py_test.py …………………… [ 100%]

    ======================= 24 passed in 0.15s =======================

    With our tests passing, we now finally have a Python library that is running C++ behind the scenes! Knowing how to do this is a huge tool in our skill set: Being able to write Python code that runs with C++ speed is the best of both worlds and will be even more helpful on future machine learning projects, as many ML tool-sets are built as this Python/C++ hybrid, and we will have more flexibility to add and modify modules to existing tool-sets.

  • Building a Tensor Class: automatic memory management, generic elementwise kernels, broadcasting

    In the last post, we built a tensor calculator using CUDA and learned a lot about memory, GPU architecture, tensors, pointers, and CUDA and NVIDIA GPUs, but the calculator we built is very clunky: We have to allocate memory to it manually and call each kernel explicitly to do basic math – not ideal. So in this post we’ll fix that with a tensor class whose purpose is to make it easy for us to use our CUDA kernels: We should be able to just give it some data and an expression on the host side and have it handle moving the data to device, parsing the math expression, running the calculation fully within GPU memory, and handing the data back across to CPU memory when done.

    Quick side note: If you’re anything like me, you may have been confused by the very word “tensor”. Definitions vary wildly, both between different fields, including math and physics, and even within machine learning itself. In my case, this has even led to some fairly confused arguments with physicists stemming from different definitions of what seems like the same very specific word. Lucky for us, machine learning has the most digestible definition: A tensor is simply an n-dimensional array, often with more dimensions than can be easily visualised, such as 5-dimensional arrays. There is, however, a hidden caveat: A tensor in machine learning also often includes some concept of residing on a GPU or other parallel-optimized hardware, and is often not just a simple value matrix, but a class which has expanded operations available to it, specifically things like topology mapping, and gradients/automatic differentiation.

    With the possible exception of when we add autograd, this will be the biggest jump in code complexity in our project, but it also comes with a great increase in functionality. Let’s get to it.

    First, let’s think conceptually about how this can work. We have a very versatile host-side CPU and memory, but it’s slow for large data. The GPU is fairly primitive by comparison, and is actually slower in raw computational speed, but can run simple instructions in massive parallel, and has comparatively much more available fast memory for its threads.

    With that in mind, we’ll set up a class that resides on CPU, but can move arrays back and forth from the GPU, and can create and delete them on the GPU as well. Similarly, our kernel launcher functions will be on CPU as well. The only things that touch GPU directly will be the class, handling moving data there, and the kernels, which run entirely within a CUDA <<<launch>>>. The way I like to think about this is that the CPU side class works as a sort of puppetmaster, pushing around and making things happen on the GPU, but only through the strings of pointers.

    Ok, so what should our class look like? Assuming we still have our code from last time, including the error-checking wrapper, we’ll create a class:

    // CPU side tensor class
    class Tensor{
    public:
    // Allocate an uninitialized tensor on the GPU
    explicit Tensor(const std::vector<int>& shape) : shape_(shape) {
    float* ptr = nullptr;
    cudaCheck(cudaMalloc(&ptr, numel() * sizeof(float)), "cudaMalloc");
    // shared_ptr frees the GPU memory when the last Tensor using it is destroyed
    data_ = std::shared_ptr<float>(ptr, [](float* p) { cudaFree(p); });
    }
    // copy a tensor from host(CPU)
    static Tensor fromHost(const std::vector<int>& shape, const std::vector<float>& values){
    Tensor t(shape);
    if ((int)values.size() != t.numel()) {
    throw std::runtime_error("fromHost: number of values doesn't match shape");
    }
    cudaCheck(cudaMemcpy(t.data(), values.data(), t.numel() * sizeof(float),
    cudaMemcpyHostToDevice), "cudaMemcpy H2D");
    return t;
    }
    // copy data out of GPU back to host
    std::vector<float> toHost() const {
    std::vector<float> values(numel());
    cudaCheck(cudaMemcpy(values.data(), data(), numel() * sizeof(float),
    cudaMemcpyDeviceToHost), "cudaMemcpy D2H");
    return values;
    }
    float* data() const { return data_.get(); }
    const std::vector<int>& shape() const { return shape_; }
    int numel() const {
    int n = 1;
    for (int d : shape_) n *= d;
    return n;
    }
    private:
    std::shared_ptr<float> data_;
    std::vector<int> shape_;
    };

    This looks like a lot just to make a basic class, which, if you’re coming from Python, might look intimidating, but much of it is just C++ housekeeping. The core changes happen in the GPU initializer:

    // Allocate an uninitialized tensor on the GPU
    explicit Tensor(const std::vector<int>& shape) : shape_(shape) {
    float* ptr = nullptr;
    cudaCheck(cudaMalloc(&ptr, numel() * sizeof(float)), "cudaMalloc");
    // shared_ptr frees the GPU memory when the last Tensor using it is destroyed
    data_ = std::shared_ptr<float>(ptr, [](float* p) { cudaFree(p); });
    }

    This basically says that when someone declares a tensor with our class(through Tensor()), it will take a shape -we need the shape to know how much area to allocate on the GPU- and allocate that memory on the GPU. The nullptr is an empty pointer on the CPU that cudaMalloc will fill with the address of the data array. We’ll then handle the data through our internal data_ shared pointer, which provides automatic memory management: when the last reference to data_ goes away, C++’s RAII system will automatically free the memory it owns. However, the data on the GPU isn’t accessible by normal C++ functions, so we can specify how we free the data with { cudaFree(p); }. This brings up an important note about our ptr from earlier: CUDA writes the address of the GPU-side data array to that pointer, but CPU and GPU have separate memory spaces, so the memory address stored by ptr can only be used on the GPU, by things like cudaMemcpy() and <<<kernel launches>>>: if we call it on the CPU, we’ll get some error, probably a segmentation fault, as the address it points to on the CPU would be some random location, if it exists at all.

    The other two methods in the class are just handling copying tensor arrays back and forth from host to device with cudaMemcpy:

    // copy a tensor from host(CPU)
    static Tensor fromHost(const std::vector<int>& shape, const std::vector<float>& values){
    Tensor t(shape);
    if ((int)values.size() != t.numel()) {
    throw std::runtime_error("fromHost: number of values doesn't match shape");
    }
    cudaCheck(cudaMemcpy(t.data(), values.data(), t.numel() * sizeof(float),
    cudaMemcpyHostToDevice), "cudaMemcpy H2D");
    return t;
    }
    // copy data out of GPU back to host
    std::vector<float> toHost() const {
    std::vector<float> values(numel());
    cudaCheck(cudaMemcpy(values.data(), data(), numel() * sizeof(float),
    cudaMemcpyDeviceToHost), "cudaMemcpy D2H");
    return values;
    }

    These methods use the built-in structure of the class. The formHost method uses the Tensor initializer when copying data from the CPU to the GPU so that all CUDA memory allocation goes through that managed constructor.

    Generic Kernels

    We want our calculator to be able to do more than just one or two operations, but writing each kernel explicitly would take a lot of time and bloat the codebase. To save time and write more concise code, we can take advantage of C++’s templates, where a single function(or, hint for later, operator) can be written generically, and the compiler generates the right version based on the type of arguments passed along. This allows us to write a generic kernel that takes two tensors, performs an elementwise operation on them, and then returns the result into an output tensor:

    template <typename Op>
    __global__ void binaryKernel(const float* a, const float* b, float* out, int n, Op op) {
    int i = threadIdx.x + blockDim.x * blockIdx.x;
    if (i < n) out[i] = op(a[i], b[i]);
    }

    We can then define several operations for this kernel in a single line(s):

    struct AddOp { __device__ float operator()(float x, float y) const { return x + y; } };
    struct SubOp { __device__ float operator()(float x, float y) const { return x - y; } };
    struct MulOp { __device__ float operator()(float x, float y) const { return x * y; } };
    struct DivOp { __device__ float operator()(float x, float y) const { return x / y; } };

    With this, op(a[i], b[i]) is replaced with a[i] + b[i] or some other operation at compile time.

    We can do the same for a unary kernel like negation or taking to a power:

    //unary operations
    struct NegOp { __device__ float operator()(float x) const { return x * (-1); } };
    struct PowOp {
    float p;
    __device__ float operator()(float x) const { return powf(x, p); }
    };
    //unary kernel
    template <typename Op>
    __global__ void unaryKernel(const float* a, float* out, int n, Op op) {
    int i = threadIdx.x + blockDim.x * blockIdx.x;
    if (i < n) out[i] = op(a[i]);
    }

    Now we have the kernels written -for the most part- and it was remarkably simple! We have no way to call our kernels yet, so we’ll need to create wrappers to handle the kernel launch. These will sit on the host side, handle device memory pointers, create output tensors, and launch the kernels. We’ll also include some error handling code here so we have less chance of having an error occur silently within the GPU:

    template <typename Op>
    Tensor binaryOp(const Tensor& a, const Tensor& b, Op op) {
    if (a.shape() != b.shape()) return broadcastOp(a, b, op);
    //Don't worry about broadcast op yet; we'll cover that later.
    Tensor out(a.shape());
    int n = out.numel(), threads = 256, blocks = (n + threads - 1) / threads;
    binaryKernel<<<blocks, threads>>>(a.data(), b.data(), out.data(), n, op);
    cudaCheck(cudaGetLastError(), "kernel launch");
    return out;
    }

    Similar to how we used templates in our kernel definitions, we can now define the overload behavior for math symbol operations with Tensors:

    Tensor operator+(const Tensor& a, const Tensor& b) { return binaryOp(a, b, AddOp{}); }
    Tensor operator-(const Tensor& a, const Tensor& b) { return binaryOp(a, b, SubOp{}); }
    Tensor operator*(const Tensor& a, const Tensor& b) { return binaryOp(a, b, MulOp{}); }
    Tensor operator/(const Tensor& a, const Tensor& b) { return binaryOp(a, b, DivOp{}); }

    This will give our calculator much more ease of use; rather than saying add(a, b), we can say a + b. This makes it very simple to implement more complex operations like:

    Tensor out = (((a + b) * c) + d * -g) -f;

    Rather than this, which is both hard to follow and takes much more time to translate from normal equation format:

    Tensor out = sub(add(mult(add(a, b), c), mult(d, neg(g))), f);

    This is similar to the way Karpathy’s micrograd works with Python operator overloading through its double underscore methods like __add__ and __call__. Now that we’ve built a basic class, we can create and manipulate tensors with just a couple lines of code:

    std::vector<int> shape = {2,3};
    Tensor a = Tensor::fromHost(shape, {1.0f, 2.0f, 3.0f,
    4.0f, 5.0f, 6.0f});
    Tensor b = Tensor::fromHost(shape, {10.0f, 10.0f, 10.0f,
    10.0f, 10.0f, 10.0f});
    Tensor c = Tensor::fromHost(shape, {0.5f, 1.0f, 1.5f,
    2.0f, 2.5f, 3.0f});
    Tensor out = a + b * c;
    printTensor("a + b * c", out);

    With the new class, what would’ve taken pages of code can be done much more easily, and without thinking about memory at all: memory is automatically allocated at tensor declaration, and automatically freed after the function finishes. This automatic memory management will be critical when we’re working with complex neural networks where there are many hidden layers and operations.

    Shape and handling 2D Tensors

    You may have noticed we’ve silently added shape in the class declaration, but if we look closely, our data arrays are still declared as a vector. This is indicative of how n-dimensional arrays work in computer memory in general: there is no such thing as an n-dimensional or even 2D array in memory; all data stored in memory is a linear block of memory of a given size, and we can add higher dimensions by keeping track of our location and indexing. For this project, we want to build out functionality for at least 2D Tensors. To do this, on top of adding shape in the Tensor class, we’ll need to add shape checking to some kernels and add broadcasting functionality. Broadcasting will be useful anytime we need to add a scalar to an array, such as adding a bias to an array, or if we want to broadcast a single row or column into a larger array. This is a simple concept in 2D:

    We will need to apply this simple 2D concept within a 1D memory block, so it will look somewhat more complicated because we need to index rows and columns into a 1D vector. Our strides here are just allowing us to step through the 1D array as if it were 2D:

    // 2D broadcasting kernel
    template <typename Op>
    __global__ void broadcastKernel2D(const float* a, int aStrideR, int aStrideC,
    const float* b, int bStrideR, int bStrideC,
    float* out, int rows, int cols, Op op) {
    int i = threadIdx.x + blockDim.x * blockIdx.x;
    if (i < rows * cols) {
    int r = i / cols, c = i % cols;
    out[i] = op(a[r * aStrideR + c * aStrideC], b[r * bStrideR + c * bStrideC]);
    }
    }

    We’ll also add a wrapper and function to make shapes 2D:

    // Pad a shape to 2D with leading 1s: {10} -> {1, 10}, {} -> {1, 1}
    std::vector<int> to2D(const std::vector<int>& shape) {
    if (shape.size() > 2) throw std::runtime_error("broadcast: only up to 2D supported");
    std::vector<int> s = shape;
    while (s.size() < 2) s.insert(s.begin(), 1);
    return s;
    }
    //2D broadcasting wrapper
    template <typename Op>
    Tensor broadcastOp(const Tensor& a, const Tensor& b, Op op){
    std::vector<int> as = to2D(a.shape()), bs = to2D(b.shape());
    std::vector<int> out2D(2);
    for (int d = 0; d < 2; d++) {
    if (as[d] == bs[d]) out2D[d] = as[d];
    else if (as[d] == 1) out2D[d] = bs[d];
    else if (bs[d] == 1) out2D[d] = as[d];
    else throw std::runtime_error("broadcast: incompatible shapes " +
    shapeToString(a.shape()) + " and " +
    shapeToString(b.shape()));
    }
    // Output keeps the larger of the two original ranks: (3) + (1) -> (3), not (1, 3)
    size_t maxRank = std::max(a.shape().size(), b.shape().size());
    Tensor out(std::vector<int>(out2D.end() - maxRank, out2D.end()));
    int aStrideR = (as[0] == 1) ? 0 : as[1], aStrideC = (as[1] == 1) ? 0 : 1;
    int bStrideR = (bs[0] == 1) ? 0 : bs[1], bStrideC = (bs[1] == 1) ? 0 : 1;
    int rows = out2D[0], cols = out2D[1], n = rows * cols;
    int threads = 256, blocks = (n + threads - 1) / threads;
    broadcastKernel2D<<<blocks, threads>>>(a.data(), aStrideR, aStrideC,
    b.data(), bStrideR, bStrideC,
    out.data(), rows, cols, op);
    cudaCheck(cudaGetLastError(), "broadcast kernel launch");
    return out;
    }

    With this, we can easily add scalars and manipulate matrices using a given row or column. This will be very useful when we go to implement ML models.

    Final thoughts:

    While this step was a significant jump in complexity, we’ve come out of it with a much more flexible and practical class which we can use for practical, real-world projects. While our functionality is still somewhat limited, we now have a class that we can easily add to and build on. In the next posts, we’ll extend this framework to work in Python through bindings using CMake and Nanobind. This will allow us easier testing through Python libraries like NumPy, PyTorch, and PyTest. Once that’s done, we’ll continue to build up core tensor and kernel functionality towards our goal of a functional machine learning framework.

  • Building a Tensor-Based Calculator with CUDA

    Come along with me in this post as we create a C++ CUDA tensor calculator! This is part of a larger project to recreate a high-performance neural network tool library: Starting from the ground level of writing tensor classes that execute on GPU hardware, and building to an eventual PyTorch-style library for building simple machine learning models in Python. In this post, we’re going to learn how computers handle memory, down to the hardware level, and then use that knowledge, along with CUDA resources and a bit of linear algebra knowledge, to build out a matrix calculator that runs on NVIDIA GPUs. This is essentially the core of tensor classes.

    What’s a Pointer, Really?

    If you’ve taken any classes on C programming, you’ve probably heard about pointers and had to learn about them on a surface level. Many people struggle with them when learning in school, partly because to understand the purpose of pointers, you must understand the deeper level of how memory works on hardware, which is often further than programming courses will go. We will touch on it here, but the subject of memory deserves its own post.

    In essence, pointers are simply a place in memory that stores the address of another place in memory. This is useful when we want a variable to persist past the function that declared it, or when we want to work directly with the information stored in a variable, rather than a copy. In most basic code, there is no reason to need either of those things. Where pointers become useful is with more complex code, particularly when you’re handling large objects: it’s much faster to handle just the 8-byte pointer than a 40MB array. Pointers also give us more explicit control of memory, which is critical for utilizing GPUs.

    What’s a GPU and why do we need it?

    Graphics Processing Units(GPU) were traditionally developed to handle the bulk repetitive tasks involved with playing video and calculating what needs to go in every pixel of a 3D render in a video game or other 3D software. While most of these tasks are quite simple, doing them for the 8 million or more pixels of a 4k display at 120Hz or more adds up to a huge number of calculations, something that a single CPU thread will struggle with. For many years, this problem was overcome by making faster CPU cores, but this eventually hit a limit, running into the unmoving walls of thermodynamics: Faster CPUs mean more heat, and eventually the heat generation outpaces cooling capacity, and the core will start to melt/burn itself. This is where GPUs come in. Because the tasks in graphics processing are often repetitions of the same equations, just with different input data, a processor chip that has thousands of threads all running the same instructions, at different memory addresses, can handle repetitive tasks in massive parallel, rather than serially. This little trick means GPUs can run parallelized tasks many orders of magnitude faster than a CPU.

    From NVIDIA's cuda programming guide:  an example of CPU and GPU architecture.
    From NVIDIA’s CUDA programming guide: an example of CPU and GPU architecture.

    Limitations:

    With a GPU’s obvious advantage in parallel processing, you might wonder why they’re not used for everything, and there are a couple of reasons: many tasks aren’t easily parallelizable, and it is not simple to write code that runs directly on GPU. A large part of the difficulty of writing code for processing on GPU comes down to memory management. While a CPU or GPU can access its memory registers and caches very quickly, and its DRAM or VRAM less quickly, transferring data across the bridge from DRAM/CPU/Host to VRAM/GPU/device is much, much slower. For this reason, we want our high-level logic to run on CPU, while the actual memory being worked on should reside on the GPU. Also, special care should be taken in the algorithms which are computed on the GPU to ensure they are parallelizable and utilize the GPU’s onboard memory, including registers and caches, efficiently.

    With that out of the way, let’s set some practical goals for this project. While we’re going to build to a large and more capable library eventually, this checkpoint is going to be light on features, heavier on background learning. We want to lay a good base for future features, but keep things simple enough to learn in this early stage, so here are some requirements:

    Level 1:
    A basic calculator that runs on any CUDA GPU; it should be able to add, subtract, multiply, divide, do powers, negate, etc.

    Level 2:
    In addition to all of the features from level 1, level 2 should include features to make the code actually useful:
    1: A generalized tensor class that can handle memory allocation automatically.
    2: Ability to handle at least 2D Tensors, with basic broadcasting and stride dynamics, and a framework allowing for additional operations to be added later.

    With all that out of the way, let’s get into the implementation for level 1! I’ll go over significant things to learn, but leave out most of the line-by-line code. First, we’re gonna need to read up on the official CUDA programming in C++ doc; this is published by NVIDIA and is very approachable. To run things on the GPU we’re going to need to do three things:

    1. Build functions that can run parallel computations on the GPU(kernels)
    2. Learn how to allocate and free memory on the GPU
    3. Learn how to launch kernels to the GPU

    Additionally, we’ve got a couple of housekeeping steps:

    4. Include error checking and synchronization
    5. Figure out how to compile CUDA code

    1. Kernels:

    Kernels are pretty simple, but look very odd the first time you see them:

    //kernel definition example
    __global__ void vecAdd(float* a, float* b, float* out, int vectorLength)
    {
    int workIdx = threadIdx.x + blockDim.x * blockIdx.x;
    {
    out[workIdx] = a[workIdx] + b[workIdx];
    }
    }

    The kernel is declared just like a normal global function, with a couple of twists in the implementation: First, arguments are passed in as pointers, and this isn’t optional: since we don’t want to be passing large data arrays back and forth across the CPU-GPU bridge, we need to have the data loaded into GPU memory separately and simply pass the address(pointer) to the kernel. Second, rather than just adding a+b, which works for scalars, we’re adding a + b at the memory index of workIdx(work index). The work index keeps track of where in memory a specific computational thread should be looking for the memory it is working on. This brings up another aspect of good kernel programming: not only are the inputs pointers to your data, but the data itself should be a vector or continuous array in memory. If we’re just operating on scalars, that computational work should be done on the CPU.
    To further break down workIdx, on CUDA architecture computational threads are grouped into blocks, and then further into a grid. When it’s time to run, individual blocks are sent to a streaming multiprocessor(this is a physical thing) that will run multiple blocks of threads simultaneously. All that to say, workIdx is just indexing the 2D array created by a block’s index and a thread’s index within that block:

    int workIdx = threadIdx.x + blockDim.x * blockIdx.x;

    This is a common notation for memory indexing, but its components can be 3D as well for more complex operations.

    2. Allocating GPU memory:

    Now that we have a kernel done, let’s set up the memory it will operate on. This will require CUDA-specific calls from the cuda_runtime library:

    #include <cuda_runtime.h>
    const int n = 1<<20; // ~1 million elements
    const size_t bytes = n * sizeof(float);
    // Allocate and fill arrays in CPU memory
    float *h_a = (float *)malloc(bytes);
    float *h_b = (float *)malloc(bytes);
    float *h_c = (float *)malloc(bytes);
    float *d_a, *d_b, *d_c;
    cudaMalloc(&d_a, bytes);
    cudaMalloc(&d_b, bytes);
    cudaMalloc(&d_c, bytes);
    cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice);
    cudaMemcpy(d_b, h_b, bytes, cudaMemcpyHostToDevice);
    cudaMemcpy(d_c, h_c, bytes, cudaMemcpyHostToDevice);
    //do our calculation here
    cudaMemcpy(h_c, d_c, bytes, cudaMemcpyDeviceToHost);

    This code simply creates some very large vectors on the CPU, creates empty arrays of the same size on the GPU, copies the numbers to the GPU arrays, and then copies the result back after the calculations are done. This is all done through pointers, and in our final code will be wrapped in CUDA error handling calls, but we’ll get to that later. d_a and h_a stand for device(GPU) and host(CPU), respectively; this is standard notation for CUDA and other GPU calls.

    3. Launching kernels

    Now that we have kernel functions and the memory allocated for our work to go into, we can launch those kernels with the allocated memory and have them run our calculation:

    const int threadsPerBlock = 256;
    const int blocks = (n+ threadsPerBlock -1) / threadsPerBlock; //this rounds up
    vecAdd<<<blocks, threadsPerBlock>>>(d_a,d_b,d_c, n);

    Here we are specifying how we want to set the kernels up, in terms of number of threads per block and total number of blocks. NVIDIA GPUs are composed of a number of streaming multiprocessors(SM), which execute many threads in parallel, grouped into warps and further into thread blocks. Off of the SM, thread blocks are organized into a grid that SMs pull blocks from for processing. All of this can get pretty involved, but starting out we can generally set the block size to 256 and then calculate the number of blocks we need by comparing it to our variable size and rounding up:

    const int threadsPerBlock = 256;
    const int blocks = (n+ threadsPerBlock -1) / threadsPerBlock; //this rounds up

    Once we know our block size and the number we need, we can launch the kernel with NVIDIA’s triple chevron notation:

    vecAdd<<<blocks, threadsPerBlock>>>(d_a,d_b,d_c, n);

    And that’s it! We’ll continue to go over compiling CUDA code, error checking, and synchronizing the GPU and CPU, but the core code is done! CUDA requires a different way of thinking, but we can see that the simplest example is very approachable, and we can easily build from there.

    4. Error handling and GPU-CPU sync:

    The CUDA API returns an error code with every call. Normally, this return value will be cudaSuccess. To be sure everything is going as we want it, we will need to wrap every CUDA call with a simple error handling function, so that we don’t have silent failures on the CUDA side. This is necessary because where an error on the CPU side will stop things automatically in most cases, GPU errors can happen asynchronously and silently, causing further problems in later instructions and making it difficult to find the root cause. To ensure this doesn’t happen, we’ll wrap all our CUDA calls in a small error handler:

    #define CUDA_CHECK(call) \
    do { \
    cudaError_t err = (call); \
    if (err != cudaSuccess) { \
    fprintf(stderr, "CUDA error: %s (%s:%d)\n", \
    cudaGetErrorString(err), __FILE__, __LINE__); \
    exit(1); \
    } \
    } while (0)

    Next, we need to handle synchronization. Since the GPU is a separate processor, it runs asynchronously from the CPU, which means we need to make sure data transfers between the two are coordinated; specifically, we need to make sure the CPU side logic is not using data that hasn’t been calculated yet. There are a number of ways to handle syncing the CPU-GPU, with some much more advanced methods, but for our simple purpose we will just make it so that the CPU logic waits for the GPU to complete when it’s launched. After our kernel launch, we’ll add a sync call:

    cudaDeviceSynchronize();

    This forces the CPU-side execution to pause and wait for the GPU to finish. Once it’s done, we can copy our result back over to the host, and free the GPU memory:

    cudaMemcpy(h_c, d_c, bytes, cudaMemcpyDeviceToHost);
    CUDA_CHECK(cudaFree(d_a));
    CUDA_CHECK(cudaFree(d_b));
    CUDA_CHECK(cudaFree(d_c));

    We can add an error check for the actual operation; this is good practice to make sure we’re getting the expected result:

    // Verify on the CPU
    int errors = 0;
    for (int i = 0; i < n; i++) {
    if((h_a[i] + h_b[i]) != h_c[i] ){errors++;}
    }
    printf("Launched %d blocks x %d threads. Errors: %d\n",
    blocks, threadsPerBlock, errors);
    printf("Sample value = %.6f\n", h_c[3]);

    And that’s it! All the code is done; now we can tackle the compilation and running of the code, which can be more tricky than the code itself.

    5. Compiling CUDA code:

    While we write CUDA calls in C++, the GPU code actually gets compiled to something called ptx(Parallel Thread Execution), which a normal C++ compiler will not know how to generate. To generate ptx code, we will need to use the NVIDIA CUDA Compiler(nvcc), which piggybacks off the host C++ compiler to generate both CPU and GPU code in a single executable or library. nvcc is part of the CUDA toolkit, so to compile this little example program, we will need both a host C++ compiler and the CUDA toolkit set up and running. In my example, I just used the Visual Studio compiler I had on hand, but the specific setup on most machines will be slightly different:

    nvcc -ccbin “C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\VC\Tools\MSVC\14.44.35207\bin\Hostx64\x64” example.cu -o example.exe

    In future posts, we will end up using a custom CMake build as our needs get more complex, but for now, the built-in host compiler should work. We can now run and test our full program:

    PS C:\working_dir> .\example.exe
    Launched 4096 blocks x 256 threads. Errors: 0
    Sample value = 3.000000

    Finishing out the calculator functions

    Now that we’ve figured out all the individual steps, let’s add some simple kernels and test that the calculator works correctly:

    #include <cstdio>
    #include <cstdlib>
    #include <cuda_runtime.h>
    __global__ void vecAdd(float* a, float* b, float* out, int vectorLength)
    {
    int workIdx = threadIdx.x + blockDim.x * blockIdx.x;
    if(workIdx < vectorLength)
    {
    out[workIdx] = a[workIdx] + b[workIdx];
    }
    }
    __global__ void vecSub(float* a, float* b, float* out, int vectorLength)
    {
    int workIdx = threadIdx.x + blockDim.x * blockIdx.x;
    if(workIdx < vectorLength)
    {
    out[workIdx] = a[workIdx] - b[workIdx];
    }
    }
    __global__ void vecMult(float* a, float* b, float* out, int vectorLength)
    {
    int workIdx = threadIdx.x + blockDim.x * blockIdx.x;
    if(workIdx < vectorLength)
    {
    out[workIdx] = a[workIdx] * b[workIdx];
    }
    }
    __global__ void vecDivide(float* a, float* b, float* out, int vectorLength)
    {
    int workIdx = threadIdx.x + blockDim.x * blockIdx.x;
    if(workIdx < vectorLength)
    {
    out[workIdx] = a[workIdx] / b[workIdx]; // b == 0 gives inf
    }
    }
    __global__ void vecPow(float* a, float* b, float* out, int vectorLength)
    {
    int workIdx = threadIdx.x + blockDim.x * blockIdx.x;
    if(workIdx < vectorLength)
    {
    out[workIdx] = powf(a[workIdx], b[workIdx]);
    }
    }
    __global__ void vecExp(float* a, float* out, int vectorLength)
    {
    int workIdx = threadIdx.x + blockDim.x * blockIdx.x;
    if(workIdx < vectorLength)
    {
    out[workIdx] = expf(a[workIdx]);
    }
    }

    These kernels don’t cover every math operation possible but are enough to build a functional elementwise calculator. With the kernels done, we can write a main() script to test our kernels. This script does some basic elementwise math with large vectors of numbers: int n = 1<<20 creates a number that is 2^20 by shifting where the 1 in an array is; this works out to about 1 million elements. So this script will perform the same operations on every element of the array of floats we make, effectively testing our massive parallel operation:

    int main()
    {
    const int n = 1<<20; // ~1 million elements
    const size_t bytes = n * sizeof(float);
    // 1. Allocate and fill arrays in CPU memory
    float *h_a = (float *)malloc(bytes);
    float *h_b = (float *)malloc(bytes);
    float *h_c = (float *)malloc(bytes);
    float *h_d = (float *)malloc(bytes);
    float *h_e = (float *)malloc(bytes);
    float *h_f = (float *)malloc(bytes);
    float *h_out = (float *)malloc(bytes);
    for (int i = 0; i < n; i++) {
    h_a[i] = 1.0f;
    h_b[i] = 2.0f;
    h_c[i] = 3.5f;
    h_d[i] = 2.0f;
    h_e[i] = 10.0f;
    h_f[i] = 0.5f;
    }
    float *d_a, *d_b, *d_c, *d_d, *d_e, *d_f, *d_out;
    CUDA_CHECK(cudaMalloc(&d_a, bytes));
    CUDA_CHECK(cudaMalloc(&d_b, bytes));
    CUDA_CHECK(cudaMalloc(&d_c, bytes));
    CUDA_CHECK(cudaMalloc(&d_d, bytes));
    CUDA_CHECK(cudaMalloc(&d_e, bytes));
    CUDA_CHECK(cudaMalloc(&d_f, bytes));
    CUDA_CHECK(cudaMalloc(&d_out, bytes));
    CUDA_CHECK(cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(d_b, h_b, bytes, cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(d_c, h_c, bytes, cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(d_d, h_d, bytes, cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(d_e, h_e, bytes, cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(d_f, h_f, bytes, cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(d_out, h_out, bytes, cudaMemcpyHostToDevice));
    const int threadsPerBlock = 256;
    const int blocks = (n+ threadsPerBlock -1) / threadsPerBlock; //this rounds up
    vecAdd<<<blocks, threadsPerBlock>>>(d_a,d_b,d_c, n);
    vecMult<<<blocks, threadsPerBlock>>>(d_a,d_b,d_d, n);
    vecAdd<<<blocks, threadsPerBlock>>>(d_c,d_d,d_e, n);
    vecPow<<<blocks, threadsPerBlock>>>(d_e,d_f,d_out, n);
    CUDA_CHECK(cudaGetLastError());
    CUDA_CHECK(cudaDeviceSynchronize());
    CUDA_CHECK(cudaMemcpy(h_out, d_out, bytes, cudaMemcpyDeviceToHost));
    // 7. Verify on the CPU
    int errors = 0;
    for (int i = 0; i < n; i++) {
    if (h_out[i] < 2.2f || h_out[i] > 2.4f) errors++;
    }
    printf("Launched %d blocks x %d threads. Errors: %d\n",
    blocks, threadsPerBlock, errors);
    printf("Sample value = %.6f\n", h_out[3]);
    }

    This little script is a good verification of our kernels, and I was very pleased to see that the math came back correct, but we can also see an obvious limitation of the calculator as is: it’s very verbose and is extremely clunky to use for even basic functions. It was a good practice step to learn how to explicitly allocate and free GPU memory, but for any practical use in the future we will need to build something more streamlined.

    Final thoughts, next steps

    With that, we’ve made our first GPU-based program! Overall, it’s not too hard. It requires a deep understanding of memory and how processors work, but the actual implementation is not complicated. Next up, we’ll build out a Tensor class that includes full basic calculator functionality, automatic memory management, and handling for multidimensional matrices. Eventually, we’ll build out this tensor class with matrix operations like max, min, mean, summing, dot products, and full matrix matmul. To make our calculator more useful, we’ll add Python bindings through Nanobind and CMake; this will also make it easier to test with pytest: we can test against NumPy and eventually Torch. Finally, we’ll implement autograd for inside the Tensor Class, build out some simple MLPs and other models in Python, and test against PyTorch for speed and accuracy.

  • Building a Convolutional Neural Network(CNN) from scratch

    After dipping my toe into machine learning(ML) in the form of building an MNIST handwritten digit classifier from scratch, without using any libraries other than the most excellent and honorable NumPy, I found myself hungry for more. While I don’t plan to continue building historical model architectures from scratch forever(because it takes positively forever), building an initial intuition and developing a deep understanding of ML principles will be critical for developing new architectures in the future, as troubleshooting and intuition are seminal guides for developing novel architectures, where there are no similar architectures to reference and copy from. Towards this end, I decided to develop a convolutional neural network architecture from scratch. Taking this approach will be unnecessarily long and difficult, but I have a reason: This project is to test if I can successfully build novel architectures, and give me a deep understanding of ML core principles. Simply creating a CNN from tutorials would not test my ability to figure things out for myself.

    This blog post will cover the process I went through to go from a blank script to a fully functional CNN. It will be split into different parts covering motivation and overall architecture, core implementation, and several lessons and techniques I picked up along the way. This project will also include more best practices for writing clean and readable Python code, although I do not claim to be an expert in writing beautiful code yet.

    At this point, before we get into the actual development, it’s worth noting that I will be developing this using a purely logical, intuition-based approach. I will try to avoid using formal math language when possible, and while much of the neural network and its training may rely on advanced math functions, such as Fast Fourier Transforms, these are almost exclusively used only to increase speed. These networks can be built and trained in simple Python code using for loops, but speed can be greatly increased by using math tricks and vectorized expressions to decrease the number of individual operations during training and inference.

    Architecture:

    Coming from building a 1D fully connected/dense neural network, there are a couple of fundamental additions to our understanding that we need to implement in order to build a CNN:

    • 2D layers
      • 2D layers
      • Joining layers which go from 1D to 2D and vice versa
    • Convolutional layers
      • Convolutions
      • The principle of depth
      • Pooling

    While all of these things are simple individually, we’ll soon find that implementing them all together in a neural network is several orders of magnitude more complex than a simple 1D dense network. For my first project, I created a simple network class which included a configurable number of dense hidden layers. This approach was simple and worked well for a 1D fully connected network, but is not the most flexible for more complex architectures. For our 2D convolutional network, I wanted to add several features which should make for a more modular, flexible, and powerful network:

    • Monolithic architecture -> dynamically created networks using .yaml config files
    • Identical layers -> unique blocks of different shapes and sizes
    • ML functions defined at high level -> ML functions defined in each block class

    These changes were driven in part because they allow us to have more complex interactions between dissimilar blocks: An effective convolutional network will need, at a minimum: Fully connected layers, convolutional blocks, and pooling blocks. The connections between these types of blocks depend on the block types. A fully connected block, for example, is connected and functions differently depending on whether it’s connected to another fully connected block, or a pooling or convolutional block.

    So we need different types of layers/blocks, which possess unique qualities and functions, while also presenting a common interface for use with the model class and its training and inference functions. There are many ways to do this, but here’s how I went about it:

    I created network and block classes, where each block class has some common attributes and functions that the higher-level network can blindly access:

    Block Attributes:

    • Activations: The neuron activations in each layer. This will always be a numpy ndarray, but the shape and number of dimensions can change.
    • Z-values: The pre-activation function values for neurons in each layer. This will always be a numpy ndarray, but the shape and number of dimensions can change.

    Block Methods:

    • Forward: The forward function for each layer. This function will work differently for each layer, but can be called the same way, using the same arguments.
    • Backprop: Similar to the forward function, this function will work differently for each layer, but can be called the same way, using the same arguments.

    Blocks may also have many unique attributes which are used internally and may be called by higher functions in some cases, although not always. Because we may want to call these unique attributes in higher-level functions, we also need to have some way of knowing what type of block is at a given index in the neural network, so I added a simple tag to each block, identifying its type. This seems like an obvious step, but it’s important to include: it’s possible to build a network that works without it, but it leads to far more complexity and less flexibility.

    Core Code:

    Before we get into it, I’m simply going to go over code snippets here rather than going through each line of code, but the full code is always available on GitHub, although it may be an updated or more performant version, as there’s a bunch of things I plan to add/refine to this project.

    Config files and handling:

    In my first model, I just put everything in one file and had a(mostly) static architecture. For this Convolutional network, I wanted to use a more dynamic and flexible approach, both because useful convolutional networks often have unique shapes, and because it’s a good practice which will lead to more flexible code. To achieve this, I decided to use OmegaConf to import .yaml files as DictConfig classes which could be used throughout the model:

    model.yaml

    • Contains a complete model architecture based around blocks
    • A block includes all the info needed to produce the architecture for that block, such as: Name, type, shape, flags, etc.
    • Beyond common attributes such as name and type, some blocks have additional info such as stride and kernel shape for convolutional blocks.

    hyper_params.yaml

    • Contains all the info related to how any model should be trained, such as learning rate and batch size.
    • Also contains info about the dataset, such as number of training examples, image size, and file paths.

    These files are imported into a DictConfig, which is a structured config object that makes accessing nested information easier. All this combines to make loading and training a model a simple process:

    mdl_cfg = OmegaConf.load("model.yaml")
    lrn_cfg = OmegaConf.load("hyper_params.yaml")
    model = NN.create_network(mdl_cfg)
    results = train(lrn_cfg, mdl_cfg, model)

    This approach is very similar to config management frameworks such as hydra, but without the CLI argument functionality. It allows for simple and fast edits to architecture and training parameters, while leaving the core code loop fairly clean.

    NN(Neural Network) class:

    The neural network class is the core of the network structure and fairly simple. It is primarily just a list of blocks. It contains three major methods:

    • create_network
    • forward
    • backprop

    These methods are very simple, do what they say, and mostly just contain the conditional logic for handling how layers of different types are connected and, in the case of forward and backprop, calls to the functions of the same names in each block. Since the network is basically just a list, it’s very easy to loop through it and call a function on each block:

    class NN:
    def __init__(self, config:DictConfig, blocks: list):
    self.config = config
    self.blocks = blocks
    def forward(self, input_ly):
    self.blocks[0].activations = input_ly
    self.blocks[0].z_values = input_ly
    for index in range(len(self.blocks)):
    #print("\nindex: ", index)
    if index == 0:
    self.blocks[0].activations = input_ly
    else:
    self.blocks[index].forward(self.blocks[index-1].activations)

    In the future, I’m planning to rework the code so that the network class contains more functions as methods, but I was still coming to understand the way object-oriented programming works in Python when I initially wrote the code, so the code is more function-centered.

    Block classes:

    Where the network class is the architectural core of the model, the block classes are the functional core. Each block type may function differently, so on top of the code to create them dynamically at runtime, each block type also needs to contain the forward and backwards(backprop) methods. These unique-to-block-type methods are also where most of the complex linear algebra happens in the model; for example, the forward and backprop methods for the convolutional block are as follows:

    def forward(self, input:np.ndarray):
    self.z_values = np.zeros(shape=(self.num_filters, *self.layer_shape), dtype=np.float32)
    self.activations = np.zeros(shape=(self.num_filters, *self.layer_shape), dtype=np.float32)
    if len(input.shape) == 2:
    input = np.expand_dims(input, axis=0)
    for m in range(self.filters.shape[1]):
    for h in range(self.filters.shape[0]):
    self.z_values[m,:,:] += convolve(input[h,:,:], self.filters[h,m,:,:], conv_mode="valid")
    self.z_values[m,:,:] += self.biases[m]
    self.activations = LeakyReLU(self.z_values)
    self.activations, self.z_values, clip_warns = clip_activations(self.activations, self.z_values)
    if clip_warns:
    logging.warning(f"activations clip warning: {clip_warns} at layer {self.index}")
    def backprop(self, prior_activations:np.ndarray=None, prior_z_vals:np.ndarray=None, del_l:np.ndarray=None, expected:np.ndarray=None):
    self.W_delta = np.zeros_like(self.filters, dtype=np.float32)
    self.B_delta = np.zeros_like(self.biases, dtype=np.float32)
    if len(prior_z_vals.shape) == 2:
    prior_z_vals = np.expand_dims(prior_z_vals, axis=0)
    if len(prior_activations.shape) == 2:
    prior_activations = np.expand_dims(prior_activations, axis=0)
    prior_z_prime = LeakyReLU_prime(prior_z_vals)
    neg1_error = np.zeros_like(prior_z_vals)
    self.B_delta = np.sum(del_l, axis=(1, 2))
    for m in range(self.filters.shape[1]):
    for h in range(self.filters.shape[0]):
    kernel = self.filters[h, m]
    flipped_kernel = np.flip(kernel, axis=(0, 1))
    back = scisig.correlate2d(del_l[m], flipped_kernel, mode="full")
    trimmed = back[1:-1, 1:-1]
    neg1_error[h] += trimmed
    self.W_delta[h,m,:,:] = scisig.convolve2d(prior_activations[h,:,:], del_l[m,:,:], mode="valid")
    del_l_neg1 = neg1_error * prior_z_prime
    return(del_l_neg1, self.W_delta, self.B_delta)

    I’ll go over this code and the associated linear algebra in more detail later, but for now we can see that it’s going to be unique to each block type. Speaking of block types, where in my first 1D fully connected neural network we just had one type, we now have a gaggle of them:

    • Input block
    • FC(fully connected)
    • FC_CONV block
    • Conv(convolutional)
    • Pooling

    These are mostly what you would expect, with the exception of the FC_CONV block, which is just a fully connected block that is set up a little differently to be able to connect to each individual feature map in a convolutional layer, rather than a flat 2D layer.

    Convolution function:

    The convolution function is the core of what makes convolutional neural networks work so well for visual tasks. In broad terms, it determines each pixel/neuron in the next layer by looking at a local subset of pixels in the prior layer, multiplying them by a set of weights that’s the same size as the subset. This can be a bit confusing to talk through, but a visual can help:

    This idea of convolutions means that for a given layer-layer interaction, we only need to have a small kernel(also called a filter) to feed values between the layers. This kernel will be some small size like 5×5 or 3×3. That means that the number of weights we need to deal with goes from the dimensions of the layers multiplied together to just the kernel dimensions multiplied with the number of kernels (depth). For our example of two 28×28 2D layers, that means the weights(W) for fully connected and convolutional types are:

    Fully Connected:

    Convolutional:

    w=kx∗ky∗n=3∗3∗12=108w = kx *ky*n = 3*3*12= 108

    Where:
    l1x, l1y are the previous layer dimensions.
    l2x, l2y
    are the next layer dimensions.
    kx, ky
    are the kernel dimensions, and n is the depth(number of unique kernels).

    This really displays why CNNs are so much more effective over a dense(fully connected) network for vision tasks. The number of weights we need to do useful computations can be reduced by several orders of magnitude.

    For computer vision, what we’re doing doesn’t quite fit the strict mathematical definitions of a convolution, but it’s close enough that we can still use convolution functions to do most of the work, with some tricks before/after to format the data. This is important, because being able to use mathematical convolution functions will reduce the computational load on the network by an order of magnitude. For an in-depth look at why, please see 3Blue1Brown‘s excellent video on convolutions. For our use case, we’re going to skip over much of the pure math and focus on some gotchas and good practices for implementing convolutions in our code:

    Padding function:

    The padding function just adds zeros or copied pixels to the edges of a layer, returning a layer with slightly larger dimensions. This function is good to have so that a convolution pass can go to the very edge of a layer if needed.

    Pooling function:

    We use pooling to reduce the x-y size of layers. Pooling essentially works by running some mathematical function over a layer and outputting the results to a new layer. The function used for our case is usually max pool: Where we’re only interested in the most extreme values(because they are most likely to be carrying useful information), so we keep the maximum value from each set of tiles and get rid of the rest.

    Batch backprop function:

    This function handles much of the heavy lifting for training the model. While each layer type has its own internal method for the forward pass and backpropagation, this function handles batching data, calling the forward pass and backprop methods, and tracking the mean change to the weights and biases.

    Training function:

    The training function simply calls batch backprop over a set number of epochs taken from a hyperparameter config file. While simple in theory, this function also has to track a number of housekeeping tasks, such as data handling, updating weights and biases, logging, importing and exporting weights and performance data, and starting and communicating with the monitoring server. I also built it to save the weights and performance data periodically while training is ongoing so a power outage can’t ruin a long training run. This also enables us to end training early and pause and restart training if needed.

    Save performance class:

    Saving model performance, not just the weights and biases, is easy to overlook but is essential in making debugging easier. Things like total loss, gradient max and mins, and changes to the weights are all useful tools for debugging the model, and saving them while the training was in progress saved me a lot of headache in the debugging stage.

    Save weights class:

    Save weights is pretty self-explanatory, with the small added feature that it acts as an independent class which contains the weights separately from the model trainer.

    A server script to monitor training:

    For new models where we’re not just using an off-the-shelf model with our data, I believe that visibility into the model is as important as performance. Writing code that enables quick debugging should be as much of a focus as writing the model itself. Without this visibility, it’s all too easy to spend weeks wondering where the problem in a model is, and spend whole training runs waiting for results that we could know were bad within the first epoch. One good way to avoid wasting that effort is through testing everything on a small scale, with simple implementation first. Another critical piece is to have the ability to watch training in real time and pause to debug or make changes. To make this possible, I created a web server that displays a live dashboard of the training progress, including loss, activations, dW, and dB. To make sure the server ran reliably and could update while the training loop was busy, I used Python’s threading library to run the server on a parallel thread, which accesses training run data through shared dictionaries:

    shared_dict = {
    'epoch': 0,
    'loss': 0.0,
    'log' : [],
    'etc.': [],
    }
    import threading
    threading.Thread(target=server.start_dashboard_server, args=(shared_dict,), daemon=True).start()

    Now we have a board to monitor training, and we can change what is displayed based on what we need. Here’s a sample output from the server:

    Now, the only thing left to do is run and debug! I didn’t document as much as I should have in this step, but I worked through a couple of different bugs, including some typos in the code, which led to loss not being passed back correctly, exploding gradients, and an odd bug where improperly using a “valid” convolution rather than “full” resulted in a 1×1 being broadcast into a 9×9 filter, rather than a 9×9 into a 9×9 filter. Here’s a picture from training before the bug fix:

    And after the fix:

    This is a great example of why you should always check the scale on a graph! The buggy model is still clearly learning, and the shape of the graph looks good, but loss is still very high at the end of training. After the fix, the graph might look similar, but we can see immediately that loss is much lower, even after 5 epochs. Now that we’re confident the model is training as intended, we can do a full 50-epoch run and evaluate on our test dataset:

    That’s a pretty perfect hockey stick, and a loss of less than .1 should be good. But let’s check a couple of examples, and then evaluate the model against the full test dataset to make sure we haven’t overtrained:

    Image key: 4
    Network’s guess: 4
    [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]

    Image key: 9
    Network’s guess: 9
    [0. 0. 0. 0. 0. 0. 0. 0.0007 0. 0.9992]

    Image key: 6
    Network’s guess: 5
    [0. 0.0003 0. 0. 0. 0.7346 0.265 0. 0. 0. ]

    Here we can see that the model guesses correctly with a high degree of confidence most of the time, but when it guesses wrong, its confidence is generally lower, and in most cases, it’s hard to blame the model: That “6” barely looks like a number at all. Just to be sure, let’s check it against the full test dataset:

    num_correct = 0
    for choice in range(len(test_images)):
    trained_model.forward(test_images[choice])
    if np.argmax(trained_model.blocks[-1].activations) == test_labels[choice]:
    num_correct = num_correct + 1
    print(f" num samples:{len(test_images)}, num correct:{num_correct}")
    print(f"overall accuracy:{num_correct/len(test_images)}")

    output: num samples:10000, num correct:9796 overall accuracy:0.9796

    An overall accuracy of 97% is pretty good! I’ll do another post about lessons learned and things I would do differently in the future, but for now I’m more than satisfied with this project.

  • Building a neural net from scratch: Code Implementation

    In this post, let’s get right into the code!

    Let’s start out by defining a basic neural network. There will be many more utility functions to write soon, but this will at least give us a basic idea of what things will look like. Our network will be comprised of layers, biases, and weights, and given that the biases and weights are there to modify the layers, we should be able to create them automatically:

    def create_layer(layer_size, dtype=np.float32, **kwargs):
    layer = np.zeros(layer_size, dtype=dtype)
    return(layer)
    def create_layer_weights(prev_ly_size, curr_ly_size, init=True):
    if init:
    #ly_weights = np.random.rand(prev_ly_size, curr_ly_size)
    ly_weights = np.random.uniform(-1,1, size=(prev_ly_size, curr_ly_size))
    else:
    ly_weights = np.zeros(shape=(prev_ly_size, curr_ly_size))
    return(ly_weights)
    def create_biases(ly_size, init=True):
    if init:
    biases = np.random.rand(ly_size)
    else:
    biases = np.zeros(ly_size)
    return(biases)

    We can now create a network, which is just an object containing lists of layers, biases, and weights. We’ll also store the z-values(the values of each neuron before being run through the activation function), because future us finds out they’re necessary to help do backpropagation :

    class n_network:
    def __init__(self, layers, z_layers, biases, weights):
    self.layers = layers
    self.z_layers = z_layers
    self.biases = biases
    self.weights = weights
    def create_network(in_ly_size, out_ly_size, hidden_ly_num, hidden_ly_size):
    in_layer = create_layer(in_ly_size)
    hidden_lys = []
    for index in range(hidden_ly_num):
    hidden_lys.append(create_layer(hidden_ly_size))
    out_layer = create_layer(out_ly_size)
    network_lys = [in_layer, *hidden_lys, out_layer]
    z_layers = deep_copy_mat_list(network_lys, False)
    biases =[]
    for i in range(1, len(network_lys), 1):
    biases.append(create_biases(np.size(network_lys[i]), init=False))
    weights = []
    for i in range(1, len(network_lys), 1):
    weights.append( create_layer_weights(np.size(network_lys[i-1]), np.size(network_lys[i]), init=True))
    network = n_network(network_lys, z_layers, biases, weights)
    return(network)

    We also need to create a function to create deep copies of Python lists, as simply creating a copy this way:

    z_layers = network_lys

    will create a new list linked to the same objects, rather than copying the objects themselves, so we create a function:

    def deep_copy_mat_list (list_to_copy, propigate_cell_vals=True):
    #creates a copy of a list containing numpy arrays of varible size, ethier as empty arrays or with the same values
    new_list = []
    if propigate_cell_vals:
    for items in list_to_copy:
    new_list.append(items)
    else:
    for items in list_to_copy:
    new_list.append(np.zeros_like(items))
    return(new_list)

    Now, to test if the network will run, we can add our forward and activation functions. For this project, we’re going to use a sigmoid function. We’ll also add its derivative (sigmoid_prime), which we’ll need for backprop later:

    def forward(input_vals:np.ndarray, net:n_network):
    #first layer
    input_vals = np.array(input_vals)
    net.layers[0] = input_vals
    for index in range(1, len(net.layers), 1):
    net.z_layers[index] = np.dot(net.layers[(index-1)], net.weights[index-1]) + net.biases[index-1]
    net.layers[index] = sigmond(net.z_layers[index])
    #activation function
    return(net)
    def sigmond(input):
    #a more easily vectorizable sigmond function
    return( 1/(1+np.exp(-input)))
    def sigmond_prime(input):
    return(sigmond(input) * (1-sigmond(input)))

    With this done, we can test a forward pass, using random weights and a mostly empty input layer. This should just output random gibberish, but it’s a good check to see that the network is functional:

    net = create_network(28*28, 10, 2, 5)
    input_ly = np.zeros((28,28))
    input_ly[3,4] = 1
    input_ly = input_ly.flatten()
    out = forward(input_ly, net)
    print(np.max(out.layers[-1]))

    Now that we have a basic idea of our neural network, we can get into the bulk of the work. To start out, before we get into any of the ML, we need to get our dataset imported and make sure we can handle and inspect training data. The MNIST digit dataset can be downloaded here and is split into images, labels, training, and test, formatted in .idx1-ubyte or .idx3-ubyte. If the files have a .gz format as well, they will need to be unzipped before use. A quick peek into these files once they’re unzipped shows that they’re in a binary format, which is common for large ML datasets. So to read and manipulate the data, we’ll write a few functions:

    import matplotlib.pyplot as plt
    import numpy as np
    images_path = "MNIST/train-images.idx3-ubyte"
    labels_path = "MNIST/train-labels.idx1-ubyte"
    batch_size = 2
    dataset_size = 60000
    image_size = 28**2
    image_dim = int(np.sqrt(image_size))
    def label_to_output(int) -> np.ndarray:
    #for a single label
    outlayer = np.zeros(shape=(10), dtype=np.float32)
    outlayer[int] = 1
    return(outlayer)
    def label_vec_to_output(inputs: np.ndarray) -> np.ndarray:
    #for a batch of labels
    # Create an identity matrix of size 10 and index into it
    return np.eye(10, dtype=np.int8)[inputs]
    def create_batch(image_file, label_file):
    #this takes the raw file objects and reads an appropriately sized batch in numpy arrays
    image_buffer = image_file.read(image_size * batch_size)
    input_batch = np.frombuffer(image_buffer, dtype=np.uint8).astype(np.float32)
    input_batch = input_batch.reshape(batch_size, image_size)
    label_buffer = label_file.read(batch_size)
    label_batch = np.frombuffer(label_buffer, dtype=np.uint8).astype(np.int64)
    Label_batch = label_vec_to_output(label_batch)
    return(input_batch, Label_batch)
    def view_batch_sample(batch_size, image_batch, label_batch):
    image_batch = image_batch.reshape(batch_size, image_dim, image_dim, 1)
    for index in range(batch_size):
    image = np.asarray(image_batch[index]).squeeze()
    plt.imshow(image)
    plt.show()
    print(f"image label: {np.argmax(label_batch[index])}")

    Now let’s test our functions:

    f = open(images_path, 'rb')
    f.read(16)
    l = open(labels_path,'rb')
    l.read(8)
    im_btc, lb_btc = create_batch(f, l)
    view_batch_sample(batch_size, im_btc, lb_btc)

    Notice the functions for creating a batch do not load the files themselves. Since we will be creating many batches in a single training loop, we will only load the files into memory once in the high-level training loop. This is good practice to avoid wasting resources reloading the same files. We should see an output like this from our test code:

    image label: 5

    image label: 0

    We should also add a loss function, maybe a couple other functions, and a config object. For this example, we’ll use the @dataclass decorator. This seems verbose but will make passing code parameters to functions much simpler. For simplicity purposes, I’ve removed references to cfg in the functions and objects shown up to this point, but they are included in the full working code on GitHub:

    from dataclasses import dataclass
    @dataclass
    class Config:
    input_layer_size: int
    output_layer_size: int
    hidden_layer_num : int
    hidden_layer_size : int
    dataset_size : int
    learning_rate :float
    batch_size : int
    epochs : int
    def loss(network_output_ly, expected_ly):
    #loss = mean of all output neurons - the expected, squared
    loss_vec = ((network_output_ly - expected_ly)**2) / 2
    loss_sclr = np.sum((network_output_ly - expected_ly)**2)
    return(loss_sclr, loss_vec)

    Now, finally, we can get to the core of our learning code. We’ll split this into three separate functions, with the core math happening in the backprop function:

    def backprop_single(net: n_network, expected_out_ly):
    #does backprop for a single training example, duhh
    first = True
    expected_out_ly = np.array(expected_out_ly)
    w_delta = deep_copy_mat_list(net.weights, propigate_cell_vals=False)
    b_delta = deep_copy_mat_list(net.biases, propigate_cell_vals=False)
    a_error = deep_copy_mat_list(net.layers, propigate_cell_vals=False)
    for l in range(len(net.layers)-1, 0, -1):
    w = l - 1
    if first:
    #first(last) layer
    first = False
    a_delta_dir = expected_out_ly - net.layers[l]
    a_error[l] = a_delta_dir * sigmond_prime(net.z_layers[l])
    a_error[l-1] = np.dot(net.weights[w], a_error[l]) * sigmond_prime(net.z_layers[l-1])
    w_delta[w] = np.outer(net.layers[l-1], a_error[l])
    b_delta[w] = a_error[l]
    else:
    a_error[l] = np.dot(net.weights[w+1], a_error[l+1]) * sigmond_prime(net.z_layers[l])
    w_delta[w] = np.outer(net.layers[l-1], a_error[l])
    b_delta[w] = a_error[l]
    return(w_delta, b_delta)

    This code bears explaining, as it’s the core of what makes our neural network able to learn, and therefore deserving of being called AI/ML. The code loops backwards through our network, because we can only directly measure error in the final(output) layer. We start by subtracting what the network predicted from our expected outputs(which will be a one-hot matrix containing the image label); this gives us a point on the error surface:

                a_delta_dir = expected_out_ly - net.layers[l]

    Note that this actually gives us the negative of our error; we do this because we want to reduce error. We could also do this by multiplying by -1 later when we want to apply changes, but doing it now means we don’t have to remember it later. Next, we’ll take the derivative of our activation function at that point; this will provide our error gradient. Note that to take the derivative properly, we actually use the pre-activation values for each neuron(the z values). This makes sense because we want to know how our layer changes with respect to its changes in its input values:

                a_error[l] = a_delta_dir * sigmond_prime(net.z_layers[l])

    We can now directly change the activations of our layer by biasing them with the negative error, and we can change the weights by multiplying the negative error by the activations of the prior layer. Applying either one of these changes would greatly reduce error for this training image, but would probably not help the network as a whole, as the gradient is not constant, and it will change for different training examples and as we manipulate weights and biases. Instead, we’ll simply save the suggested changes to the weights and biases of this layer and multiply them by the learning rate (a small number such as 0.01), and average them over a batch before applying them to the network. This is also just finding suggested changes to the final layer so far:

                w_delta[w] =  np.outer(net.layers[l-1], a_error[l])
                b_delta[w] = a_error[l]

    Since these are fully connected layers, each weight is directly connected to exactly 1 neuron in the prior layer and 1 neuron in the current layer, so we can find how to change them to reduce error by multiplying each weight by its corresponding activation in the prior layer and the negative error of the corresponding neuron in the current layer. This ends up being easily represented as the outer product. For a network of 1-D layers, it can even easily be visualized by a table:

    negative error in current layer neurons
    0.24-0.120.9
    input neuron activations0.10.024-0.0120.09
    0.50.12-0.060.45
    0.780.1872-0.09360.702
    suggested changes to each weight ^

    For simple fully connected networks, this is a wonderful way to build intuition for how we use error to train neural networks. In many more complicated examples, finding an intuition becomes far harder to visualize, but the core of changing weights to reduce error by understanding how different neurons interact through weights… will remain largely the same.

    Speaking of more complicated, we now need to backpropagate our error to prior layers. We do this one layer at a time, by finding how the error in each output neuron is formed by the weights and activations of the neurons in the prior layer:

    a_error[l-1] = np.dot(net.weights[w], a_error[l]) * sigmond_prime(net.z_layers[l-1])

    We’ve used the derivative of the activation function before to know how our layer changes with respect to its changes in its input values, so the only new part here is the dot product. The dot product here is transforming the error in the current layer, through the weights, into the prior layer. This can be a little counterintuitive at first, but it’s really just a way of summing the influence of the error in each output neuron to a given neuron in the prior layer, through the weights which connect each neuron.

    Whew! Now that we’ve gone through all that for one layer, and backpropagated our measure of negative error to the next layer back, we can just repeat over the rest of the layers in the network, stopping one layer before the input layer, as we can’t influence it, and there are 1 fewer layers of weights than neurons, as the weights only exist between neuron layers.

        for l in range(len(net.layers)-1, 0, -1):
            if not last_layer:
                w = l - 1
                a_error[l] = np.dot(net.weights[w+1], a_error[l+1]) * sigmond_prime(net.z_layers[l])
                w_delta[w] =  np.outer(net.layers[l-1], a_error[l])
                b_delta[w] = a_error[l]

    Looking at the whole function again:

    def backprop_single(net: n_network, expected_out_ly):
    #does backprop for a single training example, duhh
    first = True
    expected_out_ly = np.array(expected_out_ly)
    w_delta = deep_copy_mat_list(net.weights, propigate_cell_vals=False)
    b_delta = deep_copy_mat_list(net.biases, propigate_cell_vals=False)
    a_error = deep_copy_mat_list(net.layers, propigate_cell_vals=False)
    for l in range(len(net.layers)-1, 0, -1):
    w = l - 1
    if first:
    #first(last) layer
    first = False
    a_delta_dir = expected_out_ly - net.layers[l]
    a_error[l] = a_delta_dir * sigmond_prime(net.z_layers[l])
    a_error[l-1] = np.dot(net.weights[w], a_error[l]) * sigmond_prime(net.z_layers[l-1])
    w_delta[w] = np.outer(net.layers[l-1], a_error[l])
    b_delta[w] = a_error[l]
    else:
    a_error[l] = np.dot(net.weights[w+1], a_error[l+1]) * sigmond_prime(net.z_layers[l])
    w_delta[w] = np.outer(net.layers[l-1], a_error[l])
    b_delta[w] = a_error[l]
    return(w_delta, b_delta)

    It finally returns weight change suggestions and bias change suggestions. We’ll now use a batching function to repeat this process and average the change suggestions over a batch of training examples:

      
    def batch_learning(input_batch:np.ndarray, desired_output_batch:np.ndarray, net:n_network, cfg:Config):
        #This runs the network across every training example in a single batch and averages the results, returning a decent step and the loss across the batch
    
        cfg.batch_size
        w_del_batch = []
        b_del_batch = []
        batch_loss = np.ndarray((cfg.batch_size,))
    
        for layers in net.weights:
            w_del_batch.append(np.zeros((cfg.batch_size,) + layers.shape, dtype=np.float32)  )
        for layers in net.biases:
            b_del_batch.append(np.zeros((cfg.batch_size,) + layers.shape, dtype=np.float32)  )
    
    
        for batch in range(cfg.batch_size):
            net = forward(input_batch[batch], net)
            w_del_batch_tmp, b_del_batch_tmp = backprop_single(net, desired_output_batch[batch])
    
            for layer_num in range(cfg.hidden_layer_num +1):   
                w_del_batch[layer_num][batch,:,:] = w_del_batch_tmp[layer_num]
                b_del_batch[layer_num][batch,:] = b_del_batch_tmp[layer_num]
            
            loss_sclr, loss_vec = loss(net.layers[-1], desired_output_batch[batch])
            batch_loss[batch] = loss_sclr
        batch_loss = np.mean(batch_loss)
    
        w_delta_mean = deep_copy_mat_list(net.weights, False)
        b_delta_mean = deep_copy_mat_list(net.biases, False)
        for layer_num in range(cfg.hidden_layer_num +1):   
            w_delta_mean[layer_num] = np.mean(w_del_batch[layer_num], axis=0) * cfg.learning_rate         #learning rate is here!
            b_delta_mean[layer_num] = np.mean(b_del_batch[layer_num], axis=0) * cfg.learning_rate
    
        descent_step = w_delta_mean, b_delta_mean
        return(descent_step, batch_loss)

    We also take the chance to apply the learning rate here. This reduces the step size we take down the gradient to a size within which we hope the direction will still be mostly correct. After finding the suggested changes(descent step), we can pass it up to our highest level training function, which trains over the whole dataset for a number of epochs:

    
    def train(images_pth, labels_pth, cfg:Config):
        #the core training loop that trains through epochs.  
        # requires an images path, labels path(ideally located in the same directory as this code), and cfg containing hyperparameters
    
        #plotting stuff 
        x_data, y_data = [],[]
        from IPython.display import clear_output
    
        net = create_network(cfg.input_layer_size, cfg.output_layer_size, cfg.hidden_layer_num, cfg.hidden_layer_size)
        for epoch in range(cfg.epochs):
            print("epoch ", int(epoch), "out of ", int(cfg.epochs))
            f = open(images_pth, 'rb')
            f.read(16)
            l = open(labels_pth,'rb')
            l.read(8)
            for index in range(0, cfg.dataset_size, cfg.batch_size):
                input_ly, label_ly = create_batch(cfg, f, l)
                (W_delta, B_delta), loss = batch_learning(input_ly, label_ly, net,cfg)
                for layer_num in range(cfg.hidden_layer_num +1):   
                    net.weights[layer_num] = net.weights[layer_num] + W_delta[layer_num]
                    net.biases[layer_num] = net.biases[layer_num] + B_delta[layer_num]
            
            #plotting stuff
            x_data.append(epoch)
            y_data.append(loss)
            clear_output(wait=True)        # Clear previous plot
            plt.figure(figsize=(6, 4))
            plt.plot(x_data, y_data, 'bo-')
            plt.title("Epoch vs Loss")
            plt.xlabel("Epoch")
            plt.ylabel("Loss at epoch end")
            plt.grid(True)
            plt.show()
    
        return(net, (x_data, y_data))   
    
    
    
    

    While this loop looks sizable, most of it is just for tracking training progress and file handling. The core learning just moves over batches and epochs, adding the suggested changes calculated earlier in our batch learning function:

    (W_delta, B_delta), loss = batch_learning(input_ly, label_ly, net,cfg)
    for layer_num in range(cfg.hidden_layer_num +1):
    net.weights[layer_num] = net.weights[layer_num] + W_delta[layer_num]
    net.biases[layer_num] = net.biases[layer_num] + B_delta[layer_num]

    And that’s it! We now just need to create a config set and call the training function. Before we do that, we’ll also write some functions to save training performance and our network weights and biases. I won’t go over this code in depth since it’s nothing special:

    def save_weights_biases(net:n_network):
    #save the weights and biases
    import pickle
    from datetime import datetime
    timestamp = datetime.now().strftime("%m%d%Y_%H%M%S")
    file_name = f"weights/nn_training_{timestamp}.pkl"
    with open(file_name, "wb") as f:
    pickle.dump(net, f)
    return(timestamp, file_name)
    def save_performance(x_epoch, y_loss, cfg:Config, timestamp):
    #save hyperparams and preformance data to a csv
    import csv
    #["run ID", "timestamp", "number of hidden layers", "hidden layer size", "LR", "Epochs", "Batch size"]
    from datetime import datetime
    #timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    run_id = f"{cfg.hidden_layer_num}{cfg.hidden_layer_size}{cfg.learning_rate}{cfg.epochs}{cfg.batch_size}"
    data = [run_id, timestamp, cfg.hidden_layer_num, cfg.hidden_layer_size, cfg.learning_rate, cfg.epochs, cfg.batch_size]
    results_name = 'results.csv'
    with open(results_name, mode='a', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(data)
    plot_f_name = f"results/{run_id}_{timestamp}_plots.csv"
    print(type(y_loss))
    plots = [[x_epoch],[y_loss]]
    with open(plot_f_name, mode='w', newline='') as file:
    writer = csv.writer(file)
    for index, value in enumerate(x_epoch):
    writer.writerow([int(x_epoch[index]), (y_loss[index])])
    return(run_id, results_name,plot_f_name)

    Now to create a config set and call the training function:

    image_size = 28**2
    batch_size = 100
    dataset_size = 60000
    hidden_layers = 3
    hidden_layer_size = 17
    learning_rate = 0.05
    epochs = 100
    images_path = "MNIST/train-images.idx3-ubyte"
    labels_path = "MNIST/train-labels.idx1-ubyte"
    cfg = Config(input_layer_size=image_size,
    output_layer_size=10,
    hidden_layer_num= hidden_layers,
    hidden_layer_size = hidden_layer_size,
    learning_rate=learning_rate,
    dataset_size=dataset_size,
    batch_size=batch_size,
    epochs=epochs
    )
    net, (x_epoch, y_loss) = train(images_path, labels_path, cfg=cfg)
    timestamp, f_name = save_weights_biases(net)
    run_id, results_f_name, plot_f_name = save_performance(x_epoch,y_loss, cfg=cfg, timestamp=timestamp)

    Now that we’ve done all the code, we can go ahead and train the model; we should see an output something like this:

    We can see that after 100 epochs, our loss is around 0.1, which means the model will correctly guess most of the time, which is pretty good! Side note: A loss of 0.1 is not necessarily 90%, because loss is not exactly accuracy, but it’s still quite a good result. The model is clearly learning and performs significantly better than a random guess, which means we’ve successfully made a machine learning model that works! It could be better, and we will need to check against a test dataset to ensure the model hasn’t just memorized the training dataset, but overall we can call the project a success. Now we can move on to more useful models like convolutional neural networks and transformers.

  • Building a neural net from scratch: Motivation and Architecture

    In the Machine Learning (ML) world, the equivalent of a hello world program is building a handwritten digit classifier using a neural network. I decided to take building a digit classifier on as my first project, just dipping my toe into ML and AI, to see if it was something I could compete in. There was no question that I was interested in it. I had dreamed of making artificial intelligence since early high school, long before it became a visible career path. Now, at the ripe old age of 27, I decided to try my hand at the most difficult and competitive field of software engineering, during a time when the job market was one of the worst in years. What could possibly go wrong?

    So naturally I needed to figure out if I could swing it, and keep up with people 10 years younger and smarter than me in the field. Towards this end, I decided to do this project in the hardest, but also most learning-intensive, way possible: with little to no references or help, and not following any guide. I would learn about what a neural network was, understand the major concepts required for its functionality, and then build it. This is not the fastest way to build a neural network, or even the most efficient way to learn ML, but it would be a good test to show whether the field was a fit for me: By not using many outside resources, and trying to build and iterate on intuition rather than replicating others’ work, I was simulating my job goal: Building novel neural nets where resources are limited because no one has built anything similar.

    A simple neural network with fully connected layers

    So what is a neural network (NN)? I expected this question to have a complex answer. It does not. Most basic NNs are simply a number of neurons, which are just a number, and weights. The neurons are organized in layers and connected through weights. Pretty simple, right? I’m not sure what all the fuss is about with ML; this stuff’s easy!

    Neural Networks are easy. simple.

    How they learn, on the other hand, is very much not easy, not simple. Even though on a high level of abstraction it may seem simple: The learning process is trial and error, and the network goes towards less error. The formal term for this is gradient descent, and its implementation relies largely on a deep understanding of vector calculus: Taking concepts from formal mathematics which are taught in one or two dimensions and applying them between much more complex N-dimensional matrices.

    A veryyyyyy simplified example of gradient descent

    I won’t make an attempt to fully cover how gradient descent works here, mostly because there are others who have already done this far, far better than I can. A quick web search will return a plethora of resources. For getting started with an intuition for how NNs learn, I used and highly recommend 3Blue1Brown’s excellent video series on the topic, which does not fully explain the complexities in implementing gradient descent, but helps build a fundamental understanding of what it’s meant to do. Beyond that, Andrej Karpathy is an excellent resource for getting everything from high-level understanding down to the code. I also used Michael Nielsen’s online textbook for some points where I got stuck, although I don’t recommend using the code from this textbook, as it was written in Python 2.7, and the function of some modules used has changed dramatically since then.

    So our network should be comprised of some minimum number of layers, with an input layer, n number of hidden layers, and an output layer. The neurons in these layers will be connected by weight matrices, where the weights are updated to reduce error in the output layer through a process called gradient descent.

    To gain an intuition for how gradient descent works, let’s start with an example which is simple enough to visualize. If we have an output layer of two neurons which can output anywhere from 0 to 1, and a set of training data which gives us knowledge of what the output layer SHOULD be (let’s call these expected values), we should be able to figure out what the difference, or error, is in the output layer. For example:

    Or expressed as code:

    import numpy as np
    output = np.array([1,1])
    expected = np.array([0,1])
    error = output - expected
    print(error) -> [1, 0]

    To turn this into something we can minimize, we combine the errors into a single number called the loss (or cost). A common choice is squared error, ½·Σ(output − expected)². The gradient of the loss with respect to our two output neurons tells us how changing each one affects the total error, and for squared error it works out to exactly the error vector above: output − expected. Because this is a simple example with just two neurons, we can plot the error and its gradient in a visually intuitive way; this will quickly become impossible to visualize as each additional neuron adds a dimension to the error vector, but for our very simple example we can plot it to aid our intuitive understanding of error and learning:

    The above visuals helpfully show the difference between the error and its gradient, and we can intuitively make the jump that moving down the gradient will reduce our error. Beyond this simple example, it will quickly become impossible to visualize the gradient directly, as even for simple networks the gradient is many thousands of dimensions.

    Now that we know the gradient at the location our network currently is, we can adjust the values of our output neurons in the negative direction of the gradient at the current location, thereby reducing error. We can do this either by directly changing neuron activation (changing the bias) or by changing the ways our neurons interact with prior layers (changing the weights). There is a third way we can use the gradient to reduce error, and while it’s the most complex, it’s also by far the most powerful and critical to the secret sauce of ML. So far we’ve only talked about manipulating the neurons in our output layer directly, which would be all we could do if our network was completely flat (a single layer), but neural networks (loosely inspired by the brain) are made of many layers, each feeding forward into the next. True learning comes from changing ALL layers hidden between the input and output layers. That being said, we only have an understanding of what the error gradient is in our output layer, so how would we know which directions to change hidden layers in our network to reduce error?

    Enter backpropagation. Backprop is the third way we can use our gradient to reduce error that we referenced earlier, and is by far the most powerful. It’s also where, as we’ll find out in future chapters covering code implementation, the math goes from simple calculus to brain-numbingly complex linear algebra. Yay!

    For now, let’s stick with our super simple example. In addition to the two output neurons we have been studying, let’s add a hidden layer feeding into them, also with two neurons:

    We’ve calculated the error gradient in the output layer, so we know which direction we want each output neuron to change. We should also know the way those output neurons are influenced by upstream hidden layers, through the weighted connections between neurons in each layer (the weights), so we should logically be able to figure out how we would want individual neurons in prior hidden layers to change to reduce error in the output layer. The term for how we want these upstream neurons to change is the backpropagated error gradient, and we can use it in exactly the same ways as we did in the output layer: to change neuron activations directly (biases), to change the way the prior layers affect them (weights), and to once more backpropagate the error gradient to the next earlier layer. We can repeat this process until we’ve backpropagated the error in our output neurons all the way through our neural network, and then make changes in each layer based on that error.

    In our simple example, we can easily plot the error gradient for the whole range of possible output neurons. In real networks, however, we can generally only know the error gradient at the exact point a given training example produces. Because the gradient is not constant, we cannot simply adjust the network to the negative magnitude of the gradient; if the gradient were constant, doing this would reduce error to zero in a single step. In reality, it will most often just cause some random change in the error. To get around this, we will adjust the network weights and biases only by a small percentage of the negative error gradient, just taking a small step in that direction, before repeating this process and taking many small steps down the gradient until we reach a sufficiently low error.

    To further increase the accuracy of our gradient descent, we will also average together suggested learning steps from a number of different training examples, only applying the averaged change to our network weights and biases. This process is called batching.

    We can also train our network on all our training data multiple times, looping through all training examples for some number of epochs.

    All of these processes and steps combine to form the core of our training loop. There are many other things which I’ve left out of this explanation, such as our loss and activation functions, but these will be covered in future chapters. While no single step of the machine learning process is particularly difficult in isolation, they layer atop each other to create a system which is difficult to fully intuit at the beginning of the learning process. Isolating individual steps, testing them in their simplest form, and digging out the actual processes from high-level abstractions are key skills for learning and developing ML.

    Armed with this understanding, in the next post we’ll cover using our intuition to start writing the high-level code for a neural network that classifies images of handwritten digits using the MNIST database to train a fully connected network with 1-3 hidden layers.

  • WIEVLE – Autonomous underwater robot design

    While working at the Naval Postgraduate School, I handled the physical design for an underwater robot which would result in further development, ongoing funding, and patents. This was one of my first professional experiences being given complete ownership over part of a project: applying the systems engineering process to a real-world design and taking a concept through the full engineering lifecycle. I loved it.

    The design of this robot, particularly the physical design, came from a clear set of requirements:

    • A spherical hull rated for extreme depths
    • Manufactured primarily by 3D printing
    • A unique, physics-based propulsion system that used buoyancy and reversed, angled thrust to reduce sediment disturbance
    A diagram showing WIEVLE's unique propulsion system
    A diagram showing WIEVLE’s unique propulsion system
    A screenshot from the patent showing the modular plate structure
    A screenshot from the patent showing the modular plate structure

    This design uses modular plates, easily replaceable, attached to a floating ring system and pulled together over a propulsion core, creating a pseudo-exoskeleton to bear structural loads and freeing up internal space for payloads and control electronics. A truncated cubeoctahedron was chosen as the basic shape because it fit seamlessly with the thrust outlet pattern.

    To accommodate these requirements, I designed and built a modular plate system using a truncated cuboctahedron projected onto a sphere; this design choice was requirements-driven and gave us the ability to manufacture the robot in modular sections within the performance limitations of the 3D printing capabilities available to us. This work would result in successful prototypes tested underwater, ongoing funding for the WIEVLE project and spinoff projects, a patent for this exact work, and a further patent on the WIEVLE vehicle.

    A CAD rendering showing how WIEVLE's plates attach to internal rings
    A CAD rendering showing how WIEVLE’s plates attach to internal rings

    This work provided a baseline that has continued on to fund multiple projects, generate patents, garner Navy interest, and is currently continuing towards commercialization and adoption by the Navy.