MindSpore自定义算子中的张量维度问题

技术背景

在前面的几篇博客中,我们介绍了MindSpore框架下使用CUDA来定义本地算子的基本方法,以及配合反向传播函数的使用,这里主要探讨一下MindSpore框架对于CUDA本地算子的输入输出的规范化形式。

测试思路

MindSpore使用的CUDA算子规范化接口形式为:

extern "C" int CustomOps(int nparam, void **params, int *ndims, int64_t **shapes, const char **dtypes,
                         void *stream, void *extra)

也就是说,我们在一个.cu文件中按照这种形式写好函数接口,其中主要是规范化输入输出的形式,然后再将各项输入传给写好的CUDA Kernel函数进行计算并获得返回值。
我们可以使用一个Kernel打印函数的测试案例来说明MindSpore对于输入输出的处理:

#include <iostream>
#define THREADS 1024

__global__ void OpsKernel(const int shape0, const int *input){
    auto i = blockIdx.x * THREADS + threadIdx.x;
    if (i < shape0){
        printf("%d\n", input[i]);
    }
}

在这个函数体内,会把指定大小范围内的input的内容打印出来。

常数输入

首先我们来看一下最简单的常数输入,可以用一个最简单的整数来测试,对应的CUDA算子代码为:

// nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu

#include <iostream>
#define THREADS 1024

__global__ void OpsKernel(const int shape0, const int *input){
    auto i = blockIdx.x * THREADS + threadIdx.x;
    if (i < shape0){
        printf("%d\n", input[i]);
    }
}

extern "C" int CustomOps(int nparam, void **params, int *ndims, int64_t **shapes, const char **dtypes,
                         void *stream, void *extra){
    int *input = static_cast<int*>(params[0]);
    OpsKernel<<<1, THREADS>>>(shapes[0][0], input);
    return 0;
}

调用CUDA算子的Python代码为:

import os
import numpy as np
import mindspore as ms
from mindspore import ops, Tensor, context

context.set_context(mode=context.GRAPH_MODE, device_target="GPU")

CURRENT_PATH = os.path.abspath(__file__)
CustomOps = ops.Custom(CURRENT_PATH.replace(".py", ".so:CustomOps"),
                       out_shape=lambda x:x,
                       out_dtype=ms.int32,
                       func_type="aot")
T0 = Tensor([7], ms.int32)
print (T0)
CustomOps(T0)

运行的指令为:

$ nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu && python3 test_shape.py 
[7]
7

需要注意的是,这里只能给MindSpore内置的几种Tensor变量,如果是直接调用CustomOps(7)会报一个段错误。

高维张量输入

这里一维的张量输入我们就不做讨论了,因为跟前面用到的常数输入本质上是一样的形式。这里我们用一个二维的张量来做一个测试,CUDA代码保持不动,只修改Python代码中的输入:

import os
import numpy as np
import mindspore as ms
from mindspore import ops, Tensor, context

context.set_context(mode=context.GRAPH_MODE, device_target="GPU")

CURRENT_PATH = os.path.abspath(__file__)
CustomOps = ops.Custom(CURRENT_PATH.replace(".py", ".so:CustomOps"),
                       out_shape=lambda x:x,
                       out_dtype=ms.int32,
                       func_type="aot")
T0 = Tensor(np.arange(12).reshape((4, 3)), ms.int32)
print (T0)
CustomOps(T0)

运行结果为:

$ nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu && python3 test_shape.py 
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
0
1
2
3

需要注意的是,我们在CUDA的打印函数中设置的打印输出大小是输入张量的第一个维度的大小,我们给的是一个(4,3)大小的张量,因此会顺序打印4个数出来。这里我们也能够发现MindSpore在进行输入的规范化的时候,会自动压平输入的张量变成一个维度。因此这里的调用代码等价于先对输入张量做一个reshape,然后再把第一个维度对应大小的张量元素打印出来。如果要打印所有的元素也很简单,可以修改一下CUDA代码:

// nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu

#include <iostream>
#define THREADS 1024

__global__ void OpsKernel(const int shape0, const int *input){
    auto i = blockIdx.x * THREADS + threadIdx.x;
    if (i < shape0){
        printf("%d\n", input[i]);
    }
}

extern "C" int CustomOps(int nparam, void **params, int *ndims, int64_t **shapes, const char **dtypes,
                         void *stream, void *extra){
    int *input = static_cast<int*>(params[0]);
    int elements = 1;
    for (int i=0; i<ndims[0]; i++){
        elements *= shapes[0][i];
    }
    OpsKernel<<<1, THREADS>>>(elements, input);
    return 0;
}

通过定义一个elements变量用于存储对应张量的元素数量,然后再逐一打印出来即可,执行结果为:

$ nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu && python3 test_shape.py 
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
0
1
2
3
4
5
6
7
8
9
10
11

输出规范化

当我们使用ops.Custom算子时,如果指定了out_dtype和out_shape,那么算子会自动帮我们分配好相应的device memory空间。那么我们在CUDA计算的时候可以直接修改对应的内存空间:

// nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu

#include <iostream>
#define THREADS 1024

__global__ void OpsKernel(const int shape0, const int *input, float *output){
    auto i = blockIdx.x * THREADS + threadIdx.x;
    if (i < shape0){
        output[i] = input[i] * 0.5;
    }
}

extern "C" int CustomOps(int nparam, void **params, int *ndims, int64_t **shapes, const char **dtypes,
                         void *stream, void *extra){
    int *input = static_cast<int*>(params[0]);
    float *output = static_cast<float*>(params[1]);
    int elements = 1;
    for (int i=0; i<ndims[0]; i++){
        elements *= shapes[0][i];
    }
    OpsKernel<<<1, THREADS>>>(elements, input, output);
    return 0;
}

这里我们对算子的功能做了一点调整,我们输出的结果是整个张量的元素值乘以0.5,同时也把一个整形变量转化成了一个浮点型变量。其运行Python代码也要做一点调整:

import os
import numpy as np
import mindspore as ms
from mindspore import ops, Tensor, context

context.set_context(mode=context.GRAPH_MODE, device_target="GPU")

CURRENT_PATH = os.path.abspath(__file__)
CustomOps = ops.Custom(CURRENT_PATH.replace(".py", ".so:CustomOps"),
                       out_shape=lambda x:x,
                       out_dtype=ms.float32,
                       func_type="aot")
T0 = Tensor(np.arange(12).reshape((4, 3)), ms.int32)
print (T0)
output = CustomOps(T0)
print (output)

这里主要是修改了out_dtype为浮点型,这里如果写错了,会直接导致内存溢出。上述代码的运行结果为:

$ nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu && python3 test_shape.py 
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
[[0.  0.5 1. ]
 [1.5 2.  2.5]
 [3.  3.5 4. ]
 [4.5 5.  5.5]]

可以看到这里输出的张量形状是跟输入保持一致的,即时这个输入张量在经过MindSpore的Custom算子接口时已经被压平成一个一维张量,但是因为我们设置了out_shape=lambda x:x,这表示输出的张量shape跟输入的张量shape一致,当然,直接用Python的列表来给out_shape赋值也是可以的。例如我们写一个输入输出不同shape的案例:

// nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu

#include <iostream>
#define THREADS 1024

__global__ void OpsKernel(const int shape0, const int *input, int *output){
    auto i = blockIdx.x * THREADS + threadIdx.x;
    if (i < shape0){
        atomicAdd(&output[0], input[i]);
    }
}

extern "C" int CustomOps(int nparam, void **params, int *ndims, int64_t **shapes, const char **dtypes,
                         void *stream, void *extra){
    int *input = static_cast<int*>(params[0]);
    int *output = static_cast<int*>(params[1]);
    int elements = 1;
    for (int i=0; i<ndims[0]; i++){
        elements *= shapes[0][i];
    }
    OpsKernel<<<1, THREADS>>>(elements, input, output);
    return 0;
}

这个Kernel函数的主要功能是通过一个atomicAdd函数,把输入张量的所有元素做一个求和,这样输出的张量的shape只有[1],对应的Python调用形式也要做一定的调整:

import os
import numpy as np
import mindspore as ms
from mindspore import ops, Tensor, context

context.set_context(mode=context.GRAPH_MODE, device_target="GPU")

CURRENT_PATH = os.path.abspath(__file__)
CustomOps = ops.Custom(CURRENT_PATH.replace(".py", ".so:CustomOps"),
                       out_shape=[1],
                       out_dtype=ms.int32,
                       func_type="aot")
T0 = Tensor(np.arange(12).reshape((4, 3)), ms.int32)
print (T0)
output = CustomOps(T0)
print (output)

由于atomicAdd(addr, element)原子操作要求输入输出的类型要一致,因此这里我们还是使用的int类型的output,输出结果如下所示:

$ nvcc --shared -Xcompiler -fPIC -o test_shape.so test_shape.cu && python3 test_shape.py 
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
[66]

总结概要

当我们使用GPU进行快速运算时,虽然可以用成熟的深度学习框架如MindSpore和PyTorch等进行实现,但其实从速度上来说,最快不过直接使用C/C++的CUDA来实现。也正是因为如此,在MindSpore框架中支持了对CUDA实现的算子的直接调用,只是在格式规范上有一定的要求。本文主要介绍MindSpore调用本地CUDA算子的一些规范化和技巧。

版权声明

本文首发链接为:https://www.cnblogs.com/dechinphy/p/custom-ops-shape.html

作者ID:DechinPhy

更多原著文章:https://www.cnblogs.com/dechinphy/

请博主喝咖啡:https://www.cnblogs.com/dechinphy/gallery/image/379634.html

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在PyTorch,我们可以使用C++或CUDA编写自定义算子,并将其发布为PyTorch的扩展,以便在PyTorch使用。下面是发布自定义算子的一般步骤: 1. 编写C++或CUDA代码实现自定义算子。 2. 使用PyTorch提供的C++ API或CUDA API将算子封装为PyTorch扩展,生成动态链接库文件。可以使用setup.py或CMake来构建和安装扩展。 3. 在Python导入扩展,并使用torch.ops.register_custom_op_symbolic()函数注册算子。 4. 在Python使用自定义算子。 下面是一个简单的示例,演示了如何发布一个简单的自定义算子。 1. 编写C++代码实现自定义算子。假设我们要实现一个名为mymul的算子,它可以计算两个张量的乘积。以下是mymul的C++实现: ```c++ #include <torch/extension.h> torch::Tensor mymul(torch::Tensor x, torch::Tensor y) { return x * y; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("mymul", &mymul, "My multiply operation"); } ``` 2. 使用PyTorch提供的API将算子封装为扩展。可以使用setup.py或CMake来构建和安装扩展。以下是使用setup.py构建和安装扩展的示例: ```python from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension setup(name='mymul', ext_modules=[ CUDAExtension('mymul_cuda', [ 'mymul_cuda.cpp', 'mymul_cuda_kernel.cu', ]), CppExtension('mymul_cpp', ['mymul.cpp']), ], cmdclass={'build_ext': BuildExtension}) ``` 3. 在Python导入扩展,并使用torch.ops.register_custom_op_symbolic()函数注册算子。以下是在Python使用mymul的示例: ```python import torch from torch.utils.cpp_extension import load # 导入扩展 mymul_cpp = load('mymul_cpp', ['mymul.cpp']) # 注册算子 torch.ops.load_library(mymul_cpp.__file__) torch.ops.register_custom_op_symbolic('mymul_cpp::mymul', 2) # 创建输入张量 x = torch.tensor([1, 2, 3]) y = torch.tensor([4, 5, 6]) # 使用自定义算子 z = torch.ops.mymul_cpp.mymul(x, y) print(z) ``` 在上面的示例,我们首先导入了扩展,并使用torch.ops.load_library()函数加载它。然后,我们使用torch.ops.register_custom_op_symbolic()函数注册算子,指定算子的名称和输入参数的数量。最后,我们创建了两个输入张量x和y,并使用torch.ops.mymul_cpp.mymul()函数调用自定义算子,计算x和y的乘积。 注意,以上仅为一般步骤示例,实际上发布自定义算子需要编写更多的代码和配置文件,具体实现需要根据具体需求和环境进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值