如何使用cub :: DeviceReduce :: ArgMin

问题描述

我对如何使用 cub :: DeviceReduce :: ArgMin()感到困惑。 在这里,我复制了CUB文档中的代码。

#include <cub/cub.cuh> 
// Declare,allocate,and initialize device-accessible pointers for input and output
int                      num_items;      // e.g.,7
int                      *d_in;          // e.g.,[8,6,7,5,3,9],located in GPU
KeyValuePair<int,int>   *d_out;         // e.g.,[{-,-}]

// Determine temporary device storage requirements
void     *d_temp_storage = NULL;
size_t   temp_storage_bytes = 0;
cub::DeviceReduce::ArgMin(d_temp_storage,temp_storage_bytes,d_in,d_out,num_items);
// Allocate temporary storage
cudaMalloc(&d_temp_storage,temp_storage_bytes);
// Run argmin-reduction
cub::DeviceReduce::ArgMin(d_temp_storage,num_items);
// d_out <-- [{5,0}]

问题如下:

  1. 如果 d_in 是指向某些 GPU内存(设备)的指针,那么如何初始化 d_out 的指针?
  2. 如果 ArgMin()的操作已在设备(GPU)中完成,如何将结果复制到CPU?

解决方法

如果d_in是指向某些GPU内存(设备)的指针,那么如何初始化d_out的指针?

您使用cudaMalloc,类似于初始化d_in指针的方式。

如果ArgMin()的操作已在设备(GPU)中完成,如何将结果复制到CPU?

您使用cudaMemcpy,类似于将d_in数据从主机复制到设备的方式,只不过现在您正在将d_out数据从设备复制到主机。 KeyValuePair是具有keyvalue成员的C ++对象。

这是一个完整的示例:

$ cat t37.cu
#include <cub/cub.cuh>
#include <iostream>

int main(){


  // Declare,allocate,and initialize device-accessible pointers for input and output
  int                      num_items = 32;
  int                      *d_in;
  cub::KeyValuePair<int,int>   *d_out;

  int *h_in = new int[num_items];
  cub::KeyValuePair<int,int> *h_out = new cub::KeyValuePair<int,int>;
  cudaMalloc(&d_in,num_items*sizeof(d_in[0]));
  cudaMalloc(&d_out,sizeof(cub::KeyValuePair<int,int>));
  for (int i = 0; i < num_items; i++) h_in[i] = 4;
  h_in[12] = 2;  // so we expect our return tuple to be 12,2
  cudaMemcpy(d_in,h_in,num_items*sizeof(d_in[0]),cudaMemcpyHostToDevice);

  // Determine temporary device storage requirements
  void     *d_temp_storage = NULL;
  size_t   temp_storage_bytes = 0;
  cub::DeviceReduce::ArgMin(d_temp_storage,temp_storage_bytes,d_in,d_out,num_items);
  // Allocate temporary storage
  cudaMalloc(&d_temp_storage,temp_storage_bytes);
  // Run argmin-reduction
  cub::DeviceReduce::ArgMin(d_temp_storage,num_items);

  cudaMemcpy(h_out,int>),cudaMemcpyDeviceToHost);
  std::cout << "minimum value: " << h_out[0].value << std::endl;
  std::cout << "index of min:  " << h_out[0].key << std::endl;
}
$ nvcc -o t37 t37.cu -arch=sm_35 -std=c++14 -Wno-deprecated-gpu-targets
$ ./t37
minimum value: 2
index of min:  12
$

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...