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.

Posted in

Leave a Reply