首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >cuda函数在cuda中的应用

cuda函数在cuda中的应用
EN

Stack Overflow用户
提问于 2015-10-05 19:00:30
回答 1查看 2K关注 0票数 1

在将矩阵A和向量x相乘得到结果y之后,我想对y应用一个函数h元素。

我想获得z= h( A_x ),其中h按元素应用于向量A_x。

我知道如何在GPU上进行矩阵/向量乘法(用cublas)。现在我想把h(这是我自己的函数,用C++编码)应用于结果向量,也是在GPU中,我怎么能这样做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-05 19:39:40

两种可能的办法是:

  1. 编写自己的CUDA内核来执行操作
  2. 使用推力 (例如每个() )。

以下是这两种方法的工作示例:

代码语言:javascript
复制
$ cat t934.cu
#include <iostream>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <thrust/for_each.h>

#define DSIZE 4

#define nTPB 256

template <typename T>
__host__ __device__ T myfunc(T &d){

  return d + 5;  // define your own function here
}

struct mytfunc
{
template <typename T>
__host__ __device__
 void operator()(T &d){

  d = myfunc(d);
  }
};

template <typename T>
__global__ void mykernel(T *dvec, size_t dsize){

  int idx = threadIdx.x+blockDim.x*blockIdx.x;
  if (idx < dsize) dvec[idx] = myfunc(dvec[idx]);
}

int main(){

  // first using kernel
  float *h_data, *d_data;
  h_data = new float[DSIZE];
  cudaMalloc(&d_data, DSIZE*sizeof(float));
  for (int i = 0; i < DSIZE; i++) h_data[i] = i;
  cudaMemcpy(d_data, h_data, DSIZE*sizeof(float), cudaMemcpyHostToDevice);
  mykernel<<<(DSIZE+nTPB-1)/nTPB,nTPB>>>(d_data, DSIZE);
  cudaMemcpy(h_data, d_data, DSIZE*sizeof(float), cudaMemcpyDeviceToHost);
  for (int i = 0; i < DSIZE; i++) std::cout << h_data[i] << ",";
  std::cout << std::endl;

  // then using thrust
  thrust::host_vector<float>   hvec(h_data, h_data+DSIZE);
  thrust::device_vector<float> dvec = hvec;
  thrust::for_each(dvec.begin(), dvec.end(), mytfunc());
  thrust::copy_n(dvec.begin(), DSIZE, std::ostream_iterator<float>(std::cout, ","));
  std::cout << std::endl;
}

$ nvcc -o t934 t934.cu
$ ./t934
5,6,7,8,
10,11,12,13,
$

注意,为了提供一个完整的示例,我从主机内存中的向量定义开始。如果您已经有了设备内存中的向量(可能是计算y=Ax的结果),那么您可以使用thrust::device_ptr包装器直接将该向量传递给CUDA内核,或者直接在推力函数中使用该向量(此方法将在前面链接的推力快速启动指南中讨论)。

我在这里做的假设是,你想要使用一个变量的任意函数。这应该可以处理myfunc中定义的任意函数。但是,对于您可能感兴趣的某些类别的函数,您可能也能够实现它一个或多个CUBLAS调用。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32955924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档