Triton学习笔记

Ref

  1. triton案例

Triton

从Add开始入门

py 复制代码
import torch
import triton
import triton.language as tl
@triton.jit
def add_kernel(x_ptr, # *Pointer* to first input vector.
    y_ptr, # *Pointer* to second input vector.
    z_ptr, # *Pointer* to output vector.
    N, # Size of the vector.
    BLOCK_SIZE: tl.constexpr, # Num elements each program uses
    ):
    # There are multiple 'programs' processing different data.
    # We identify which program we are here:
    pid = tl.program_id(axis=0)
    # Offsets is a list of which elements this program instance will act on
    # e.g. if BLOCK_SIZE is 32 these would be
    # [0:32], [32:64], [64:96] etc, using the `pid` to find the starting index
    block_start = pid * BLOCK_SIZE
    offsets = block_start + tl.arange(0, BLOCK_SIZE)
    # Create a mask to guard memory operations against out-of-bounds acces
    mask = offsets < N
    # Load x and y, using the mask
    x = tl.load(x_ptr + offsets, mask=mask)
    y = tl.load(y_ptr + offsets, mask=mask)
    z = x + y
    # Write z back to HBM.
    tl.store(z_ptr + offsets, z, mask=mask)

可以看到,pid是以BLOCK_SIZE为单位启动的,然后你同时launch许多pid,他们找到自己执行的区域开始执行并且store回HBM

之后我们launch它:

py 复制代码
def add(x: torch.Tensor, y: torch.Tensor):
    # Preallocate the output.
    z = torch.empty_like(x)
    N = z.numel()
    # grid can be a static tuple, or a callable that returns a tuple
    # here it will be (N//BLOCK_SIZE,)
    grid = lambda meta: (triton.cdiv(N, meta['BLOCK_SIZE']), )
    add_kernel[grid](x, y, z, N, BLOCK_SIZE=1024)
    return z

虽然你传入了Tensor,但是他使用了@triton.jit,所以会自动重载到和Kernel相符合的格式

相关推荐
小羽网安2 小时前
从零开始学习 sql 注入,常见的 sql 注入解析
数据库·sql·学习
想成为优秀工程师的爸爸8 小时前
第十九篇技术笔记:UDP——相思传得快,飞鸽传书在
笔记·网络协议·tcp/ip·udp·信息与通信
stm32 菜鸟9 小时前
nucleo-f411re学习记录-12,Wifi模块ESP8684
学习
stm32 菜鸟11 小时前
nucleo-f411re学习记录-9,双轴XY摇杆传感器
学习
南子北游11 小时前
Python学习(基础语法1)
开发语言·python·学习
Yeh20205812 小时前
cookie与Session笔记
笔记
Atri厨12 小时前
X86存储器的段描述符学习随笔
学习
星幻元宇VR13 小时前
VR航空航天科普设备助力航天知识普及
人工智能·科技·学习·安全·vr·虚拟现实
d111111111d13 小时前
STM32-UART封装问题解析
笔记·stm32·单片机·嵌入式硬件·学习·算法
寒秋花开曾相惜13 小时前
(学习笔记)4.2 逻辑设计和硬件控制语言HCL(4.2.1 逻辑门&4.2.2 组合电路和HCL布尔表达式)
linux·网络·数据结构·笔记·学习·fpga开发