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.

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:
<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 upvecAdd<<<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:
CUDA_CHECK(call)
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 CPUint 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:
<cstdio> <cstdlib> <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.
Leave a Reply