23ms 实现 5e8 长度前缀和
DarkMoon_Dragon · · 个人记录
Report on Parallel Scan
Environment
1. Problem Description
We want to implement the Inclusive Scan:
- Given an array
[x_0,x_1,x_2,\ldots,x_n] ,calculate its prefix sum array[y_0,y_1,y_2,\ldots,y_n] , wherey_i = \sum_{i=0}^n x_i .
CPU version of C++:
void get_presum_cpu(DTYPE *x, DTYPE *y, int len) {
DTYPE sum = DTYPE();
for (int i = 0; i < len; i++) {
sum += x[i];
y[i] = sum;
}
}
The time complexity of this algorithm is
2. A Simple Parallel Scan
2.1. For array length less than 1024
The algorithm shown above is an in-place algorithm which operates on the initial array
We first write a kernel that performs scan on only one section (length of 1024) of the input, which is small enough for one block to handle. We use shared memory to achieve IO efficiency.
__global__ void Scan_kernel_naive_one_section(DTYPE *X, DTYPE *Y, int len) {
__shared__ DTYPE XY[BLOCK_SIZE * 2];
int i = threadIdx.x;
if (i < len)
XY[i] = X[i];
int state = false; // double buffer's state
for (unsigned int stride = 1; stride < blockDim.x; stride <<= 1) {
__syncthreads();
state ^= 1;
if (threadIdx.x >= stride)
XY[threadIdx.x + BLOCK_SIZE * state] =
XY[threadIdx.x + BLOCK_SIZE * (state ^ 1)] +
XY[threadIdx.x - stride + BLOCK_SIZE * (state ^ 1)];
else XY[threadIdx.x + BLOCK_SIZE * state] = XY[threadIdx.x + BLOCK_SIZE * (state ^ 1)];
}
Y[i] = XY[threadIdx.x + state * BLOCK_SIZE];
}
The loop iterates through the reduction tree (the above picture) for the original X array position assigned to a thread. Every thread is responsible for one position in the array. We use a __syncthreads() to ensure that all threads have finished their previous iteration of additions in the reduction tree before any of them starts the next iteration. We add double buffer in the shared memory to avoid competitive IO, this can be achieved by simply extending the length of shared memory to its twice. When the stride value exceeds the threadIdx.x value of a thread, the assigned X position of the thread is supposed to have accumulated all required input values.
The result is shown below:
- This version of parallel scan only works for array whose length is less than 1024 (so as to be stored in one block).
- It is seen that this version achieves no speed-up for the small-size data, However, it is used to justify our kernel is correct under this circumstance.
Now, we'll consider extend this version of scan to process arbitray size of data. However, we cannot easily synchronize among the blocks, thus we need to further change the way of implementation.
2.2 For arbitrary array length
Despite we cannot easily synchronize among blocks during the computing process, instead, we can synchronize in the caller function by hand, as is shown:
Version i:
__global__ void Scan_kernel_naive_double_buffer(DTYPE *X, DTYPE *Y, int len, int stride) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= stride) Y[i] += X[i - stride];
}
DTYPE *caller_double_buffer(DTYPE *input, int len,
void (*kernel)(DTYPE *input, DTYPE *output, int len, int stride)) {
dim3 block(512);
// one block processes 512 numbers, use double buffer to avoid competitive IO
dim3 grid((len - 1) / (block.x) + 1);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_buffer0 = NULL;
DTYPE *d_buffer1 = NULL;
CHECK(cudaMalloc(&d_buffer0, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&d_buffer1, len * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_buffer0, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
CHECK(cudaMemcpy(d_buffer1, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
bool state = true; // buffer's state : [~state] as input, [state] as output
// different iterations
for (unsigned int stride = 1; stride < len; stride <<= 1) {
if (state) {
kernel<<<grid, block>>>(d_buffer0, d_buffer1, len, stride);
CHECK(cudaMemcpy(d_buffer0, d_buffer1, len * sizeof(DTYPE), cudaMemcpyDeviceToDevice));
} else {
kernel<<<grid, block>>>(d_buffer1, d_buffer0, len, stride);
CHECK(cudaMemcpy(d_buffer1, d_buffer0, len * sizeof(DTYPE), cudaMemcpyDeviceToDevice));
}
state ^= 1;
}
timer.Stop();
printf("Double buffer computing time: %f ms.\n", timer.Elapsed());
if (state) {
CHECK(cudaMemcpy(output, d_buffer0, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
} else {
CHECK(cudaMemcpy(output, d_buffer1, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
}
CHECK(cudaFree(d_buffer0));
CHECK(cudaFree(d_buffer1));
return output;
}
We divide different iterations mannually in the caller's for, then we use double buffer to avoid competitive IO among blocks. However, we have to call cudaMemcpyDeviceToDevice() to copy buffers' data. This may cost lots of time. We can further improve it into version ii, which involves copying data in the kernel function.
Version ii:
__global__ void Scan_kernel_naive_double_buffer_1(DTYPE *X, DTYPE *Y, int len, int stride) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= stride) Y[i] = X[i] + X[i - stride];
else Y[i] = X[i];
}
DTYPE *caller_double_buffer_1(DTYPE *input, int len,
void (*kernel)(DTYPE *input, DTYPE *output, int len, int stride)) {
dim3 block(512);
// one block processes 512 numbers, use double buffer to avoid competitive IO
dim3 grid((len - 1) / (block.x) + 1);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_buffer0 = NULL;
DTYPE *d_buffer1 = NULL;
CHECK(cudaMalloc(&d_buffer0, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&d_buffer1, len * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_buffer0, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
CHECK(cudaMemcpy(d_buffer1, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
bool state = true; // buffer's state : [~state] as input, [state] as output
for (unsigned int stride = 1; stride < len; stride <<= 1) {
if (state) {
kernel<<<grid, block>>>(d_buffer0, d_buffer1, len, stride);
} else {
kernel<<<grid, block>>>(d_buffer1, d_buffer0, len, stride);
}
state ^= 1;
}
timer.Stop();
printf("Double buffer(version ii) computing time: %f ms.\n", timer.Elapsed());
if (state) {
CHECK(cudaMemcpy(output, d_buffer0, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
} else {
CHECK(cudaMemcpy(output, d_buffer1, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
}
CHECK(cudaFree(d_buffer0));
CHECK(cudaFree(d_buffer1));
return output;
}
By utilizing double buffer, we can achieve a speed-up of 90% than cpu, cost
Results:
-
For an array whose length is
5\cdot10^8 , scan on CPU cost about4300 ms, while the GPU version i costs714 ms, and version ii costs337 ms.
3. Work-Efficient Scan
3.1 For array length less than 1024
Work-efficient scan can be achieved mainly in two steps.
-
The first step is the up-sweep phase which calculates the reduction tree of the given array, the basic idea of which is the same as
reductionthat is mentioned in the class. -
The second step is the down-sweep phase which uses partial sums from reduce phase to build scan in place on array, as is shown:
__global__ void Work_efficient_scan_one_section(DTYPE *X, DTYPE *Y, int len) {
__shared__ DTYPE XY[SECTION_SIZE];
int i = threadIdx.x;
if (i < len) XY[i] = X[i];
if (i + blockDim.x < len) XY[i + blockDim.x] = X[i + blockDim.x];
// Get a reduction tree
for (unsigned int stride = 1; stride <= blockDim.x; stride <<= 1) {
__syncthreads();
int index = (i + 1) * 2 * stride - 1;
if (index < SECTION_SIZE) {
XY[index] += XY[index - stride];
}
}
// Push down
for (int stride = SECTION_SIZE >> 2; stride > 0; stride >>= 1) {
__syncthreads();
int index = (i + 1) * stride * 2 - 1;
if (index + stride < SECTION_SIZE) {
XY[index + stride] += XY[index];
}
}
__syncthreads();
if (i < len) Y[i] = XY[i];
if (i + blockDim.x < len) Y[i + blockDim.x] = XY[i + blockDim.x];
}
The caller of work-efficient scan is nearly the same as the simple parallel scan.
DTYPE *caller_work_efficent_scan_one_section(DTYPE *input, int len,
void (*kernel)(DTYPE *input, DTYPE *output, int len)) {
dim3 block(1024);
// one block process 1024 numbers
dim3 grid(1);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_input = NULL;
DTYPE *d_output = NULL;
CHECK(cudaMalloc(&d_input, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&d_output, len * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_input, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
kernel<<<grid, block>>>(d_input, d_output, len);
timer.Stop();
printf("Work-efficient scan computing time: %f ms.\n", timer.Elapsed());
CHECK(cudaMemcpy(output, d_output, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
CHECK(cudaFree(d_input));
CHECK(cudaFree(d_output));
return output;
}
Results:
- Although this version of work-efficient scan only works for the array whose length is less than 1024, but we can combine work-efficient scan for one section and simple parallel scan to implement the later version which works for arbitrary array length.
3.2 For arbitrary array length (Bonus)
The expanded version of work-efficient scan can be achieved in three phases:
-
This type of scan is also named as Hierarchical scan.
-
The first step is to partite the input into sections so that each of them can fit into the shared memory and be processed by a single block in one work-efficient scan kernel, then we call the kernel work-efficient scan to process each of these sections. After the process, we'll get an array
Ywhich contains the scanned results for individual sections, as is shown above.The first step's kernel : (changes the one section scan kernel into a multiple section one)
__global__ void Work_efficient_scan_multi_section(DTYPE *X, DTYPE *S, int len) { __shared__ DTYPE XY[SECTION_SIZE]; int i = 2 * blockIdx.x * blockDim.x + threadIdx.x; if (i < len) XY[threadIdx.x] = X[i]; if (i + blockDim.x < len) XY[threadIdx.x + blockDim.x] = X[i + blockDim.x]; // calculate the redution tree for (unsigned int stride = 1; stride <= blockDim.x; stride <<= 1) { __syncthreads(); int index = (threadIdx.x + 1) * 2 * stride - 1; if (index < SECTION_SIZE) { XY[index] += XY[index - stride]; } } // pushdown for (int stride = SECTION_SIZE >> 2; stride > 0; stride >>= 1) { __syncthreads(); int index = (threadIdx.x + 1) * stride * 2 - 1; if (index + stride < SECTION_SIZE) { XY[index + stride] += XY[index]; } } __syncthreads(); if (i < len) X[i] = XY[threadIdx.x]; if (i + blockDim.x < len) X[i + blockDim.x] = XY[threadIdx.x + blockDim.x]; if (threadIdx.x == blockDim.x - 1) { S[blockIdx.x] = XY[SECTION_SIZE - 1]; } } -
The second step is to process the auxiliary array
S. The last output element of each scan block yields the sum of all input elements of the scan block. These values are7,7,6,11 as is shown. We then use simple parallel scan to process the arraySfor the length of which can be much longer than1024 . Here we don't have to conduct any memory access process, thus this can be achieved in a quite fast way. After the process, we get a scanned arrayS', which contains the prefix sum of the auxiliary arrayS. -
The third step is to write
S'back intoY. The process is quite trivial as is shown:__global__ void Hierarchical_distribute(DTYPE *S, DTYPE *Y, int len) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (blockIdx.x > 0 && i < len) Y[i] += S[blockIdx.x - 1]; }
The caller of these three step, which combines these three phases, is shown below:
DTYPE *caller_work_efficient_scan_hierarchical(DTYPE *input, int len) {
dim3 block(BLOCK_SIZE);
// one block with BLOCK_SIZE(512) threads process SECTION_SIZE(1024) numbers
const int SECTION_NUM = (len - 1) / SECTION_SIZE + 1;
dim3 grid(SECTION_NUM);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_input = NULL;
DTYPE *S = NULL;
CHECK(cudaMalloc(&d_input, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&S, SECTION_NUM * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_input, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
// Phase one
Work_efficient_scan_multi_section<<<grid, block>>>(d_input, S, len);
// Phase two
caller_double_buffer_S(S, SECTION_NUM);
// Phase three
block = dim3(SECTION_SIZE);
grid = dim3((len - 1) / SECTION_SIZE + 1);
Hierarchical_distribute<<<grid, block>>>(S, d_input, len);
timer.Stop();
printf("Hierarchical scan computing time:%f ms\n", timer.Elapsed());
CHECK(cudaMemcpy(output, d_input, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
CHECK(cudaFree(d_input));
CHECK(cudaFree(S));
return output;
}
The results are shocking:
-
For an array whose length is
5\cdot10^7 , scan on CPU costs about420 ms, while the optimized GPU version only costs2.5516 ms. -
For an array whose length is
5\cdot10^8 , scan on CPU costs about4200 ms, while the optimized GPU version only costs23.0592 ms.
Appendices
The complete code is in this section.
Headers
error_check.h
#ifndef ERROR_CHECK_H
#define ERROR_CHECK_H
#include<stdio.h>
#define CHECK(call){ \
cudaError_t e_code = call; \
if(e_code!=cudaSuccess){ \
printf("##CUDA Error:\n"); \
printf(" File: %s\n", __FILE__); \
printf(" Line: %d\n", __LINE__); \
printf(" Error info: %s\n", cudaGetErrorString(e_code)); \
} \
}
#endif
gpu_timer.h
#ifndef __GPU_TIMER_H__
#define __GPU_TIMER_H__
struct GpuTimer
{
cudaEvent_t start;
cudaEvent_t stop;
GpuTimer()
{
cudaEventCreate(&start);
cudaEventCreate(&stop);
}
~GpuTimer()
{
cudaEventDestroy(start);
cudaEventDestroy(stop);
}
void Start()
{
cudaEventRecord(start, 0);
}
void Stop()
{
cudaEventRecord(stop, 0);
}
float Elapsed()
{
float elapsed;
cudaEventSynchronize(stop);
cudaEventElapsedTime(&elapsed, start, stop);
return elapsed;
}
};
#endif /* __GPU_TIMER_H__ */
Full code:
//
// Created by Liao_rl during 2022/12/22 - 2022/12/24.
// DO NOT DUPLICATE WITHOUT PERMISSION !!!
// Email : [email protected]
// Contact me for the source code !!!
#include<stdio.h>
#include<stdlib.h>
#include"error_check.h"
#include"gpu_timer.h"
#define DTYPE double
#define SECTION_SIZE 1024
#define BLOCK_SIZE (SECTION_SIZE / 2)
// #define DEBUG
DTYPE *test_data_gen(int len) {
srand(time(0));
DTYPE *data = (DTYPE *) malloc(len * sizeof(DTYPE));
for (int i = 0; i < len; i++) {
data[i] = 1.0 * (rand() % RAND_MAX) / RAND_MAX;
}
return data;
}
void get_presum_cpu(DTYPE *x, DTYPE *y, int len) {
DTYPE sum = DTYPE();
for (int i = 0; i < len; i++) {
sum += x[i];
y[i] = sum;
}
}
bool check(DTYPE *x, DTYPE *y, int len) {
for (int i = 0; i < len; i++) {
if (abs(x[i] - y[i]) > 1.0) {
#ifdef DEBUG
printf("pos[%d], val x:%lf, y:%lf\n", i, x[i], y[i]);
#endif
return false;
}
}
return true;
}
__global__ void Scan_kernel_naive_one_section(DTYPE *X, DTYPE *Y, int len) {
__shared__ DTYPE XY[SECTION_SIZE * 2];
int i = threadIdx.x;
if (i < len)
XY[i] = X[i];
int state = false;
for (unsigned int stride = 1; stride < blockDim.x; stride <<= 1) {
__syncthreads();
state ^= 1;
if (threadIdx.x >= stride)
XY[threadIdx.x + SECTION_SIZE * state] = XY[threadIdx.x + SECTION_SIZE * (state ^ 1)] +
XY[threadIdx.x - stride + SECTION_SIZE * (state ^ 1)];
else XY[threadIdx.x + SECTION_SIZE * state] = XY[threadIdx.x + SECTION_SIZE * (state ^ 1)];
}
Y[i] = XY[threadIdx.x + state * SECTION_SIZE];
}
__global__ void Scan_kernel_naive_double_buffer(DTYPE *X, DTYPE *Y, int len, int stride) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= stride) Y[i] += X[i - stride];
}
__global__ void Scan_kernel_naive_double_buffer_1(DTYPE *X, DTYPE *Y, int len, int stride) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= stride) Y[i] = X[i] + X[i - stride];
else Y[i] = X[i];
}
__global__ void Work_efficient_scan_one_section(DTYPE *X, DTYPE *Y, int len) {
__shared__ DTYPE XY[SECTION_SIZE];
int i = threadIdx.x;
if (i < len) XY[i] = X[i];
if (i + blockDim.x < len) XY[i + blockDim.x] = X[i + blockDim.x];
// Get a reduction tree
for (unsigned int stride = 1; stride <= blockDim.x; stride <<= 1) {
__syncthreads();
int index = (i + 1) * 2 * stride - 1;
if (index < SECTION_SIZE) {
XY[index] += XY[index - stride];
}
}
// Push down
for (int stride = SECTION_SIZE >> 2; stride > 0; stride >>= 1) {
__syncthreads();
int index = (i + 1) * stride * 2 - 1;
if (index + stride < SECTION_SIZE) {
XY[index + stride] += XY[index];
}
}
__syncthreads();
if (i < len) Y[i] = XY[i];
if (i + blockDim.x < len) Y[i + blockDim.x] = XY[i + blockDim.x];
}
__global__ void Work_efficient_scan_multi_section(DTYPE *X, DTYPE *S, int len) {
__shared__ DTYPE XY[SECTION_SIZE];
int i = 2 * blockIdx.x * blockDim.x + threadIdx.x;
if (i < len) XY[threadIdx.x] = X[i];
if (i + blockDim.x < len) XY[threadIdx.x + blockDim.x] = X[i + blockDim.x];
// calculate the redution tree
for (unsigned int stride = 1; stride <= blockDim.x; stride <<= 1) {
__syncthreads();
int index = (threadIdx.x + 1) * 2 * stride - 1;
if (index < SECTION_SIZE) {
XY[index] += XY[index - stride];
}
}
// pushdown
for (int stride = SECTION_SIZE >> 2; stride > 0; stride >>= 1) {
__syncthreads();
int index = (threadIdx.x + 1) * stride * 2 - 1;
if (index + stride < SECTION_SIZE) {
XY[index + stride] += XY[index];
}
}
__syncthreads();
if (i < len) X[i] = XY[threadIdx.x];
if (i + blockDim.x < len) X[i + blockDim.x] = XY[threadIdx.x + blockDim.x];
if (threadIdx.x == blockDim.x - 1) {
S[blockIdx.x] = XY[SECTION_SIZE - 1];
}
}
__global__ void Hierarchical_distribute(DTYPE *S, DTYPE *Y, int len) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
// printf(" [%d %d %f] ", i, blockIdx.x, S[blockIdx.x - 1]);
if (blockIdx.x > 0 && i < len) Y[i] += S[blockIdx.x - 1];
}
DTYPE *caller_one_section(DTYPE *input, int len,
void (*kernel)(DTYPE *input, DTYPE *output, int len)) {
dim3 block(1024);
// one block process 1024 numbers
dim3 grid(1);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_input = NULL;
DTYPE *d_output = NULL;
CHECK(cudaMalloc(&d_input, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&d_output, len * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_input, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
kernel<<<grid, block>>>(d_input, d_output, len);
CHECK(cudaGetLastError())
timer.Stop();
printf("One section computing time: %f ms.\n", timer.Elapsed());
CHECK(cudaMemcpy(output, d_output, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
CHECK(cudaFree(d_input));
CHECK(cudaFree(d_output));
return output;
}
DTYPE *caller_double_buffer(DTYPE *input, int len,
void (*kernel)(DTYPE *input, DTYPE *output, int len, int stride)) {
dim3 block(512);
// one block process 1024 numbers, use double buffer to avoid competitive IO
dim3 grid((len - 1) / (block.x) + 1);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_buffer0 = NULL;
DTYPE *d_buffer1 = NULL;
CHECK(cudaMalloc(&d_buffer0, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&d_buffer1, len * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_buffer0, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
CHECK(cudaMemcpy(d_buffer1, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
bool state = true; // buffer's state : [~state] as input, [state] as output
for (unsigned int stride = 1; stride < len; stride <<= 1) {
if (state) {
kernel<<<grid, block>>>(d_buffer0, d_buffer1, len, stride);
// CHECK(cudaGetLastError());
// cudaDeviceSynchronize();
CHECK(cudaMemcpy(d_buffer0, d_buffer1, len * sizeof(DTYPE), cudaMemcpyDeviceToDevice));
} else {
kernel<<<grid, block>>>(d_buffer1, d_buffer0, len, stride);
// CHECK(cudaGetLastError());
// cudaDeviceSynchronize();
CHECK(cudaMemcpy(d_buffer1, d_buffer0, len * sizeof(DTYPE), cudaMemcpyDeviceToDevice));
}
state ^= 1;
}
timer.Stop();
printf("Double buffer(version i) computing time: %f ms.\n", timer.Elapsed());
if (state) {
CHECK(cudaMemcpy(output, d_buffer0, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
} else {
CHECK(cudaMemcpy(output, d_buffer1, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
}
CHECK(cudaFree(d_buffer0));
CHECK(cudaFree(d_buffer1));
return output;
}
DTYPE *caller_double_buffer_1(DTYPE *input, int len,
void (*kernel)(DTYPE *input, DTYPE *output, int len, int stride)) {
dim3 block(512);
// one block process 512 numbers, use double buffer to avoid competitive IO
dim3 grid((len - 1) / (block.x) + 1);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_buffer0 = NULL;
DTYPE *d_buffer1 = NULL;
CHECK(cudaMalloc(&d_buffer0, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&d_buffer1, len * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_buffer0, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
CHECK(cudaMemcpy(d_buffer1, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
bool state = true; // buffer's state : [~state] as input, [state] as output
for (unsigned int stride = 1; stride < len; stride <<= 1) {
if (state) {
kernel<<<grid, block>>>(d_buffer0, d_buffer1, len, stride);
// CHECK(cudaGetLastError());
// cudaDeviceSynchronize();
} else {
kernel<<<grid, block>>>(d_buffer1, d_buffer0, len, stride);
// CHECK(cudaGetLastError());
// cudaDeviceSynchronize();
}
state ^= 1;
}
timer.Stop();
printf("Double buffer(version ii) computing time: %f ms.\n", timer.Elapsed());
if (state) {
CHECK(cudaMemcpy(output, d_buffer0, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
} else {
CHECK(cudaMemcpy(output, d_buffer1, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
}
CHECK(cudaFree(d_buffer0));
CHECK(cudaFree(d_buffer1));
return output;
}
void caller_double_buffer_S(DTYPE *S, int len) {
dim3 block(512);
// one block process 512 numbers, use double buffer to avoid competitive IO
dim3 grid((len - 1) / (block.x) + 1);
DTYPE *d_buffer0 = NULL;
DTYPE *d_buffer1 = NULL;
CHECK(cudaMalloc(&d_buffer0, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&d_buffer1, len * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_buffer0, S, len * sizeof(DTYPE), cudaMemcpyDeviceToDevice));
CHECK(cudaMemcpy(d_buffer1, S, len * sizeof(DTYPE), cudaMemcpyDeviceToDevice));
bool state = true; // buffer's state : [~state] as S, [state] as output
for (unsigned int stride = 1; stride < len; stride <<= 1) {
if (state) {
Scan_kernel_naive_double_buffer_1<<<grid, block>>>(d_buffer0, d_buffer1, len, stride);
// CHECK(cudaGetLastError());
// cudaDeviceSynchronize();
} else {
Scan_kernel_naive_double_buffer_1<<<grid, block>>>(d_buffer1, d_buffer0, len, stride);
// CHECK(cudaGetLastError());
// cudaDeviceSynchronize();
}
state ^= 1;
}
if (state) {
CHECK(cudaMemcpy(S, d_buffer0, len * sizeof(DTYPE), cudaMemcpyDeviceToDevice));
} else {
CHECK(cudaMemcpy(S, d_buffer1, len * sizeof(DTYPE), cudaMemcpyDeviceToDevice));
}
CHECK(cudaFree(d_buffer0));
CHECK(cudaFree(d_buffer1));
}
DTYPE *caller_work_efficient_scan_one_section(DTYPE *input, int len,
void (*kernel)(DTYPE *input, DTYPE *output, int len)) {
dim3 block(1024);
// one block process 1024 numbers
dim3 grid(1);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_input = NULL;
DTYPE *d_output = NULL;
CHECK(cudaMalloc(&d_input, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&d_output, len * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_input, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
kernel<<<grid, block>>>(d_input, d_output, len);
timer.Stop();
printf("Work-efficient scan computing time: %f ms.\n", timer.Elapsed());
CHECK(cudaMemcpy(output, d_output, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
CHECK(cudaFree(d_input));
CHECK(cudaFree(d_output));
return output;
}
DTYPE *caller_work_efficient_scan_hierarchical(DTYPE *input, int len) {
dim3 block(BLOCK_SIZE);
// one block with BLOCK_SIZE(512) threads process SECTION_SIZE(1024) numbers
const int SECTION_NUM = (len - 1) / SECTION_SIZE + 1;
dim3 grid(SECTION_NUM);
DTYPE *output = (DTYPE *) malloc(len * sizeof(DTYPE));
DTYPE *d_input = NULL;
DTYPE *S = NULL;
CHECK(cudaMalloc(&d_input, len * sizeof(DTYPE)));
CHECK(cudaMalloc(&S, SECTION_NUM * sizeof(DTYPE)));
CHECK(cudaMemcpy(d_input, input, len * sizeof(DTYPE), cudaMemcpyHostToDevice));
GpuTimer timer;
timer.Start();
Work_efficient_scan_multi_section<<<grid, block>>>(d_input, S, len);
#ifdef DEBUG
CHECK(cudaMemcpy(output, S, SECTION_NUM * sizeof(DTYPE), cudaMemcpyDeviceToHost));
for (int i = 0; i < 10; ++i) printf(" %f \n", output[i]);
#endif
caller_double_buffer_S(S, SECTION_NUM);
#ifdef DEBUG
CHECK(cudaMemcpy(output, S, SECTION_NUM * sizeof(DTYPE), cudaMemcpyDeviceToHost));
for (int i = 0; i < 10; ++i) printf(" %f \n", output[i]);
#endif
block = dim3(SECTION_SIZE);
grid = dim3((len - 1) / SECTION_SIZE + 1);
// printf("\n\n xxx %d %d %d xxxxx\n\n", SECTION_NUM, block.x, grid.x);
Hierarchical_distribute<<<grid, block>>>(S, d_input, len);
timer.Stop();
printf("Hierarchical scan computing time:%f ms\n", timer.Elapsed());
CHECK(cudaMemcpy(output, d_input, len * sizeof(DTYPE), cudaMemcpyDeviceToHost));
CHECK(cudaFree(d_input));
CHECK(cudaFree(S));
return output;
}
void test(int len,
DTYPE *(*caller)(DTYPE *input, int len, void (*kernel)(DTYPE *input, DTYPE *output, int len, int stride)),
void (*kernel)(DTYPE *input, DTYPE *output, int len, int stride)) {
printf("-----------------------\n");
DTYPE *vector_input, *presum_cpu, *presum_gpu;
vector_input = test_data_gen(len);
presum_cpu = (DTYPE *) malloc(len * sizeof(DTYPE));
double st = clock();
get_presum_cpu(vector_input, presum_cpu, len);
double et = clock();
GpuTimer timer;
timer.Start();
presum_gpu = caller(vector_input, len, kernel);
timer.Stop();
printf("Array Length [%d]:\n", len);
printf("CPU time cost: %lf ms. \n", (et - st) / CLOCKS_PER_SEC * 1000);
printf("GPU time cost(include IO): %g ms.\n", timer.Elapsed());
puts("CHECKING RESULTS...");
if (check(presum_cpu, presum_gpu, len)) printf("--- PASSED!!! ---\n");
else printf("--- FAILED!!! ---\n");
puts("Last six element on GPU: ");
for (int i = len - 7; i < len; ++i)
printf("%f ", presum_gpu[i]);
puts("");
puts("Last six element on CPU:");
for (int i = len - 7; i < len; ++i)
printf("%f ", presum_cpu[i]);
printf("\n-----------------------\n\n");
free(vector_input);
free(presum_cpu);
free(presum_gpu);
}
void test(int len, DTYPE *(*caller)(DTYPE *input, int len)) {
printf("-----------------------\n");
DTYPE *vector_input, *presum_cpu, *presum_gpu;
vector_input = test_data_gen(len);
presum_cpu = (DTYPE *) malloc(len * sizeof(DTYPE));
double st = clock();
get_presum_cpu(vector_input, presum_cpu, len);
double et = clock();
GpuTimer timer;
timer.Start();
presum_gpu = caller(vector_input, len);
timer.Stop();
printf("Array Length [%d]:\n", len);
printf("CPU time cost: %lf ms. \n", (et - st) / CLOCKS_PER_SEC * 1000);
printf("GPU time cost(include IO): %g ms.\n", timer.Elapsed());
puts("CHECKING RESULTS...");
if (check(presum_cpu, presum_gpu, len)) printf("--- PASSED!!! ---\n");
else printf("--- FAILED!!! ---\n");
puts("Last six element on GPU: ");
for (int i = len - 7; i < len; ++i)
printf("%f ", presum_gpu[i]);
puts("");
puts("Last six element on CPU:");
for (int i = len - 7; i < len; ++i)
printf("%f ", presum_cpu[i]);
printf("\n-----------------------\n\n");
free(vector_input);
free(presum_cpu);
free(presum_gpu);
}
void test(int len,
DTYPE *(*caller)(DTYPE *input, int len, void (*kernel)(DTYPE *input, DTYPE *output, int len)),
void (*kernel)(DTYPE *input, DTYPE *output, int len)) {
printf("-----------------------\n");
DTYPE *vector_input, *presum_cpu, *presum_gpu;
vector_input = test_data_gen(len);
presum_cpu = (DTYPE *) malloc(len * sizeof(DTYPE));
double st = clock();
get_presum_cpu(vector_input, presum_cpu, len);
double et = clock();
GpuTimer timer;
timer.Start();
presum_gpu = caller(vector_input, len, kernel);
timer.Stop();
printf("Array Length [%d]:\n", len);
printf("CPU time cost: %lf ms. \n", (et - st) / CLOCKS_PER_SEC * 1000);
printf("GPU time cost(include IO): %g ms.\n", timer.Elapsed());
puts("CHECKING RESULTS...");
if (check(presum_cpu, presum_gpu, len)) printf("--- PASSED!!! ---\n");
else printf("--- FAILED!!! ---\n");
puts("Last six element on GPU: ");
for (int i = len - 7; i < len; ++i)
printf("%f ", presum_gpu[i]);
puts("");
puts("Last six element on CPU:");
for (int i = len - 7; i < len; ++i)
printf("%f ", presum_cpu[i]);
printf("\n-----------------------\n\n");
free(vector_input);
free(presum_cpu);
free(presum_gpu);
}
int main(int argc, char **argv) {
int n_arr1[] = {512, 1024};
for (int i = 0; i < sizeof(n_arr1) / sizeof(int); i++) {
puts("Naive Scan within one section (only work for array size less than 1024):");
test(n_arr1[i], caller_one_section, Scan_kernel_naive_one_section);
}
int n_arr2[] = {1 << 9, 1 << 10, 1 << 12, 1 << 20, int(7e6), int(5e7), int(5e8)};
for (int i = 0; i < sizeof(n_arr2) / sizeof(int); i++) {
puts("Naive Scan with double buffer for Arbitray-Length Input (1st edition):");
test(n_arr2[i], caller_double_buffer, Scan_kernel_naive_double_buffer);
puts("Naive Scan with double buffer for Arbitray-Length Input (2nd edition):");
test(n_arr2[i], caller_double_buffer_1, Scan_kernel_naive_double_buffer_1);
}
int n_arr3[] = {512, 1024};
for (int i = 0; i < sizeof(n_arr3) / sizeof(int); i++) {
puts("Work-efficient Scan within one section (only work for array size less than 1024):");
test(n_arr3[i], caller_work_efficient_scan_one_section, Work_efficient_scan_one_section);
}
int n_arr4[] = {1024, 2048, int(1 << 15), int(1 << 20), int(5e7), int(5e8)};
for (int i = 0; i < sizeof(n_arr4) / sizeof(int); i++) {
puts("Hierarchical Work-efficient Scan for Arbitray-Length Input:");
test(n_arr4[i], caller_work_efficient_scan_hierarchical);
}
return 0;
}