pytorch中使用cuda扩展
以下面这个例子作为教程,实现功能是element-wise add;
(pytorch中想调用cuda模块,还是用另外使用C编写接口脚本)
第一步:cuda编程的源文件和头文件
// mathutil_cuda_kernel.cu
// 头文件,最后一个是cuda特有的
#include <curand.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include "mathutil_cuda_kernel.h" // 获取GPU线程通道信息
dim3 cuda_gridsize(int n)
{
int k = (n - ) / BLOCK + ;
int x = k;
int y = ;
if(x > ) {
x = ceil(sqrt(k));
y = (n - ) / (x * BLOCK) + ;
}
dim3 d(x, y, );
return d;
}
// 这个函数是cuda执行函数,可以看到细化到了每一个元素
__global__ void broadcast_sum_kernel(float *a, float *b, int x, int y, int size)
{
int i = (blockIdx.x + blockIdx.y * gridDim.x) * blockDim.x + threadIdx.x;
if(i >= size) return;
int j = i % x; i = i / x;
int k = i % y;
a[IDX2D(j, k, y)] += b[k];
} // 这个函数是与c语言函数链接的接口函数
void broadcast_sum_cuda(float *a, float *b, int x, int y, cudaStream_t stream)
{
int size = x * y;
cudaError_t err; // 上面定义的函数
broadcast_sum_kernel<<<cuda_gridsize(size), BLOCK, , stream>>>(a, b, x, y, size); err = cudaGetLastError();
if (cudaSuccess != err)
{
fprintf(stderr, "CUDA kernel failed : %s\n", cudaGetErrorString(err));
exit(-);
}
}
#ifndef _MATHUTIL_CUDA_KERNEL
#define _MATHUTIL_CUDA_KERNEL #define IDX2D(i, j, dj) (dj * i + j)
#define IDX3D(i, j, k, dj, dk) (IDX2D(IDX2D(i, j, dj), k, dk)) #define BLOCK 512
#define MAX_STREAMS 512 #ifdef __cplusplus
extern "C" {
#endif void broadcast_sum_cuda(float *a, float *b, int x, int y, cudaStream_t stream); #ifdef __cplusplus
}
#endif #endif
第二步:C编程的源文件和头文件(接口函数)
// mathutil_cuda.c
// THC是pytorch底层GPU库
#include <THC/THC.h>
#include "mathutil_cuda_kernel.h" extern THCState *state; int broadcast_sum(THCudaTensor *a_tensor, THCudaTensor *b_tensor, int x, int y)
{
float *a = THCudaTensor_data(state, a_tensor);
float *b = THCudaTensor_data(state, b_tensor);
cudaStream_t stream = THCState_getCurrentStream(state); // 这里调用之前在cuda中编写的接口函数
broadcast_sum_cuda(a, b, x, y, stream); return ;
}
int broadcast_sum(THCudaTensor *a_tensor, THCudaTensor *b_tensor, int x, int y);
第三步:编译,先编译cuda模块,再编译接口函数模块(不能放在一起同时编译)
nvcc -c -o mathutil_cuda_kernel.cu.o mathutil_cuda_kernel.cu -x cu -Xcompiler -fPIC -arch=sm_52
import os
import torch
from torch.utils.ffi import create_extension this_file = os.path.dirname(__file__) sources = []
headers = []
defines = []
with_cuda = False if torch.cuda.is_available():
print('Including CUDA code.')
sources += ['src/mathutil_cuda.c']
headers += ['src/mathutil_cuda.h']
defines += [('WITH_CUDA', None)]
with_cuda = True this_file = os.path.dirname(os.path.realpath(__file__)) extra_objects = ['src/mathutil_cuda_kernel.cu.o'] # 这里是编译好后的.o文件位置
extra_objects = [os.path.join(this_file, fname) for fname in extra_objects] ffi = create_extension(
'_ext.cuda_util',
headers=headers,
sources=sources,
define_macros=defines,
relative_to=__file__,
with_cuda=with_cuda,
extra_objects=extra_objects
) if __name__ == '__main__':
ffi.build()
第四步:调用cuda模块
from _ext import cuda_util #从对应路径中调用编译好的模块 a = torch.randn(3, 5).cuda()
b = torch.randn(3, 1).cuda()
mathutil.broadcast_sum(a, b, *map(int, a.size())) # 上面等价于下面的效果: a = torch.randn(3, 5)
b = torch.randn(3, 1)
a += b
pytorch中使用cuda扩展的更多相关文章
- PyTorch中的C++扩展
今天要聊聊用 PyTorch 进行 C++ 扩展. 在正式开始前,我们需要了解 PyTorch 如何自定义module.这其中,最常见的就是在 python 中继承torch.nn.Module,用 ...
- PyTorch中的CUDA操作
CUDA(Compute Unified Device Architecture)是NVIDIA推出的异构计算平台,PyTorch中有专门的模块torch.cuda来设置和运行CUDA相关操作.本 ...
- pytorch中调用C进行扩展
pytorch中调用C进行扩展,使得某些功能在CPU上运行更快: 第一步:编写头文件 /* src/my_lib.h */ int my_lib_add_forward(THFloatTensor * ...
- PyTorch官方中文文档:PyTorch中文文档
PyTorch中文文档 PyTorch是使用GPU和CPU优化的深度学习张量库. 说明 自动求导机制 CUDA语义 扩展PyTorch 多进程最佳实践 序列化语义 Package参考 torch to ...
- Pytorch中RoI pooling layer的几种实现
Faster-RCNN论文中在RoI-Head网络中,将128个RoI区域对应的feature map进行截取,而后利用RoI pooling层输出7*7大小的feature map.在pytorch ...
- PyTorch中的MIT ADE20K数据集的语义分割
PyTorch中的MIT ADE20K数据集的语义分割 代码地址:https://github.com/CSAILVision/semantic-segmentation-pytorch Semant ...
- pytorch中tensorboardX的用法
在代码中改好存储Log的路径 命令行中输入 tensorboard --logdir /home/huihua/NewDisk1/PycharmProjects/pytorch-deeplab-xce ...
- [Pytorch]Pytorch中tensor常用语法
原文地址:https://zhuanlan.zhihu.com/p/31494491 上次我总结了在PyTorch中建立随机数Tensor的多种方法的区别. 这次我把常用的Tensor的数学运算总结到 ...
- 详解Pytorch中的网络构造,模型save和load,.pth权重文件解析
转载:https://zhuanlan.zhihu.com/p/53927068 https://blog.csdn.net/wangdongwei0/article/details/88956527 ...
随机推荐
- IP分片攻击——就是发送部分分片报文,让对方一直等待从而耗对方内存的DoS攻击
为了传送一个大的IP报文,IP协议栈需要根据链路接口的MTU对该IP报文进行分片,通过填充适当的IP头中的分片指示字段,接收计算机可以很容易的把这些IP分片报文组装起来. 目标计算机在处理这些分片 ...
- 遗传算法介绍并附上Python代码
之前介绍过遗传算法,参见:https://www.cnblogs.com/LoganChen/p/7509702.html 我们用Python实现同样的问题解答. y=10*sin(5*x)+7*ab ...
- ArcGIS for Server 10.2 发布Feature Service
折腾一下午,终于把自带的例子发布成Feature Service了,这样就可以通过web编辑了.记录一下步骤. 环境:已经安装好SQL Server 2008 R2,ArcGIS for Deskto ...
- IDEA 注释模板
类.接口.等文件注释: /** * @Description: * @author: tangsw * @date: ${DATE} ${TIME} * */ 方法上注释: /** * @Descri ...
- map test
// mapTest.cpp : Defines the entry point for the console application. // #include "stdafx.h&quo ...
- Worldview in Context
Worldview in Context Figures 1 and 2 provide a basis for a deeper understanding of worldview. The se ...
- 一个.java文件中是否可以有多个类
前段时间,有个同事问到我这个问题:一个.java文件中是否可以有多个类? 答案:可以有多个类,但最多只能有一个被public修饰的class. 且若这个.java文件中有一个public类型的clas ...
- linux 运维基本操作
本记录来自腾讯云实验 https://cloud.tencent.com/developer/labs/lab/10000 目录操作 任务时间:5min ~ 10min 创建目录 使用 mkdir ...
- exception java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
1.情景展示 Java 报错信息如下: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 2.原因分析 首先,这是越界异常,但不是数组越 ...
- keepalived haproxy 主备配置
global_defs { router_id k8s_master} vrrp_script chk_http_port {script "/etc/keepalived/check_ha ...