前言
通过前两章对于triton的简单介绍,相信大家已经能够通过从源码来安装triton,同时通过triton提供的language前端写出自己想要的一些计算密集型算子。这章开始,我们通过构建一套比较标准的batch gemm的benchmark,来看看目前这些主流的代码生成工具,高性能模板库,与厂商提供的vendor library的差距。因为只有明确了目前的差距,后期关于针对性的优化才能做到点上。这一章,我将使用一个batch的gemm作为例子,来看看triton目前对其的优化能力。选batch gemm的原因是因为目前的llm中不可避免会有对应的attention操作,而attention操作中,核心的计算密集型算子就是batch的gemm,如果你能够对batch的gemm有一个很好的优化思路,那么在mlsys中大部分的算子优化类的工作对你来说将不会显得那么无从下手。
通过triton实现一个batch gemm算子
在triton的官方tutorial中给出了如何使用triton的language api来实现gemm的算子,在上一章的最后,我也给出了对应的例子以及他通过和调用torch.matmul实现的gemm在3090上的性能比较。最终可以发现,针对某些size的gemm,triton在tflops这个指标层面是能够超过cublas的实现,但是后面我通过nsight system对每个kernel的具体执行时间进行了profiling,发现在torch.matmul或者torch.bmm底层所调用的cublas的kernel并不是对应输入输出datatype以及computetype中最快的那个。所以,这样的比较就显得有些没有意义。不过,没事,这对我们建立起如何优化一个计算密集型算子来说是一个不错的入门。
其实想要通过triton实现一个batch的gemm非常简单,我们只需要将triton中原先例子里的tl.program_id(axis=0),在这个program_id上再添加一个axis来表示batch维度的并行就可以了,然后针对每个数组的变化由单batch到多batch,只用增加一个大小为矩阵size的stride偏置即可,这种实现方式其实也是cublas中cublasgemmstridedbatched命名的得来。具体的代码如下所示:
@triton.jitdef matmul_kernel( # pointers to matrices a_ptr, b_ptr, c_ptr, # matrix dimensions b, m, n, k, # the stride variables represent how much to increase the ptr by when moving by 1 # element in a particular dimension. e.g. stride_am is how much to increase a_ptr # by to get the element one row down (a has m rows) stride_ab, stride_am, stride_ak, stride_bb, stride_bk, stride_bn, stride_cb, stride_cm, stride_cn, # meta-parameters block_size_m: tl.constexpr, block_size_n: tl.constexpr, block_size_k: tl.constexpr, group_size_m: tl.constexpr, activation: tl.constexpr,): pid = tl.program_id(axis=0) offs_b = tl.program_id(axis=1) num_pid_m = tl.cdiv(m, block_size_m) num_pid_n = tl.cdiv(n, block_size_n) num_pid_k = tl.cdiv(k, block_size_k) num_pid_in_group = group_size_m * num_pid_n group_id = pid // num_pid_in_group first_pid_m = group_id * group_size_m group_size_m = min(num_pid_m - first_pid_m, group_size_m) pid_m = first_pid_m + (pid % group_size_m) pid_n = (pid % num_pid_in_group) // group_size_m offs_m = pid_m * block_size_m + tl.arange(0, block_size_m) offs_n = pid_n * block_size_n + tl.arange(0, block_size_n) offs_k = tl.arange(0, block_size_k) a_ptr = a_ptr + (offs_b * stride_ab + offs_m[:, none] * stride_am + offs_k[none, :] * stride_ak) b_ptr = b_ptr + (offs_b * stride_bb + offs_k[:, none] * stride_bk + offs_n[none, :] * stride_bn) # initialize and iteratively update accumulator acc = tl.zeros((block_size_m, block_size_n), dtype=tl.float32) for k in range(0, k, block_size_k): a = tl.load(a_ptr) b = tl.load(b_ptr) acc += tl.dot(a, b) a_ptr += block_size_k * stride_ak b_ptr += block_size_k * stride_bk c = acc.to(tl.float16) c_ptr = c_ptr + (offs_b * stride_cb + offs_m[:, none] * stride_cm + offs_n[none, :] * stride_cn) c_mask = (offs_b < b) & (offs_m[:, none] < m) & (offs_n[none, :] < n) tl.store(c_ptr, c, mask=c_mask)
然后写一个简单的单元测试,确保通过triton写出来的kernel能够和torch.matmul/torch.bmm对上即可。
torch.manual_seed(0)a = torch.randn((4, 512, 512), device='cuda', dtype=torch.float16)b = torch.randn((4, 512, 512), device='cuda', dtype=torch.float16)torch_output = torch.bmm(a, b)triton_output = matmul(a, b, activation=none)print(ftriton_output={triton_output})print(ftorch_output={torch_output})if torch.allclose(triton_output, torch_output, atol=1e-2, rtol=0): print( triton and torch match)else: print( triton and torch differ)
其实triton的language语法确实很简单,相比较cuda来说,它能够帮我们快速验证一些idea,同时给出比cublas性能相当的算子。如果你想要用cuda从0开始实现一个batch gemm并且调用tensor core,借助shared memory,register files去帮你加速运算或者优化data movement,那么这个过程是非常需要一定的高性能计算和架构的经验,你才可能拿到和cublas的kernel接近的性能。ok,有了triton的具体kernel实现,接下来其实就是要去写一个triton需要被调优的模版,需要triton从你定义的这个比较小的搜索空间中,去得到对应的最优解,从而作为本次batch gemm的最优实现,我在autotuner这块并没有花太大的精力去改进,依旧gemm例子中的模版拿来作为一个参考,具体代码如下:
@triton.autotune( configs=[ triton.config({'block_size_m': 128, 'block_size_n': 256, 'block_size_k': 64, 'group_size_m': 8}, num_stages=3, num_warps=8), triton.config({'block_size_m': 64, 'block_size_n': 256, 'block_size_k': 32, 'group_size_m': 8}, num_stages=4, num_warps=4), triton.config({'block_size_m': 128, 'block_size_n': 128, 'block_size_k': 32, 'group_size_m': 8}, num_stages=4, num_warps=4), triton.config({'block_size_m': 128, 'block_size_n': 64, 'block_size_k': 32, 'group_size_m': 8}, num_stages=4, num_warps=4), triton.config({'block_size_m': 64, 'block_size_n': 128, 'block_size_k': 32, 'group_size_m': 8}, num_stages=4, num_warps=4), triton.config({'block_size_m': 128, 'block_size_n': 32, 'block_size_k': 32, 'group_size_m': 8}, num_stages=4, num_warps=4), triton.config({'block_size_m': 64, 'block_size_n': 32, 'block_size_k': 32, 'group_size_m': 8}, num_stages=5, num_warps=2), triton.config({'block_size_m': 32, 'block_size_n': 64, 'block_size_k': 32, 'group_size_m': 8}, num_stages=5, num_warps=2), ], key=['m', 'n', 'k'],)
然后通过调用triton的do_bench就可以将你写的算子跑起来了,do_bench处在python/triton/testing.py下,其中会对每个kernel进行25次的warm_up和100次iteration,最后会根据你设置的分位数得到一个相对稳定的性能。切记,在测试每个kernel的运行情况的时候,需要将gpu的频率锁在最高频,通过下面的代码就可以做到,由于我用到的a10,a10最大频率在1695 mhz
sudo nvidia-smi --lock-gpu-clocks=1695,1695
这是通过对fp16的输入,acc_type = fp32,最终输出为fp16的batch gemm (16x4096x4096, 16x4096x4096)
通过nsight system + nvtx就可以看到每个kernel的具体实现情况:
img
添加图片注释,不超过 140 字(可选)
使用torch.bmm/torch.matmul来实现batch-gemm,其中调用的kernel名字为ampere_fp16_s1688gemm_fp16_256x64_idg8_f2f_stages_32x1_nn,该kernel运行的时间是46.059ms
那么,当我们运行triton的时候,通过同样的方式来得到同样迭代次序的kernel,nsight分析如下
img
该kernel的名字为matmul_kernel_0d1d2d3d4d5d6d7d8d9c10d11d12c13d14d15c,运行时间为35.067ms
当然通过torch.matmul调用的cublas这个算子,显然不是我们想要的那个,我们就需要去深入到cublas的具体文档,翻一翻,找出其最快的api。在后面的benchmark中,我选用了cublashgemmstridedbatched和cublasgemmstridebatchedex这两个api来分别实现batch gemm。通过cublashgemmstridedbatched启动kernel名字为ampere_h16816gemm_256x128_idg8_stages_32x3_nn,其运行时间为30.330ms
img
通过cublas的cublasgemmstridedbatchedex api构建算子性能标准
在cublas中,针对batch gemm的实现有很多种方式,我也踩了不少坑。第一次调用成了cublashgemmstridedbatched,该kernel的性能其实是不如cublasgemmstridedbatchedex,因为cublasgemmstridedbatchedex给了一个cublasgemmalgo_t algo的参数,该参数可以帮我们选择对应batch gemm的不同实现,关于algo又具有如下这么多种:
cublas_gemm_default, cublas_gemm_algo0, cublas_gemm_algo1, cublas_gemm_algo2, cublas_gemm_algo3, cublas_gemm_algo4, cublas_gemm_algo5, cublas_gemm_algo6, cublas_gemm_algo7, cublas_gemm_algo8, cublas_gemm_algo9, cublas_gemm_algo10, cublas_gemm_algo11, cublas_gemm_algo12, cublas_gemm_algo13, cublas_gemm_algo14, cublas_gemm_algo15, cublas_gemm_algo16, cublas_gemm_algo17, cublas_gemm_dfalt_tensor_op, cublas_gemm_algo0_tensor_op, cublas_gemm_algo1_tensor_op, cublas_gemm_algo2_tensor_op, cublas_gemm_algo3_tensor_op, cublas_gemm_algo4_tensor_op, cublas_gemm_algo18, cublas_gemm_algo19, cublas_gemm_algo20, cublas_gemm_algo21, cublas_gemm_algo22, cublas_gemm_algo23, cublas_gemm_algo5_tensor_op, cublas_gemm_algo6_tensor_op, cublas_gemm_algo7_tensor_op, cublas_gemm_algo8_tensor_op, cublas_gemm_algo9_tensor_op, cublas_gemm_algo10_tensor_op, cublas_gemm_algo11_tensor_op, cublas_gemm_algo12_tensor_op, cublas_gemm_algo13_tensor_op, cublas_gemm_algo14_tensor_op, cublas_gemm_algo15_tensor_op,
其中,带有_tensor_op后缀的则为调用tensor core来加速运算的。看到这么多种实现,不要慌,通过一个for-loop的遍历,就可以方便的找到速度最快的那一个,然后对应就可以得到tflops,对应实现如下:
float min_time = 0xffff; cublasgemmalgo_t algo_index; for (const auto &algo : algolist) { float total_time = 0.0; for (int i = 0; i < iteration; i++) { cudaevent_t start, end; cudaeventcreate(&start); cudaeventcreate(&end); cudaeventrecord(start, 0); cublasgemmstridedbatchedex( handle, cublas_op_n, cublas_op_n, m, n, k, &alpha, d_a, cuda_r_16f, k, m * k, d_b, cuda_r_16f, n, k * n, &beta, d_c, cuda_r_16f, n, m * n, batch_count, cuda_r_16f, static_cast(algo)); cudaeventrecord(end, 0); cudaeventsynchronize(end); float elapsed_time; cudaeventelapsedtime(&elapsed_time, start, end); total_time += elapsed_time; } float current_time = total_time / iteration; std::cout << algo: << algo << << current_time << ms << std::endl; if( current_time < min_time ) { min_time = current_time; algo_index = algo; } } std::cout << best: << algo_index << << min_time << ms << std::endl;
通过cutlass实现batch gemm算子
cutlass这里就不花过多的篇幅进行介绍了,知乎上有很多比较详细的文章,建议做gpu性能优化的同学都能够好好研究下cutlass,不得不说,cutlass的抽象层级做的确实很好,通过暴露出对应的c++模版,就可以通过这些模版组合成很多工程开发实际中可以跑的很快的算子,而且相比于直接写cuda嵌入ptx的汇编来说,开发的难易程度也被很大程度的降低,同时能带来和cublas肩比肩的效果。在本次benchmark的构建中,我使用的是2.9.1版本的cutlass,在编译的时候一定要打开所有的kernel,然后通过下面的命令进行配置:
1. git clone https://github.com/nvidia/cutlass.git 2. git checkout v2.9.13. export cudacxx=/usr/local/cuda/bin/nvcc4. mkdir build && cd build5. cmake .. -dcutlass_nvcc_archs=80 -dcutlass_library_kernels=all6. make cutlass_profiler -j16
然后我们可以通过使用cutlass_profiler来找到目前cutlass中针对应尺寸算子的tflops最优的那个实现。这里直接使用如下代码就可以得到cutlass对应的实现,同时只要在对应的workload添加不同尺寸的gemm。
triton, cutlass, cublas性能对比
通过上述的讲解,我们将所有的输入和计算过程与cublasgemmstridedbatchedex中的参数对齐,输入为fp16,输出为fp16,accumulator_type也改为fp16。在triton中需要将如下代码进行替换:
# acc = tl.zeros((block_size_m, block_size_n), dtype=tl.float32) acc = tl.zeros((block_size_m, block_size_n), dtype=tl.float16) # acc += tl.dot(a, b) acc += tl.dot(a, b, out_dtype=tl.float16)
然后把他们全部画出来,纵坐标表示的tflops,横坐标对应矩阵的shape,batch=16。我们可以看出来,目前我这个版本的tirton代码其实性能并不是很好,原因有很多,这个后面我给大家慢慢分析,最重要的其实就是triton.autotune中那些参数的选取和设定,以及后端的一些优化。cublasgemmstridedbatchedex中最快的那个algo可以看出来目前基本上占据了领先位置,也就是为什么会被称为目前gpu上去做计算密集型算子优化的上届,cutlass在某些尺寸上的batch gemm还是表现的很优秀的,但是距离最快的cublasgemmstridedbatchedex仍然有一些差距,不过只能说cutlass的优化真的牛逼,至少我知道目前国内很多hpc的组在开发对应的kernel的时候,都是选择直接魔改拼接cutlass的组件来加快整个开发流程。
img
总结
通过上述对batch gemm性能的分析,我们可以看出来triton距离cublas的性能还有一定的距离要走,在后续的教程中,我们将结合triton dialect, tritongpu dialect, 以及triton中autotuner作为核心组件来对triton的所有优化过程中有一个清晰的认识。以及通过编译手段,一步一步来逼近cublas的性能,甚至超越他。
海尔发布全球首个智慧家庭服务生态平台场景品牌三翼鸟
自动驾驶技术正在加速商业化落地,今年将是市场爆发的一年
深入浅出编译优化选项(下)
LED灯珠白光和LED灯珠中性光区别是什么
利亚德视听科技全方位助力服贸会;联建光电8K小间距天幕来了
如何使用triton的language api来实现gemm的算子
大学生的“减压神器”:科大讯飞智能录音笔SR101
西门子S7-200SMART一键启停还能这样做!
拉力试验机维护保养指南,延长设备使用寿命!培训、测试、检定
需要标准来热覆盖窗户
熙云AI可视化智慧园区管理平台v1.0的亮点
中国半导体行业看好市场无惧前行,本土企业需找准自身定位!
realme真我X50 5G手机参数曝光搭载骁龙765G处理器支持双模5G网络
滑动电阻式节气门位置传感器的工作原理和检测步骤
linux系统命令无法使用怎么办
智慧城市的位置服务如何更好的利用
怎样实现对于数据的安全保护
第十九届“广东省少年儿童发明奖”评选活动圆满落幕
易灵思Programmer工具的配置模式过程分析
电烙铁通电后不发热的原因是什么