Write a cuda kernel for radix sort
- User
Write a cuda kernel for radix sort
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Write a cuda kernel for radix sort
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a complete implementation of a radix sort kernel in CUDA. This implementation sorts 32-bit unsigned integers using a least-significant-digit (LSD) radix sort approach.
#include <cuda_runtime.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_BITS 4
#define NUM_BINS (1 << NUM_BITS) // 2^NUM_BITS
#define BLOCK_SIZE 256
// Kernel to count the number of elements in each bin
__global__ void countKernel(const unsigned int* input, unsigned int* counts,
unsigned int size, unsigned int shift) {
__shared__ unsigned int sCounts[NUM_BINS];
// Initialize shared memory counts to 0
if (threadIdx.x < NUM_BINS) {
sCounts[threadIdx.x] = 0;
}
__syncthreads();
// Each thread processes one element
unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < size) {
unsigned int bin = (input[idx] >> shift) & (NUM_BINS - 1);
atomicAdd(&sCounts[bin], 1);
}
__syncthreads();
// Write shared counts to global memory
if (threadIdx.x < NUM_BINS) {
atomicAdd(&counts[threadIdx.x], sCounts[threadIdx.x]);
}
}
// Kernel to compute prefix sums (scan) of the counts
__global__ void scanKernel(unsigned int* counts) {
extern __shared__ unsigned int sData[];
unsigned int tid = threadIdx.x;
unsigned int offset = 1;
// Load data into shared memory
sData[tid] = (tid > 0) ? counts[tid - 1] : 0;
__syncthreads();
// Perform parallel reduction
for (unsigned int d = 1; d < NUM_BINS; d *= 2) {
if (tid >= d) {
sData[tid] += sData[tid - d];
}
__syncthreads();
}
// Write results back to global memory
if (tid < NUM_BINS) {
counts[tid] = sData[tid];
}
}
// Kernel to reorder elements based on the prefix sums
__global__ void reorderKernel(const unsigned int* input, unsigned int* output,
const unsigned int* counts, unsigned int size,
unsigned int shift) {
unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < size) {
unsigned int bin = (input[idx] >> shift) & (NUM_BINS - 1);
unsigned int pos = atomicAdd(&counts[bin], 1);
output[pos] = input[idx];
}
}
// Host function to perform radix sort
void radixSort(unsigned int* d_input, unsigned int* d_output,
unsigned int size) {
unsigned int *d_counts;
cudaMalloc(&d_counts, NUM_BINS * sizeof(unsigned int));
// Temporary array for ping-pong between input and output
unsigned int *d_temp;
for (unsigned int shift = 0; shift < 32; shift += NUM_BITS) {
// Reset counts to 0
cudaMemset(d_counts, 0, NUM_BINS * sizeof(unsigned int));
// Count the number of elements in each bin
unsigned int blockCount = (size + BLOCK_SIZE - 1) / BLOCK_SIZE;
countKernel<<<blockCount, BLOCK_SIZE>>>(d_input, d_counts, size, shift);
// Compute prefix sums (scan) of the counts
scanKernel<<<1, NUM_BINS, NUM_BINS * sizeof(unsigned int)>>>(d_counts);
// Reorder elements based on the prefix sums
reorderKernel<<<blockCount, BLOCK_SIZE>>>(d_input, d_output, d_counts, size, shift);
// Swap input and output pointers for next iteration
d_temp = d_input;
d_input = d_output;
d_output = d_temp;
}
// If the number of passes was odd, copy the result back to the original array
if ((32 / NUM_BITS) % 2 != 0) {
cudaMemcpy(d_output, d_input, size * sizeof(unsigned int),
cudaMemcpyDeviceToDevice);
}
cudaFree(d_counts);
}
// Wrapper function for easier use
void cudaRadixSort(unsigned int* h_input, unsigned int size) {
unsigned int *d_input, *d_output;
// Allocate device memory
cudaMalloc(&d_input, size * sizeof(unsigned int));
cudaMalloc(&d_output, size * sizeof(unsigned int));
// Copy input to device
cudaMemcpy(d_input, h_input, size * sizeof(unsigned int),
cudaMemcpyHostToDevice);
// Perform radix sort
radixSort(d_input, d_output, size);
// Copy result back to host
cudaMemcpy(h_input, d_output, size * sizeof(unsigned int),
cudaMemcpyDeviceToHost);
// Free device memory
cudaFree(d_input);
cudaFree(d_output);
}
Count Kernel: Each thread counts how many elements fall into each bin (based on the current digit being processed).
Scan Kernel: Computes prefix sums of the counts to determine the starting positions of each bin in the output array.
Reorder Kernel: Uses the prefix sums to place each element in its correct position in the output array.
Radix Sort Function: Orchestrates the sorting process, iterating through each digit position (from least to most significant).
Wrapper Function: Provides a convenient interface for host code to call the radix sort.
int main() {
const unsigned int size = 1000000; // 1 million elements
unsigned int *h_input = (unsigned int*)malloc(size * sizeof(unsigned int));
// Initialize input data (random values for example)
for (unsigned int i = 0; i < size; i++) {
h_input[i] = rand();
}
// Perform radix sort
cudaRadixSort(h_input, size);
// Verify the result is sorted
for (unsigned int i = 1; i < size; i++) {
if (h_input[i-1] > h_input[i]) {
printf("Sorting failed at position %d\n", i);
break;
}
}
free(h_input);
return 0;
}
This implementation uses 4 bits per digit (NUM_BITS = 4), which means it will perform 8 passes (32 bits / 4 bits per pass) to sort 32-bit integers. You can adjust NUM_BITS to trade off between the number of passes and the number of bins (which affects memory usage and performance).