To access memory across NVLink-connected GPUs in a CUDA kernel, you can use Unified Memory or explicit memory management.
Unified Memory is a feature provided by CUDA that allows the host and all GPUs to access the same memoryaddress space. This means that you can allocate memory on the host and then access it from any GPU without needing to explicitly copy the data. When you access memory from a different GPU, the memory is automatically migrated to the target GPU if it's not already there.
Here's an example of how to use Unified Memory to access memory across NVLink-connected GPUs:
Allocate memory on the host using cudaMallocManaged(). This function allocates memory that is accessible from all GPUs and the host.
Launch a CUDA kernel on each GPU and access the memory using the pointer returned by cudaMallocManaged().
scss
__global__ void kernel(float* data) {
// Access the data array
int idx = threadIdx.x + blockIdx.x * blockDim.x;
if (idx < size) {
data[idx] = idx * 2.0f;
}
}
int numBlocks = (size + 255) / 256;
dim3 threadsPerBlock(256);
// Launch the kernel on each GPU
for (int i = 0; i < numGPUs; ++i) {
cudaSetDevice(i);
kernel<<<numBlocks, threadsPerBlock>>>(data);
}
Alternatively, you can use explicit memory management to transfer data between GPUs using cudaMemcpyAsync() or cudaMemcpyPeer(). This approach gives you more control over the memory transfers, but requires more code to manage the memory. Here's an example:
Allocate memory on each GPU using cudaMalloc().
c
float* data[numGPUs];
for (int i = 0; i < numGPUs; ++i) {
cudaSetDevice(i);
cudaMalloc(&data[i], size);
}
Launch a CUDA kernel on each GPU and access the memory using the pointer returned by cudaMalloc().
scss
__global__ void kernel(float* data) {
// Access the data array
int idx = threadIdx.x + blockIdx.x * blockDim.x;
if (idx < size) {
data[idx] = idx * 2.0f;
}
}
int numBlocks = (size + 255) / 256;
dim3 threadsPerBlock(256);
// Launch the kernel on each GPU
for (int i = 0; i < numGPUs; ++i) {
cudaSetDevice(i);
kernel<<<numBlocks, threadsPerBlock>>>(data[i]);
}
Use cudaMemcpyPeer() to transfer data between GPUs if necessary. This function allows you to copy memory between GPUs directly, without going through the host.
scss
// Copy data from GPU 0 to GPU 1
cudaMemcpyPeerAsync(data[1], 1, data[0], 0, size, cudaMemcpyDefault);
// Wait for the copy to complete
cudaDeviceSynchronize();
Note that using cudaMemcpyPeer() requires that the GPUs be connected by NVLink and that they have sufficient memory to accommodate the transfer.