C 并行化函数,该函数将使用向量元素和不大于k的元素之和计算所有向量

C 并行化函数,该函数将使用向量元素和不大于k的元素之和计算所有向量,c,cuda,C,Cuda,我想并行化CUDA C中的一个函数,它将使用向量元素和不大于k的元素之和计算所有向量。例如,如果向量元素n的数量为5,sum=10,k=3,则满足此条件的向量数量为101。我已经在CUDA C中实现了这个函数,但问题是当块和线程的数量大于1时。我知道问题出在周期中,我应该改变它,但我不知道从哪里开始。当我用块和线程等于1的方式调用函数时,函数以经典方式工作,一切都很好,但在这种情况下,函数没有并行化 该程序的源代码是: //function that count number of vector

我想并行化CUDA C中的一个函数,它将使用向量元素和不大于k的元素之和计算所有向量。例如,如果向量元素n的数量为5,sum=10,k=3,则满足此条件的向量数量为101。我已经在CUDA C中实现了这个函数,但问题是当块和线程的数量大于1时。我知道问题出在周期中,我应该改变它,但我不知道从哪里开始。当我用块和线程等于1的方式调用函数时,函数以经典方式工作,一切都很好,但在这种情况下,函数没有并行化

该程序的源代码是:

//function that count number of vectors
__device__ void count(int *vector, int *total, int n, int s)
{
 int i,sum=0;
 for(i=blockIdx.x*blockDim.x+threadIdx.x;i<n;i+=blockDim.x*gridDim.x)
 {    
   sum+=vector[i];
   __syncthreads();
 }
 if(sum==s)
 {  
   total[0]=total[0]+1;
 }
}

//main function
__global__ void computeVectors(int *vector, int n, int kk, int s, int *total)
{
 int k=0;
 int j,i,next;

 while(1)
 {
  //this is the problem, in for cycle
  for(j=blockIdx.x*blockDim.x+threadIdx.x; j<=kk; j+=blockDim.x*gridDim.x)
  {
   vector[k]=j;
   count(vector, total, n, s);
   __syncthreads();
  }
  for(i=blockIdx.x*blockDim.x+threadIdx.x; i<n; i+=blockDim.x*gridDim.x)
  {

   if(vector[i]<kk)
      break;
  }  
  next=i;
  vector[next]++;
  for(i=blockIdx.x*blockDim.x+threadIdx.x; i<sledno; i+=blockDim.x*gridDim.x)
  {
   vector[i]=0;
   __syncthreads();
  }
  k=0;
  if(next>=n)
    break;
 }
}

int main()
{
  cudaError_t err = cudaSuccess;

  int n,k,sum;
  int counter=0;

  printf("Enter the length of vector n=");
  scanf("%d",&n);
  printf("Enter the max value of vector elements k=");
  scanf("%d",&k);
  printf("Enter the sum of vector elements sum=");
  scanf("%d",&sum);

  //initial vector with length n
  int *vec_h, *vec_d;
  size_t sizevec=n*sizeof(int);
  vec_h=(int *)malloc(sizevec);
  cudaMalloc((void **) &vec_d, sizevec);

  for(counter=0; counter<n; counter++)
  {
   vec_h[counter]=0;
  }
  cudaMemcpy(vec_d, vec_h, sizevec, cudaMemcpyHostToDevice);

  int *total_h, *total_d;
  size_t size=1*sizeof(int);
  total_h=(int *)malloc(size);
  cudaMalloc((void **) &total_d, size);
  total_h[0]=0;
  cudaMemcpy(total_d, total_h, size, cudaMemcpyHostToDevice);

  //calling the main function
  computeVectors<<<1, 1>>>(vec_d, n, k, sum, total_d);

  cudaThreadSynchronize(); 

  err = cudaGetLastError();
  if (err != cudaSuccess)
  {
    fprintf(stderr, "Error: %s!\n", cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }
  cudaMemcpy(total_h, total_d, size, cudaMemcpyDeviceToHost);
  printf("Number of vectors that satisfy condition is %d\n", total_h[0]);

  free(vec_h); 
  cudaFree(vec_d);

  free(total_h); 
  cudaFree(total_d);

  return 0;
}
//计算向量数的函数
__设备无效计数(整数*向量,整数*总计,整数n,整数s)
{
int i,和=0;
对于(i=blockIdx.x*blockDim.x+threadIdx.x;i而言,问题在于_syncthreads()。对于_syncthreads()而言,要正常工作,块内的所有线程都应该能够到达它,否则某些线程将永远等待,并且程序无法退出。

在您的程序中,某些部分的u syncthreads()执行是有条件的。这就是为什么您的程序不能在一个块中处理多个线程的原因。

正如Robert在评论中所说,如果您想在GPU上生成所有(k+1)^n个排列并对其进行测试,您可以考虑一些GPU内核,如下所示:

__device__ int count;  //global variable must be initialized to zero before kernel call
__global__ void perm_generator(int k, int n, int sum) {
   int tid = blockIdx.x*blockDim.x+threadIdx.x;
   int id = tid;
   int mysum = 0;
   for ( int i = n; i > 1; i-- ) { //all n-1 vector elements
     mysum += (id % (k+1));
     id /= (k+1);
   }
   mysum += id; //last element
   if ( mysum == sum ) atomicAdd( &count, 1 );
}
内核应该使用(k+1)^n个线程来调用。如果您碰巧使用更多线程来调用内核(只是因为根据经验,块维度应该是32的倍数),您需要事先检查内核内部的tid值。
另外,cudaThreadSynchronize()也不推荐使用。请改用cudaDeviceSynchronize()

下面是一个暴力程序示例,用于枚举所有可能的向量,然后测试每个向量的和,以查看它是否与所需的和匹配

  • 假设
    n
    =向量的长度(以“数字”为单位)
  • 假设每个向量“数字”由一个无符号的数量表示
  • 假设
    k
    =最大“位数”值+1
  • 向量空间的大小由
    k
    ^
    n
  • 将此空间划分为每个线程要处理的连续向量组:(
    k
    ^
    n
    )/grid\u size
  • 为每个线程生成起始向量(即每组中的起始向量)
  • 然后,每个线程循环测试向量和,必要时增加计数,然后“增加”向量,直到每个线程处理完分配给它的连续向量组
该方案:

#include <stdio.h>
#include <thrust/host_vector.h>
#include <sys/time.h>
#include <time.h>

#define MAX_N 12
#define nTPB 256
#define GRIDSIZE (32*nTPB)


#define cudaCheckErrors(msg) \
    do { \
        cudaError_t __err = cudaGetLastError(); \
        if (__err != cudaSuccess) { \
            fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \
                msg, cudaGetErrorString(__err), \
                __FILE__, __LINE__); \
            fprintf(stderr, "*** FAILED - ABORTING\n"); \
            exit(1); \
        } \
    } while (0)


// thrust code is to quickly prototype a CPU based
// method for verification
int increment(thrust::host_vector<unsigned> &data, unsigned max){
  int pos = 0;
  int done = 0;
  int finished = 0;

  while(!done){
    data[pos]++;
    if (data[pos] >= max) {
      data[pos] = 0;
      pos++;
      if (pos >= data.size()){
        done = 1;
        finished = 1;
        }
      }
    else done = 1;
  }
  return finished;
}

__constant__ unsigned long powers[MAX_N];

__device__ unsigned vec_sum(unsigned *vector, int size){
  unsigned sum = 0;
  for (int i=0; i<size; i++) sum += vector[(i*nTPB)];
  return sum;
}

__device__ void create_vector(unsigned long index, unsigned *vector, int size){
  unsigned long residual = index;
  unsigned pos = size;
  while ((residual > 0) && (pos > 0)){
    unsigned long temp = residual/powers[pos-1];
    vector[(pos-1)*nTPB] = temp;
    residual -= temp*powers[pos-1];
    pos--;
    }
  while (pos>0) {
   vector[(pos-1)*nTPB] = 0;
   pos--;
   }
}
__device__ void increment_vector(unsigned *vector, int size, int k){
  int pos = 0;
  int done = 0;

  while(!done){
    vector[(pos*nTPB)]++;
    if (vector[pos*nTPB] >= k) {
      vector[pos*nTPB] = 0;
      pos++;
      if (pos >= size){
        done = 1;
        }
      }
    else done = 1;
  }
}

__global__ void find_vector_match(unsigned long long int *count, int k, int n, unsigned sum){
  __shared__ unsigned vecs[MAX_N *nTPB];
  unsigned *vec = &(vecs[threadIdx.x]);
  unsigned long idx = threadIdx.x+blockDim.x*blockIdx.x;
  if (idx < (k*powers[n-1])){
    unsigned long vec_count = 0;
    unsigned long vecs_per_thread = (k*powers[n-1])/(gridDim.x*blockDim.x);
    vecs_per_thread++;
    unsigned long vec_num = idx*vecs_per_thread;
    create_vector((vec_num), vec, n);
    while ((vec_count < vecs_per_thread) && (vec_num < (k*powers[n-1]))){
      if (vec_sum(vec, n) == sum) atomicAdd(count, 1UL);
      increment_vector(vec, n, k);
      vec_count++;
      vec_num++;
      }
   }
}

int main(){

// calculate on CPU first for verification
  struct timeval t1, t2, t3;
  int n, k, sum;
  printf("Enter the length of vector (maximum: %d) n=", MAX_N);
  scanf("%d",&n);
  printf("Enter the max value of vector elements k=");
  scanf("%d",&k);
  printf("Enter the sum of vector elements sum=");
  scanf("%d",&sum);
  int count = 0;
  gettimeofday(&t1, NULL);
  k++;

  thrust::host_vector<unsigned> test(n);
  thrust::fill(test.begin(), test.end(), 0);
  int finished = 0;
  do{
    if (thrust::reduce(test.begin(), test.end()) == sum) count++;
    finished = increment(test, k);
    }
    while (!finished);
  gettimeofday(&t2, NULL);
  printf("CPU count = %d, in %d seconds\n", count, t2.tv_sec - t1.tv_sec);
  unsigned long h_powers[MAX_N];
  h_powers[0] = 1;
  if (n < MAX_N)
    for (int i = 1; i<n; i++) h_powers[i] = h_powers[i-1]*k;
  cudaMemcpyToSymbol(powers, h_powers, MAX_N*sizeof(unsigned long));
  cudaCheckErrors("cudaMemcpyToSymbolfail");
  unsigned long long int *h_count, *d_count;
  h_count = (unsigned long long int *)malloc(sizeof(unsigned long long int));
  cudaMalloc((void **)&d_count, sizeof(unsigned long long int));
  cudaCheckErrors("cudaMalloc fail");
  *h_count = 0;
  cudaMemcpy(d_count, h_count, sizeof(unsigned long long int), cudaMemcpyHostToDevice);
  cudaCheckErrors("cudaMemcpy H2D fail");
  find_vector_match<<<(GRIDSIZE + nTPB -1)/nTPB, nTPB>>>(d_count, k, n, sum);
  cudaMemcpy(h_count, d_count, sizeof(unsigned long long int), cudaMemcpyDeviceToHost);
  cudaCheckErrors("cudaMemcpy D2H fail");
  gettimeofday(&t3, NULL);
  printf("GPU count = %d, in %d seconds\n", *h_count, t3.tv_sec - t2.tv_sec);

  return 0;
}
样本输出:

$ ./t260
Enter the length of vector (maximum: 12) n=2
Enter the max value of vector elements k=3
Enter the sum of vector elements sum=4
CPU count = 3, in 0 seconds
GPU count = 3, in 0 seconds
$ ./t260
Enter the length of vector (maximum: 12) n=5
Enter the max value of vector elements k=3
Enter the sum of vector elements sum=10
CPU count = 101, in 0 seconds
GPU count = 101, in 0 seconds
$ ./t260
Enter the length of vector (maximum: 12) n=9
Enter the max value of vector elements k=9
Enter the sum of vector elements sum=20
CPU count = 2714319, in 12 seconds
GPU count = 2714319, in 1 seconds
$ ./t260
Enter the length of vector (maximum: 12) n=10
Enter the max value of vector elements k=9
Enter the sum of vector elements sum=20
CPU count = 9091270, in 123 seconds
GPU count = 9091270, in 4 seconds

因此,对于较大的问题规模,朴素的蛮力GPU代码似乎比朴素的蛮力单线程CPU代码快30倍左右。(…在我的特定机器设置上:CPU=Xeon X5560,GPU=Quadro5000,CentOS 5.5,CUDA 5.0)

我假设向量元素的范围从0到
k
,并且
k
应该是一个正数?因为你用1个线程的1个threadblock调用内核,你根本没有真正的并行化任何东西。你只是在运行串行代码。你有没有尝试过并行化?你甚至有一个str吗例如,如果你有多个线程,你会让每个线程做什么?(可能是一个单独的模式测试?)每个块可能负责什么?(可能是整个测试空间的一部分?)是的,k是正数,我知道当块数和线程数为1时,代码运行串行。如何使用线程进行模式测试?要测试的空间是长度
n
的所有向量,其中每个向量元素都有
k
+1个可能值。因此,使用简单的蛮力方法,有(k+1)^n个可能要测试的向量。一种方法是让每个线程完成所有工作(向量生成、求和计算、求和测试)来测试单个向量,然后让整个网格循环通过(k+1)的整个空间^n个向量。对于正确测试的向量,可以在每个线程的末尾使用原子操作来更新
计数值。这将用于(k+1)^n适合于
unsigned long
。因此,您建议生成所有可能的向量组合,并在生成后使用一个线程进行一个组合,并检查向量是否满足条件?这是一种可能的方法。它不是特别聪明,但它的好处是应该很容易尝试,因为它与你为一个幼稚的CPU串行实现编写代码的方式。我不会预先生成向量——你会为大问题耗尽空间。我会让每个线程使用基于线程索引的算法动态生成它的唯一向量(
int idx=threadIdx.x+blockDim.x*blockIdx.x;
)这样,您一次只需要足够的存储空间来存储一个网格的向量。我删除了_syncthreads(),但它同样不能处理多个线程。这个方法也可以,我测试了它,并将它与我的方法进行了比较。它比我的代码慢了一点(在我的“大”问题上大约慢8倍),可能是因为要生成每个向量,您需要
n
-1模运算和
n
-1除法运算。平均而言,我的代码大约需要一次加法运算来生成每个向量,而不管
n
。是的,您的算法设计得很明智。
$ ./t260
Enter the length of vector (maximum: 12) n=2
Enter the max value of vector elements k=3
Enter the sum of vector elements sum=4
CPU count = 3, in 0 seconds
GPU count = 3, in 0 seconds
$ ./t260
Enter the length of vector (maximum: 12) n=5
Enter the max value of vector elements k=3
Enter the sum of vector elements sum=10
CPU count = 101, in 0 seconds
GPU count = 101, in 0 seconds
$ ./t260
Enter the length of vector (maximum: 12) n=9
Enter the max value of vector elements k=9
Enter the sum of vector elements sum=20
CPU count = 2714319, in 12 seconds
GPU count = 2714319, in 1 seconds
$ ./t260
Enter the length of vector (maximum: 12) n=10
Enter the max value of vector elements k=9
Enter the sum of vector elements sum=20
CPU count = 9091270, in 123 seconds
GPU count = 9091270, in 4 seconds