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.

Posted in

Leave a Reply