CUDA Tutorials for Vectors and Statistics¶
Ten progressive, self-contained CUDA C++ tutorials migrated from Henry Ndubuaku's cuda-tutorials repository, taking you from your first element-wise vector kernel to multi-stage statistical pipelines and parallel numerical calculus. Each tutorial separates the mathematical intuition, parallelisation strategy, and engineering caveats cleanly from the full runnable source code.
How to Compile and Run¶
Running Locally with the CUDA Toolkit¶
- Any machine with an NVIDIA GPU and the CUDA Toolkit installed can compile and run all ten programs straight from the terminal.
- First check that your GPU driver is active with
nvidia-smiand that the CUDA compiler is available on your path withnvcc --version. - Navigate into the companion
cudadirectory and compile a.cusource file directly into a native executable.
nvidia-smi
cd "chapter 19 - CUDA and GPU programming/cuda"
nvcc 01.vectorAdd.cu -o vectorAdd && ./vectorAdd
- For faster kernels and architecture-specific code generation, add
-O3for compiler optimisation and-arch=sm_75(Turing, such as the T4) or your GPU's compute capability (for examplesm_86on RTX 30-series orsm_89on RTX 40-series).
Running for Free in Google Colab¶
- If you do not have an NVIDIA GPU locally, you can run every tutorial for free in Google Colab.
- Open colab.research.google.com, click Runtime in the top menu, select Change runtime type, and choose T4 GPU.
- Write any tutorial into a
.cufile using the%%writefilecell magic.
- In the next cell, compile with
-O3and run the executable on the attached GPU.
01. Vector Addition¶
- Vector addition is the "Hello, World" of GPU programming. Given two vectors \(\mathbf{a}\) and \(\mathbf{b}\) of length \(n\), their sum adds corresponding components independently,
- Because output element \(c_i\) depends only on \(a_i\) and \(b_i\), the workload is embarrassingly parallel. Every thread computes its unique 1D global index with
blockDim.x * blockIdx.x + threadIdx.xand performs one addition. - The grid launch uses ceiling division
(numElements + threadsPerBlock - 1) / threadsPerBlockso the grid always supplies at leastnumElementsthreads. With 50 elements and 256 threads per block, CUDA launches 1 block, and the bounds checkif (i < numElements)stops the spare 206 threads from touching memory past the end of the arrays. - The
mainfunction establishes the classic CUDA host-device lifecycle that reappears across every tutorial in this series. You allocate host memory withmalloc, allocate GPU memory withcudaMalloc, copy inputs withcudaMemcpyHostToDevice, launch the kernel with<<<blocksPerGrid, threadsPerBlock>>>, copy results back withcudaMemcpyDeviceToHost, and release both allocations withfreeandcudaFree. - Watch out for two beginner pitfalls. Dropping the
if (i < numElements)guard triggers out-of-bounds global memory writes in the final block, and launching a GPU kernel on tiny vectors like 50 elements spends far more time copying data over PCIe than adding numbers (real speedups appear once \(n\) reaches tens of thousands or millions).
Source file 01.vectorAdd.cu. Compile and run with nvcc 01.vectorAdd.cu -o vectorAdd && ./vectorAdd.
#include <iostream> // for std::cout
#include <cuda_runtime.h> // for CUDA runtime functions
#include <device_launch_parameters.h> // for CUDA kernel launch parameters
__global__ void vectorAdd(const int *a,
const int *b,
int *c,
int numElements) {
// Calculate the global index for the current thread
int i = blockDim.x * blockIdx.x + threadIdx.x;
// Ensure we don't go out of bounds
if (i < numElements){
// Add corresponding elements of input vectors
c[i] = a[i] + b[i];
}
}
int main() {
// Number of elements in vectors
int numElements = 50;
// Calculate the size of the data
size_t size = numElements * sizeof(int);
// Declare pointers for host and device vectors
int *hostA, *hostB, *hostC;
int *deviceA, *deviceB, *deviceC;
// Allocate memory for host vectors
hostA = (int*) malloc(size);
hostB = (int*) malloc(size);
hostC = (int*) malloc(size);
// Initialize input vectors
for (int i = 0; i < numElements; i++){
hostA[i] = i;
hostB[i] = i*2;
}
// Allocate memory for device vectors
cudaMalloc((void**)&deviceA, size);
cudaMalloc((void**)&deviceB, size);
cudaMalloc((void**)&deviceC, size);
// Copy host vectors to device
cudaMemcpy(deviceA, hostA, size, cudaMemcpyHostToDevice);
cudaMemcpy(deviceB, hostB, size, cudaMemcpyHostToDevice);
// Define grid and block dimensions
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
// Launch the vectorAdd kernel
vectorAdd<<<blocksPerGrid, threadsPerBlock>>>(deviceA, deviceB, deviceC, numElements);
// Copy result vector from device to host
cudaMemcpy(hostC, deviceC, size, cudaMemcpyDeviceToHost);
// Print the results
for (int i = 0; i < numElements; i++){
std::cout << hostA[i] << " + " << hostB[i] << " = " << hostC[i] << std::endl;
}
// Free the memory allocated for host vectors
free(hostA);
free(hostB);
free(hostC);
// Free the memory allocated for device vectors
cudaFree(deviceA);
cudaFree(deviceB);
cudaFree(deviceC);
return 0;
}
02. Hadamard (Element-Wise) Product¶
- Given two vectors \(\mathbf{a}\) and \(\mathbf{b}\) of the same dimension \(n\), their Hadamard (or element-wise) product scales each component of \(\mathbf{a}\) directly by the matching component of \(\mathbf{b}\),
- Element-wise multiplication shows up everywhere in deep learning and vision, including gating mechanisms in LSTMs and SwiGLU blocks, dropout and attention masks, and per-pixel image blending where every pixel is transformed independently.
- The parallelisation pattern mirrors vector addition (one thread per index with a bounds guard), moving from integers to single-precision
floatarrays populated by a small host helperrandomFloat. - Watch out for two subtle type details when adapting this pattern to large workloads. First,
numElementsin the kernel parameter list is typed asfloatrather thanint; that works harmlessly for small arrays, whereas production kernels should keep lengths asintorsize_tbecause 32-bit floats lose exact integer precision beyond \(2^{24}\) (about 16.7 million). Second, dividingrand()by1000scales values rather than bounding them to \([0, 1]\) (for \([0, 1]\), divide byRAND_MAX).
Source file 02.vectorHadamard.cu. Compile and run with nvcc 02.vectorHadamard.cu -o vectorHadamard && ./vectorHadamard.
// Include necessary libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void vectorHadamard(const float *a,
const float *b,
float *c,
float numElements){
// Calculate the unique index for the thread
int idx = blockDim.x * blockIdx.x + threadIdx.x;
// Check if index is within the range of elements
if (idx < numElements){
// Perform the multiplication
c[idx] = a[idx] * b[idx];
}
}
// Function to generate a random float
float randomFloat(int randMax = 1000){
// Return a random float between 0 and 1
return static_cast<float>(rand()) / static_cast<float>(randMax);
}
// Main function
int main(){
// Seed the random number generator
srand(time(0));
// Define the number of elements in the vectors
int numElements = 100;
// Calculate the size of the vectors in bytes
size_t size = numElements * sizeof(float);
// Declare pointers for host and device vectors
float *hostA, *hostB, *hostC;
float *deviceA, *deviceB, *deviceC;
// Allocate memory for host vectors
hostA = (float*) malloc(size);
hostB = (float*) malloc(size);
hostC = (float*) malloc(size);
// Initialize host vectors with random floats
for (int idx = 0; idx < numElements; idx++){
hostA[idx] = randomFloat();
hostB[idx] = randomFloat();
}
// Allocate memory for device vectors
cudaMalloc((void**)&deviceA, size);
cudaMalloc((void**)&deviceB, size);
cudaMalloc((void**)&deviceC, size);
// Copy host vectors to device
cudaMemcpy(deviceA, hostA, size, cudaMemcpyHostToDevice);
cudaMemcpy(deviceB, hostB, size, cudaMemcpyHostToDevice);
// Define the number of threads per block and the number of blocks per grid
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
// Launch the vector multiplication kernel
vectorHadamard<<<blocksPerGrid, threadsPerBlock>>>(deviceA, deviceB, deviceC, numElements);
// Copy the result vector from device to host
cudaMemcpy(hostC, deviceC, size, cudaMemcpyDeviceToHost);
// Print the results of the multiplication
for (int idx = 0; idx < numElements; idx++){
std::cout << hostA[idx] << " * " << hostB[idx] << " = " << hostC[idx] << std::endl;
}
// Free the memory allocated for host vectors
free(hostA);
free(hostB);
free(hostC);
// Free the memory allocated for device vectors
cudaFree(deviceA);
cudaFree(deviceB);
cudaFree(deviceC);
}
03. Vector Dot Product¶
- The dot product of two \(n\)-dimensional vectors \(\mathbf{a}\) and \(\mathbf{b}\) multiplies matching pairs and sums everything into a single scalar,
- Geometrically, \(\mathbf{a} \cdot \mathbf{b} = \|\mathbf{a}\| \|\mathbf{b}\| \cos\theta\), measuring the cosine of the angle between the two vectors scaled by their magnitudes. It is commutative, distributive, and linear, and powers orthogonality tests (\(\mathbf{a} \cdot \mathbf{b} = 0\)), vector projections, physical work calculations, matrix multiplication, and transformer attention.
- Unlike Tutorials 01 and 02, this operation is a parallel reduction (many inputs collapsing into one output). If hundreds of threads tried to execute
*c += a[idx] * b[idx]at once, concurrent read-modify-write operations would overwrite one another in a classic race condition. - To stay race-free, each thread computes its own element product
a[idx] * b[idx]and commits it into*cusingatomicAdd(c, a[idx] * b[idx]), which guarantees that only one thread updates the shared memory address at a time. - Watch out for two production realities with global
atomicAdd. First,cudaMallocdoes not zero device memory, so always callcudaMemset(deviceC, 0, sizeof(float))before an accumulation kernel in production code so stale bytes never leak into the sum. Second, having every single thread contend on one global address serialises memory traffic at scale; high-performance kernels perform a shared-memory tree reduction inside each block (halving active threads at each step with__syncthreads(), or using warp shuffles) and emit only oneatomicAddper block.
Source file 03.vectorDot.cu. Compile and run with nvcc 03.vectorDot.cu -o vectorDot && ./vectorDot.
// Include necessary libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
// CUDA kernel function to compute the dot product of two vectors
__global__ void vectorDot(const float *a, const float *b, float *c, int numElements) {
// Calculate the unique index for the thread
int idx = blockDim.x * blockIdx.x + threadIdx.x;
// Check if index is within the range of elements
if (idx < numElements){
// Perform the multiplication and add to the result
atomicAdd(c, a[idx] * b[idx]);
}
}
// Function to generate a random float
float randomFloat(int randMax = 1000){
// Return a random float between 0 and 1
return static_cast<float>(rand()) / static_cast<float>(randMax);
}
// Main function
int main(){
// Seed the random number generator
srand(time(0));
// Define the number of elements in the vectors
int numElements = 300;
// Calculate the size of the vectors in bytes
size_t size = numElements * sizeof(float);
// Declare pointers for host and device vectors
float *hostA, *hostB, *hostC;
float *deviceA, *deviceB, *deviceC;
// Allocate memory for host vectors
hostA = (float*) malloc(size);
hostB = (float*) malloc(size);
hostC = (float*) malloc(sizeof(float)); // Only need space for one float for the result
// Initialize host vectors with random floats
for (int idx = 0; idx < numElements; idx++){
hostA[idx] = randomFloat();
hostB[idx] = randomFloat();
}
// Allocate memory for device vectors
cudaMalloc((void**)&deviceA, size);
cudaMalloc((void**)&deviceB, size);
cudaMalloc((void**)&deviceC, sizeof(float)); // Only need space for one float for the result
// Copy host vectors to device
cudaMemcpy(deviceA, hostA, size, cudaMemcpyHostToDevice);
cudaMemcpy(deviceB, hostB, size, cudaMemcpyHostToDevice);
// Define the number of threads per block and the number of blocks per grid
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
// Launch the vector dot product kernel
vectorDot<<<blocksPerGrid, threadsPerBlock>>>(deviceA, deviceB, deviceC, numElements);
// Copy the result from device to host
cudaMemcpy(hostC, deviceC, sizeof(float), cudaMemcpyDeviceToHost);
// Print the result of the dot product
std::cout << "Dot product: " << *hostC << std::endl;
// Free the memory allocated for host vectors
free(hostA);
free(hostB);
free(hostC);
// Free the memory allocated for device vectors
cudaFree(deviceA);
cudaFree(deviceB);
cudaFree(deviceC);
}
04. Vector \(L_p\) Norm¶
- Comparing scalars like \(10 > 5\) is trivial, whereas quantifying the overall size of a vector requires a norm. The familiar Euclidean (\(L_2\)) norm measures straight-line distance from the origin \((0, 0, \dots, 0)\) to the point \(\mathbf{v}\),
- Generalising the exponent to any \(p \ge 1\) gives the generic \(L_p\) norm implemented here,
- The parallelisation splits work cleanly between GPU and CPU. The GPU handles the heavy \(O(n)\) reduction (raising every element to the \(p\)-th power and accumulating into
*normwithatomicAdd), and once the single scalar returns to the host, the CPU computes the cheap \(O(1)\) rootpow(*hostNorm, 1.0/p). - Watch out for three practical improvements when taking this beyond a teaching example. Zero
devicetNormwithcudaMemsetbefore launchingvectorNorm, wrapvector[idx]infabsf(...)so odd values of \(p\) (like the \(L_1\) norm) work properly on negative numbers, and for the common \(p = 2\) case replacepow(v, 2)withv * vto avoid an expensive floating-point power call.
Source file 04.vectorNorm.cu. Compile and run with nvcc 04.vectorNorm.cu -o vectorNorm && ./vectorNorm.
// Include necessary libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void vectorNorm(const float *vector, float *norm, int p, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
// Perform the multiplication and add to the result
atomicAdd(norm, pow(vector[idx], p));
}
}
float randomFloat(int randMax = 1000){
return static_cast<float>(rand()) / static_cast<float>(randMax);
}
int main(){
// Initialize pointer for host and device vectors
srand(time(0));
int p = 2;
int numElements = 300;
size_t size = numElements * sizeof(float);
float *hostVector, *hostNorm;
float *deviceVector, *devicetNorm;
// Allocate memory for host vectors
hostVector = (float*) malloc(size);
hostNorm = (float*) malloc(sizeof(float)); // Only need space for one float for the result
// Initialize host vectors with random floats
for (int idx = 0; idx < numElements; idx++){
hostVector[idx] = randomFloat();
}
// Allocate memory for device vectors
cudaMalloc((void**)&deviceVector, size);
cudaMalloc((void**)&devicetNorm, sizeof(float)); // Only need space for one float for the result
// Copy host vectors to device
cudaMemcpy(deviceVector, hostVector, size, cudaMemcpyHostToDevice);
// Define the number of threads per block and the number of blocks per grid
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
// Launch the vector vector norm kernel
vectorNorm<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, devicetNorm, p, numElements);
// Copy the result from device to host
cudaMemcpy(hostNorm, devicetNorm, sizeof(float), cudaMemcpyDeviceToHost);
// take the square root of the result
*hostNorm = pow(*hostNorm, 1.0/p);
// Print the result of the vector norm
std::cout << "Vector Norm: " << *hostNorm << std::endl;
// Free the memory allocated for host vectors
free(hostVector);
free(hostNorm);
// Free the memory allocated for device vectors
cudaFree(deviceVector);
cudaFree(devicetNorm);
}
05. Cosine Similarity¶
- Cosine similarity measures how closely two non-zero vectors align in direction, independent of their lengths, by taking the cosine of the angle \(\theta\) between them,
- Values lie in \([-1, 1]\), where \(1\) means identical direction, \(0\) means orthogonal (90 degrees apart, no directional similarity), and \(-1\) means diametrically opposite. Normalising by the two magnitudes makes cosine similarity the go-to metric in natural language processing and semantic retrieval, where long and short documents about the same topic should still score close to \(1\).
- This tutorial demonstrates composing multiple modular kernels in sequence (
dotProduct, thenvectorMagnitudefor \(\mathbf{a}\), thenvectorMagnitudefor \(\mathbf{b}\)). Because all three launches target the default CUDA stream, the GPU runs them in order andcudaMemcpyDeviceToHostsynchronises before the CPU finishes the square roots and final division. - Watch out for memory traffic and zero-initialisation. Remember to zero
deviceDotProduct,deviceMagnitudeA, anddeviceMagnitudeBwithcudaMemsetin production before launch, and guard against division by zero if either vector has zero norm. Notice too that launching three separate kernels reads both input vectors twice from global memory; fusing all three accumulations into a single kernel pass (paired with shared-memory block reductions) halves memory bandwidth usage and removes two launch overheads.
Source file 05.vectorSimilarity.cu. Compile and run with nvcc 05.vectorSimilarity.cu -o vectorSimilarity && ./vectorSimilarity.
// Include necessary libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void dotProduct(const float *a, const float *b, float *c, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(c, a[idx] * b[idx]);
}
}
__global__ void vectorMagnitude(const float *vector, float *magnitude, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(magnitude, vector[idx] * vector[idx]);
}
}
float randomFloat(int randMax = 1000){
return static_cast<float>(rand()) / static_cast<float>(randMax);
}
int main(){
srand(time(0));
int numElements = 300;
size_t size = numElements * sizeof(float);
float *hostVectorA, *hostVectorB, *hostDotProduct, *hostMagnitudeA, *hostMagnitudeB;
float *deviceVectorA, *deviceVectorB, *deviceDotProduct, *deviceMagnitudeA, *deviceMagnitudeB;
hostVectorA = (float*) malloc(size);
hostVectorB = (float*) malloc(size);
hostDotProduct = (float*) malloc(sizeof(float));
hostMagnitudeA = (float*) malloc(sizeof(float));
hostMagnitudeB = (float*) malloc(sizeof(float));
for (int idx = 0; idx < numElements; idx++){
hostVectorA[idx] = randomFloat();
hostVectorB[idx] = randomFloat();
}
cudaMalloc((void**)&deviceVectorA, size);
cudaMalloc((void**)&deviceVectorB, size);
cudaMalloc((void**)&deviceDotProduct, sizeof(float));
cudaMalloc((void**)&deviceMagnitudeA, sizeof(float));
cudaMalloc((void**)&deviceMagnitudeB, sizeof(float));
cudaMemcpy(deviceVectorA, hostVectorA, size, cudaMemcpyHostToDevice);
cudaMemcpy(deviceVectorB, hostVectorB, size, cudaMemcpyHostToDevice);
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
dotProduct<<<blocksPerGrid, threadsPerBlock>>>(deviceVectorA, deviceVectorB, deviceDotProduct, numElements);
vectorMagnitude<<<blocksPerGrid, threadsPerBlock>>>(deviceVectorA, deviceMagnitudeA, numElements);
vectorMagnitude<<<blocksPerGrid, threadsPerBlock>>>(deviceVectorB, deviceMagnitudeB, numElements);
cudaMemcpy(hostDotProduct, deviceDotProduct, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(hostMagnitudeA, deviceMagnitudeA, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(hostMagnitudeB, deviceMagnitudeB, sizeof(float), cudaMemcpyDeviceToHost);
*hostMagnitudeA = sqrt(*hostMagnitudeA);
*hostMagnitudeB = sqrt(*hostMagnitudeB);
float cosineSimilarity = *hostDotProduct / (*hostMagnitudeA * *hostMagnitudeB);
std::cout << "Cosine Similarity: " << cosineSimilarity << std::endl;
free(hostVectorA);
free(hostVectorB);
free(hostDotProduct);
free(hostMagnitudeA);
free(hostMagnitudeB);
cudaFree(deviceVectorA);
cudaFree(deviceVectorB);
cudaFree(deviceDotProduct);
cudaFree(deviceMagnitudeA);
cudaFree(deviceMagnitudeB);
}
06. Pearson Correlation Coefficient¶
- The Pearson correlation coefficient \(r\) measures the linear relationship between two variables \(\mathbf{x}\) and \(\mathbf{y}\), returning \(-1\) for a perfect negative linear relationship, \(0\) for no linear correlation, and \(+1\) for a perfect positive linear relationship,
- While cosine similarity compares raw angles from the origin, Pearson correlation first centres both vectors by subtracting their means \(\bar{x}\) and \(\bar{y}\), measuring how the two variables move together around their respective averages. Geometrically, Pearson \(r\) is simply the cosine similarity of the two mean-centred vectors.
- The parallelisation strategy blends CPU and GPU work cleanly. The host computes
meanAandmeanB, passes them by value into three sub-kernels (calculateNumeratorand two launches ofcalculateDenominator), retrieves the three reduced sums, and combines them on the CPU. - Watch out for the classic trade-off between modularity and kernel launch overhead. Splitting a complex formula into small sub-kernels makes learning and debugging effortless, yet every kernel launch adds microsecond-level overhead and extra reads from global memory. For large production datasets, fuse the numerator and both denominators into a single kernel pass (and always zero device accumulators with
cudaMemsetbeforeatomicAdd, plus guard against zero-variance inputs).
Source file 06.vectorCorrelation.cu. Compile and run with nvcc 06.vectorCorrelation.cu -o vectorCorrelation && ./vectorCorrelation.
// Include necessary libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void calculateNumerator(const float *a, const float *b, float *numerator, float meanA, float meanB, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(numerator, (a[idx] - meanA) * (b[idx] - meanB));
}
}
__global__ void calculateDenominator(const float *vector, float *denominator, float meanB, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(denominator, (vector[idx] - meanB) * (vector[idx] - meanB));
}
}
float randomFloat(int randMax = 1000){
return static_cast<float>(rand()) / static_cast<float>(randMax);
}
float calculateMean(float* vector, int numElements){
float sum = 0;
for(int i = 0; i < numElements; i++){
sum += vector[i];
}
return sum / numElements;
}
int main(){
srand(time(0));
int numElements = 300;
size_t size = numElements * sizeof(float);
float *hostVectorA, *hostVectorB, *hostNumerator, *hostDenominatorA, *hostDenominatorB;
float *deviceVectorA, *deviceVectorB, *deviceNumerator, *deviceDenominatorA, *deviceDenominatorB;
hostVectorA = (float*) malloc(size);
hostVectorB = (float*) malloc(size);
hostNumerator = (float*) malloc(sizeof(float));
hostDenominatorA = (float*) malloc(sizeof(float));
hostDenominatorB = (float*) malloc(sizeof(float));
for (int idx = 0; idx < numElements; idx++){
hostVectorA[idx] = randomFloat();
hostVectorB[idx] = randomFloat();
}
float meanA = calculateMean(hostVectorA, numElements);
float meanB = calculateMean(hostVectorB, numElements);
cudaMalloc((void**)&deviceVectorA, size);
cudaMalloc((void**)&deviceVectorB, size);
cudaMalloc((void**)&deviceNumerator, sizeof(float));
cudaMalloc((void**)&deviceDenominatorA, sizeof(float));
cudaMalloc((void**)&deviceDenominatorB, sizeof(float));
cudaMemcpy(deviceVectorA, hostVectorA, size, cudaMemcpyHostToDevice);
cudaMemcpy(deviceVectorB, hostVectorB, size, cudaMemcpyHostToDevice);
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
calculateNumerator<<<blocksPerGrid, threadsPerBlock>>>(deviceVectorA, deviceVectorB, deviceNumerator, meanA, meanB, numElements);
calculateDenominator<<<blocksPerGrid, threadsPerBlock>>>(deviceVectorA, deviceDenominatorA, meanA, numElements);
calculateDenominator<<<blocksPerGrid, threadsPerBlock>>>(deviceVectorB, deviceDenominatorB, meanB, numElements);
cudaMemcpy(hostNumerator, deviceNumerator, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(hostDenominatorA, deviceDenominatorA, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(hostDenominatorB, deviceDenominatorB, sizeof(float), cudaMemcpyDeviceToHost);
float correlationCoefficient = *hostNumerator / sqrt(*hostDenominatorA * *hostDenominatorB);
std::cout << "Correlation Coefficient: " << correlationCoefficient << std::endl;
free(hostVectorA);
free(hostVectorB);
free(hostNumerator);
free(hostDenominatorA);
free(hostDenominatorB);
cudaFree(deviceVectorA);
cudaFree(deviceVectorB);
cudaFree(deviceNumerator);
cudaFree(deviceDenominatorA);
cudaFree(deviceDenominatorB);
}
07. Vector Maximum with Atomic Compare-and-Swap¶
- Finding the maximum value in a vector is another fundamental reduction,
- CUDA's built-in
atomicMaxsupports integer types only, not 32-bitfloat. To support floating-point maximums safely across thousands of concurrent threads, this tutorial writes a custom__device__overload aroundatomicCAS(Atomic Compare-And-Swap). - The
atomicCAS(address, compare, val)intrinsic compares the current 32-bit word ataddressagainstcompare; if they match, it writesvalatomically without interruption and always returns the previous value. By reinterpreting the float pointer asint*and converting bit patterns with__int_as_floatand__float_as_int, thedo ... while (assumed != old)loop retries whenever another thread beats it to the update, guaranteeing a race-free floating-point maximum. - Watch out for three important engineering details in this million-element example. First, the host initialisation loop writes
idx <= numElementsinstead ofidx < numElements, stepping one float past the allocated array (tighten that condition to<in your own projects). Second,deviceMaxshould be initialised to-FLT_MAX(orhostVector[0]) before launch so negative-valued vectors still return the true maximum. Third, contending on one globalatomicCASspin-loop across 1,000,000 threads is slow; real-world kernels first perform a shared-memory tree reduction (halving stride \(s = \text{blockDim.x}/2, \text{blockDim.x}/4, \dots, 1\) with__syncthreads()) so only thread0of each block callsatomicMax.
Source file 07.vectorMax.cu. Compile and run with nvcc 07.vectorMax.cu -o vectorMax && ./vectorMax.
// Include necessary libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__device__ float atomicMax(float* address, float val)
{
int* address_as_i = (int*) address;
int old = *address_as_i, assumed;
do {
assumed = old;
old = ::atomicCAS(address_as_i, assumed,
__float_as_int(::fmaxf(val, __int_as_float(assumed))));
} while (assumed != old);
return __int_as_float(old);
}
__global__ void vectorMax(const float *vector, float *max, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicMax(max, vector[idx]);
}
}
int main(){
srand(time(0));
int numElements = 1000000;
size_t size = numElements * sizeof(float);
float *hostVector, *deviceVector;
float *hostMax, *deviceMax;
hostVector = (float*) malloc(size);
hostMax = (float*) malloc(sizeof(float));
// Initialise a random vector of distribution
for (int idx = 0; idx <= numElements; idx++){
hostVector[idx] = 1.0f * idx;
}
// Allocate device vector and variables
cudaMalloc((void**)&deviceVector, size);
cudaMalloc((void**)&deviceMax, sizeof(float));
// Copy host vector to device
cudaMemcpy(deviceVector, hostVector, size, cudaMemcpyHostToDevice);
// Define the number of threads per block and the number of blocks per grid
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
// Launch the vector max kernel
vectorMax<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceMax, numElements);
cudaDeviceSynchronize();
// Copy the result from device to host and print
cudaMemcpy(hostMax, deviceMax, sizeof(float), cudaMemcpyDeviceToHost);
printf("Max: %f\n", *hostMax);
// Free the memory allocated for host
free(hostVector);
free(hostMax);
// Free the memory allocated for device
cudaFree(deviceVector);
cudaFree(deviceMax);
}
08. Vector Statistics¶
- Even rich statistical equations decompose cleanly into small, parallel GPU building blocks. This tutorial brings seven foundational descriptive statistics together in one program.
- Mean and standard deviation summarise central tendency and spread around the centre,
- Z-score normalisation rescales every element so the vector has mean \(0\) and standard deviation \(1\), bringing measurements from different units onto a single comparable scale,
- Skewness and kurtosis capture distribution shape beyond mean and spread. Skewness measures asymmetry (positive means a longer right tail, negative means a longer left tail; when data are heavily skewed, as in finance or economics, the median often represents a typical value better than the mean). Kurtosis measures tailedness and peakedness (higher kurtosis indicates heavier tails and a sharper peak),
- Sample variance and sample covariance quantify spread and joint linear co-movement using Bessel's correction \(n - 1\),
- The parallelisation strategy chains six kernels sequentially with
cudaDeviceSynchronize()between dependent stages. Notice howvectorSkewnessKurtosisfuses both third and fourth standardised moments into a single pass so each thread only computes(vector[idx] - mean) / stdonce. - Watch out for four subtle bugs in this teaching pipeline that make excellent debugging practice if you harden the code for real datasets. First,
deviceMeanholds the raw sum on the GPU (only*hostMeanwas divided bynumElements), yetvectorStdreads*deviceMeandirectly on the device instead of receiving*hostMeanby value. Second,vectorNormalizationoverwritesdeviceVectorin place before skewness, kurtosis, variance, and covariance run (whiledeviceNormalizedstays unpopulated). Third,deviceKurtosisis never copied back tohostKurtosis, and the final divisions bynumElements(skewness and kurtosis) andnumElements - 1(sample variance and covariance) are omitted before printing. Fourth, all scalaratomicAddbuffers should be zeroed withcudaMemsetprior to launch.
Source file 08.vectorStatistics.cu. Compile and run with nvcc 08.vectorStatistics.cu -o vectorStatistics && ./vectorStatistics.
// Include necessary libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void vectorMean(const float *vector, float *mean, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(mean, vector[idx]);
}
}
__global__ void vectorStd(const float *vector, float *std, float *mean, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(std, pow(vector[idx] - *mean, 2));
}
}
__global__ void vectorNormalization(float *vector, float mean, float std, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
vector[idx] = (vector[idx] - mean) / std;
}
}
__global__ void vectorSkewnessKurtosis(const float *vector, float *skewness, float *kurtosis, float mean, float std, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
float standardized = (vector[idx] - mean) / std;
atomicAdd(skewness, pow(standardized, 3));
atomicAdd(kurtosis, pow(standardized, 4));
}
}
__global__ void vectorVariance(const float *vector, float *variance, float mean, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(variance, pow(vector[idx] - mean, 2));
}
}
__global__ void vectorCovariance(const float *vectorX, const float *vectorY, float *covariance, float meanX, float meanY, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(covariance, (vectorX[idx] - meanX) * (vectorY[idx] - meanY));
}
}
float randomFloat(int randMax = 1000){
return static_cast<float>(rand()) / static_cast<float>(randMax);
}
int main(){
srand(time(0));
int numElements = 300;
size_t size = numElements * sizeof(float);
float *hostVector, *deviceVector;
float *hostNormalized, *deviceNormalized;
float *hostMean, *deviceMean;
float *hostStd, *deviceStd;
float *hostSkewness, *deviceSkewness;
float *hostKurtosis, *deviceKurtosis;
float *hostVariance, *deviceVariance;
float *hostCovariance, *deviceCovariance;
hostVector = (float*) malloc(size);
hostNormalized = (float*) malloc(size);
hostMean = (float*) malloc(sizeof(float));
hostStd = (float*) malloc(sizeof(float));
hostSkewness = (float*) malloc(sizeof(float));
hostKurtosis = (float*) malloc(sizeof(float));
hostVariance = (float*) malloc(sizeof(float));
hostCovariance = (float*) malloc(sizeof(float));
// Initialise a random vector of distribution
for (int idx = 0; idx < numElements; idx++){
hostVector[idx] = randomFloat();
}
// Allocate device vector and variables
cudaMalloc((void**)&deviceVector, size);
cudaMalloc((void**)&deviceNormalized, size);
cudaMalloc((void**)&deviceMean, sizeof(float));
cudaMalloc((void**)&deviceStd, sizeof(float));
cudaMalloc((void**)&deviceSkewness, sizeof(float));
cudaMalloc((void**)&deviceKurtosis, sizeof(float));
cudaMalloc((void**)&deviceVariance, sizeof(float));
cudaMalloc((void**)&deviceCovariance, sizeof(float));
// Copy host vectors to device
cudaMemcpy(deviceVector, hostVector, size, cudaMemcpyHostToDevice);
// Define the number of threads per block and the number of blocks per grid
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
// Launch the vector mean kernel
vectorMean<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceMean, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostMean, deviceMean, sizeof(float), cudaMemcpyDeviceToHost);
*hostMean /= numElements;
// Launch the vector std kernel
vectorStd<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceStd, deviceMean, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostStd, deviceStd, sizeof(float), cudaMemcpyDeviceToHost);
*hostStd = sqrt(*hostStd / numElements);
// Launch the vector normalization kernel
vectorNormalization<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, *hostMean, *hostStd, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostNormalized, deviceVector, size, cudaMemcpyDeviceToHost);
// Launch the vector skewness and kurtosis kernel
vectorSkewnessKurtosis<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceSkewness, deviceKurtosis, *hostMean, *hostStd, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostSkewness, deviceSkewness, sizeof(float), cudaMemcpyDeviceToHost);
// Launch the vector variance kernel
vectorVariance<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceVariance, *hostMean, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostVariance, deviceVariance, sizeof(float), cudaMemcpyDeviceToHost);
// Launch the vector covariance kernel
vectorCovariance<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceNormalized, deviceCovariance, *hostMean, *hostMean, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostCovariance, deviceCovariance, sizeof(float), cudaMemcpyDeviceToHost);
// Print the results
std::cout << "Mean: " << *hostMean << std::endl;
std::cout << "Standard Deviation: " << *hostStd << std::endl;
std::cout << "Skewness: " << *hostSkewness << std::endl;
std::cout << "Kurtosis: " << *hostKurtosis << std::endl;
std::cout << "Variance: " << *hostVariance << std::endl;
std::cout << "Covariance: " << *hostCovariance << std::endl;
// Free the memory allocated for host vectors
free(hostVector);
free(hostNormalized);
free(hostMean);
free(hostStd);
free(hostSkewness);
free(hostKurtosis);
free(hostVariance);
free(hostCovariance);
// Free the memory allocated for device vectors
cudaFree(deviceVector);
cudaFree(deviceNormalized);
cudaFree(deviceMean);
cudaFree(deviceStd);
cudaFree(deviceSkewness);
cudaFree(deviceKurtosis);
cudaFree(deviceVariance);
cudaFree(deviceCovariance);
}
09. Fitting a Gaussian Distribution¶
- The Gaussian (bell-curve) function models countless natural and statistical phenomena, scaled by a peak amplitude \(A\), centred at mean \(\mu\), and given width by standard deviation \(\sigma\),
- Do not confuse this general unnormalised Gaussian curve with the standard normal probability density function \(\frac{1}{\sqrt{2\pi}} \exp(-x^2 / 2)\), which is the special case with \(\mu = 0\), \(\sigma = 1\), and total area normalised to \(1\). Here the peak height \(A\) is taken from the vector's own maximum value.
- This tutorial stitches together building blocks from earlier files into a complete four-kernel pipeline. Three reduction kernels (
vectorMean,vectorStd, and theatomicCAS-basedvectorMax) summarise the dataset, and then an embarrassingly parallel map kernel (vectorGaussian) evaluates the Gaussian curve at every point simultaneously. - Watch out for the same device-side mean caveat seen in Tutorial 08 (
vectorStdreceivesdeviceMean, which still holds the raw sum before host division, so passing*hostMeanby value gives the true standard deviation, and zeroing the scalar buffers withcudaMemsetprevents stale memory). InsidevectorGaussian, replacingpow(x, 2)withdiff * diffand precomputing-1.0f / (2.0f * std * std)once on the host also trims expensive floating-point instructions from every thread.
Source file 09.vectorGaussian.cu. Compile and run with nvcc 09.vectorGaussian.cu -o vectorGaussian && ./vectorGaussian.
// Include necessary libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void vectorMean(const float *vector, float *mean, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(mean, vector[idx]);
}
}
__global__ void vectorStd(const float *vector, float *std, float *mean, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicAdd(std, pow(vector[idx] - *mean, 2));
}
}
__device__ float atomicMax(float* address, float val)
{
int* address_as_i = (int*) address;
int old = *address_as_i, assumed;
do {
assumed = old;
old = ::atomicCAS(address_as_i, assumed,
__float_as_int(::fmaxf(val, __int_as_float(assumed))));
} while (assumed != old);
return __int_as_float(old);
}
__global__ void vectorMax(const float *vector, float *max, int numElements){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
atomicMax(max, vector[idx]);
}
}
__global__ void vectorGaussian(const float *vector,
float *gaussian,
int numElements,
float mean,
float std,
float max){
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx < numElements){
gaussian[idx] = max * exp(-pow(vector[idx] - mean, 2) / (2 * pow(std, 2)));
}
}
float randomFloat(int randMax = 1000){
return static_cast<float>(rand()) / static_cast<float>(randMax);
}
int main(){
srand(time(0));
int numElements = 300;
size_t size = numElements * sizeof(float);
float *hostVector, *deviceVector;
float *hostMean, *deviceMean;
float *hostStd, *deviceStd;
float *hostMax, *deviceMax;
float *hostGaussian, *deviceGaussian;
hostVector = (float*) malloc(size);
hostMean = (float*) malloc(sizeof(float));
hostStd = (float*) malloc(sizeof(float));
hostMax = (float*) malloc(sizeof(float));
hostGaussian = (float*) malloc(size);
// Initialise a random vector of distribution
for (int idx = 0; idx < numElements; idx++){
hostVector[idx] = randomFloat();
}
// Allocate device vector and variables
cudaMalloc((void**)&deviceVector, size);
cudaMalloc((void**)&deviceMean, sizeof(float));
cudaMalloc((void**)&deviceStd, sizeof(float));
cudaMalloc((void**)&deviceMax, sizeof(float));
cudaMalloc((void**)&deviceGaussian, size);
// Copy host vectors to device
cudaMemcpy(deviceVector, hostVector, size, cudaMemcpyHostToDevice);
// Define the number of threads per block and the number of blocks per grid
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
// Launch the vector mean kernel
vectorMean<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceMean, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostMean, deviceMean, sizeof(float), cudaMemcpyDeviceToHost);
*hostMean /= numElements;
// Launch the vector std kernel
vectorStd<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceStd, deviceMean, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostStd, deviceStd, sizeof(float), cudaMemcpyDeviceToHost);
*hostStd = sqrt(*hostStd / numElements);
// Launch the vector max kernel
vectorMax<<<blocksPerGrid, threadsPerBlock>>>(deviceVector, deviceMax, numElements);
cudaDeviceSynchronize();
cudaMemcpy(hostMax, deviceMax, sizeof(float), cudaMemcpyDeviceToHost);
// Launch the vector gaussian kernel
vectorGaussian<<<blocksPerGrid, threadsPerBlock>>>(
deviceVector,
deviceGaussian,
numElements,
*hostMean,
*hostStd,
*hostMax
);
// Copy the result from device to host
cudaMemcpy(hostGaussian, deviceGaussian, size, cudaMemcpyDeviceToHost);
// Print the results of the Gaussian function
for (int idx = 0; idx < numElements; idx++){
std::cout << "Gaussian function value at x = " << hostVector[idx] << ": " << hostGaussian[idx] << std::endl;
}
// Free the memory allocated for host vectors
free(hostVector);
free(hostMean);
free(hostStd);
free(hostMax);
free(hostGaussian);
// Free the memory allocated for device vectors
cudaFree(deviceVector);
cudaFree(deviceMean);
cudaFree(deviceStd);
cudaFree(deviceMax);
cudaFree(deviceGaussian);
}
10. Parallel Numerical Calculus¶
- The final tutorial moves from linear algebra and statistics into parallel numerical calculus, evaluating four classic operations over 1,000 samples of \(f(x_i) = \sin(i h)\) with grid spacing \(h = 0.01\).
- Central finite-difference derivative approximates the tangent slope at each interior point using both immediate neighbours \(x + h\) and \(x - h\), becoming more accurate as \(h \to 0\). Feeding the derivative output back into the same kernel yields second and higher-order derivatives,
- Trapezoidal local integral estimates the area of each narrow strip of width \(h\) beneath the curve between \(x - h\) and \(x\),
- First-order linearisation approximates a nonlinear function near a base point \(x_0\) with its tangent line, which is accurate whenever \(x\) stays close to \(x_0\),
- Newton-Raphson root finding iterates toward a zero where a function crosses the \(x\)-axis. Here each thread runs 10 iterations solving \(\sin(x) - x = 0\) via
Applying Newton-Raphson to a function's derivative \(f'(x) = 0\) locates stationary points (local minima and maxima), bridging numerical calculus directly to second-order optimisation.
- The parallelisation introduces 1D stencil memory access (input[idx - 1], input[idx], input[idx + 1]) alongside independent per-thread iterative loops. Because stencil kernels read neighbours on either side, the guard tightens to if (idx > 0 && idx < numElements - 1) so boundary threads never read out of bounds.
- Watch out for four practical nuances when extending these kernels. First, indices 0 and numElements - 1 are skipped by the interior stencil guard, so those boundary slots stay uninitialised unless handled with one-sided forward and backward differences. Second, calculateIntegral outputs each individual trapezoidal slice rather than the cumulative definite integral (summing all strips requires a parallel reduction or a prefix sum scan). Third, calculateLinearization currently sets x0 = idx * h, which makes (x0 - idx * h) zero; evaluate at a shifted query point \(x \neq x_0\) to see the linear approximation in action. Fourth, in calculateNewtonRaphson, \(\cos(x_0) - 1\) approaches \(0\) near \(x_0 = 0\), so production solvers check for a tiny denominator before dividing (and remember to free hostOutputNewtonRaphson and deviceOutputNewtonRaphson at shutdown).
Source file 10.vectorCalculus.cu. Compile and run with nvcc 10.vectorCalculus.cu -o vectorCalculus && ./vectorCalculus.
#include <iostream>
#include <cmath>
#include <cuda_runtime.h>
__global__ void calculateDerivative(float* input, float* output, float h, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx > 0 && idx < numElements - 1) {
output[idx] = (input[idx + 1] - input[idx - 1]) / (2 * h);
}
}
__global__ void calculateIntegral(float* input, float* output, float h, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx > 0 && idx < numElements - 1) {
output[idx] = h * (input[idx - 1] + input[idx]) / 2;
}
}
__global__ void calculateLinearization(float* input, float* derivative, float* output, float h, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx > 0 && idx < numElements - 1) {
float x0 = idx * h;
output[idx] = input[idx] + derivative[idx] * (x0 - idx * h);
}
}
__global__ void calculateNewtonRaphson(float* input, float* output, float h, int numElements) {
int idx = blockDim.x * blockIdx.x + threadIdx.x;
if (idx > 0 && idx < numElements - 1) {
float x0 = input[idx];
for (int i = 0; i < 10; i++) { // Perform 10 iterations
x0 = x0 - (sinf(x0) - x0) / (cosf(x0) - 1);
}
output[idx] = x0;
}
}
int main() {
int numElements = 1000;
float h = 0.01f;
size_t size = numElements * sizeof(float);
float* hostInput = (float*)malloc(size);
float* hostOutputDerivative = (float*)malloc(size);
float* hostOutputIntegral = (float*)malloc(size);
float* hostOutputLinearization = (float*)malloc(size);
float* hostOutputNewtonRaphson = (float*)malloc(size);
for (int i = 0; i < numElements; i++) {
hostInput[i] = sinf(i * h);
}
float* deviceInput;
float* deviceOutputDerivative;
float* deviceOutputIntegral;
float* deviceOutputLinearization;
float* deviceOutputNewtonRaphson;
cudaMalloc((void**)&deviceInput, size);
cudaMalloc((void**)&deviceOutputDerivative, size);
cudaMalloc((void**)&deviceOutputIntegral, size);
cudaMalloc((void**)&deviceOutputLinearization, size);
cudaMalloc((void**)&deviceOutputNewtonRaphson, size);
cudaMemcpy(deviceInput, hostInput, size, cudaMemcpyHostToDevice);
int threadsPerBlock = 256;
int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
calculateDerivative<<<blocksPerGrid, threadsPerBlock>>>(deviceInput, deviceOutputDerivative, h, numElements);
calculateIntegral<<<blocksPerGrid, threadsPerBlock>>>(deviceInput, deviceOutputIntegral, h, numElements);
calculateLinearization<<<blocksPerGrid, threadsPerBlock>>>(deviceInput, deviceOutputDerivative, deviceOutputLinearization, h, numElements);
calculateNewtonRaphson<<<blocksPerGrid, threadsPerBlock>>>(deviceInput, deviceOutputNewtonRaphson, h, numElements);
cudaMemcpy(hostOutputDerivative, deviceOutputDerivative, size, cudaMemcpyDeviceToHost);
cudaMemcpy(hostOutputIntegral, deviceOutputIntegral, size, cudaMemcpyDeviceToHost);
cudaMemcpy(hostOutputLinearization, deviceOutputLinearization, size, cudaMemcpyDeviceToHost);
cudaMemcpy(hostOutputNewtonRaphson, deviceOutputNewtonRaphson, size, cudaMemcpyDeviceToHost);
// Print some values for verification
for (int i = 0; i < 10; i++) {
std::cout << "Sine Output: " << hostInput[i] << std::endl;
std::cout << "Derivative: " << hostOutputDerivative[i] << std::endl;
std::cout << "Integral: " << hostOutputIntegral[i] << std::endl;
std::cout << "Linearization: " << hostOutputLinearization[i] << std::endl;
std::cout << "Newton-Raphson: " << hostOutputNewtonRaphson[i] << "\n" << std::endl;
}
free(hostInput);
free(hostOutputDerivative);
free(hostOutputIntegral);
free(hostOutputLinearization);
cudaFree(deviceInput);
cudaFree(deviceOutputDerivative);
cudaFree(deviceOutputIntegral);
cudaFree(deviceOutputLinearization);
return 0;
}
Take-Home¶
- Three core parallel patterns cover most of scientific computing. Element-wise maps (Tutorials 01, 02, and 09), scalar reductions (Tutorials 03 through 08), and 1D neighbour stencils (Tutorial 10) form the backbone of linear algebra, statistics, and numerical solvers on GPUs.
- Always guard thread bounds and initialise reduction targets. Ceiling-divided grids routinely spawn extra trailing threads, and
cudaMallocleaves device memory uninitialised, so pairingif (idx < numElements)withcudaMemsetbefore any atomic accumulation prevents silent corruption. - Atomics guarantee correctness, while shared-memory reductions deliver speed.
atomicAddandatomicCASloops (for floating-pointatomicMax) eliminate race conditions with minimal code, whereas production kernels reduce partial results inside__shared__memory (or warp shuffles) first to avoid global memory contention. - Balance modular kernels against launch and bandwidth overhead. Breaking cosine similarity, Pearson correlation, and descriptive statistics into small kernels keeps the code readable, while fusing passes over the same arrays cuts global memory reads and kernel launch latency in performance-critical workloads.
- Keep scalar \(O(1)\) finishing steps on the CPU. Letting the GPU crush the \(O(n)\) parallel work and returning tiny scalars for final roots, divisions, or scaling avoids unnecessary single-thread kernel launches.