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相符合的格式

相关推荐
sinat_2554878114 小时前
泛型:类·学习笔记
java·jvm·笔记·学习
被考核重击14 小时前
计算机网络核心知识点笔记
网络·笔记·计算机网络
鱼鳞_14 小时前
Java学习笔记_Day21(Set)
java·笔记·学习
鹅天帝14 小时前
20260407网安学习日志——序列化漏洞
前端·学习·web安全·网络安全·xss
何如呢14 小时前
FPGA初学习2
学习
头疼的程序员14 小时前
计算机网络:自顶向下方法(第七版)第八章 学习分享(二)
学习·计算机网络
世人万千丶15 小时前
开源鸿蒙跨平台Flutter开发:幼儿园成语序列与海马体印迹锚定引擎-突触链式网络渲染架构
学习·flutter·开源·harmonyos·鸿蒙
迷路爸爸18015 小时前
Docker 入门学习笔记 02:基础命令、前后台运行,以及 attach、logs、exec 的区别
笔记·学习·docker
Dovis(誓平步青云)15 小时前
《QT学习第二篇:QT的常用控件属性与按钮、view系列、Label、输入框》
开发语言·qt·学习
艾莉丝努力练剑15 小时前
【Linux系统:多线程】线程概念与控制
linux·运维·服务器·c++·后端·学习·操作系统