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

相关推荐
世人万千丶9 小时前
参数管理_Flutter在鸿蒙平台路由参数最佳实践
学习·flutter·华为·harmonyos·鸿蒙
遇乐的果园12 小时前
前端学习笔记-vue加载渲染优化
前端·笔记·学习
遇乐的果园13 小时前
前端学习笔记-vue状态管理优化
前端·笔记·学习
从零开始的代码生活_14 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
可乐奶茶sky14 小时前
AI Agent 学习
人工智能·学习
摇滚侠14 小时前
Java 全栈开发实战教程 课程笔记 29-33
笔记
茯苓gao15 小时前
嵌入式开发笔记:EtherCAT协议从硬件到软件完整配置指南——从零搭建一套EtherCAT通信系统
笔记·嵌入式硬件·学习
whyTeaFo15 小时前
GAMES101: Lecture 9: Shading 3(Texture Mapping cont.) ppt笔记
笔记
RD_daoyi16 小时前
外链权重暴跌至13%,品牌提及反超传统链接——2026年不做Digital PR,你的独立站等于隐形
运维·网络·学习·机器学习·搜索引擎
chase。17 小时前
【学习笔记】PointWorld:迈向通用机器人操控的3D世界模型
笔记·学习·机器人