원클릭으로
triton-ascend-basics
Triton Ascend 编程基础,包括核心概念(program_id、block、grid)、内核函数结构、装饰器用法和标准代码模式。适用使用 Triton Ascend、需要了解基本语法结构的任意内核代码生成场景
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Triton Ascend 编程基础,包括核心概念(program_id、block、grid)、内核函数结构、装饰器用法和标准代码模式。适用使用 Triton Ascend、需要了解基本语法结构的任意内核代码生成场景
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
SOC 직업 분류 기준
AscendC direct-invoke 崩溃/挂起修复索引:Kernel timeout、hang、Segmentation Fault、aic error、buffer 死锁、plog/memcheck 调试。
AscendC direct-invoke 精度失败修复索引:输出全 0/随机值、DataCopy 对齐、EnQue/DeQue 同步、FP16/FP32 精度、Cast RoundMode、DumpTensor 分段定位。
AscendC direct-invoke 工程契约:WA 使用 kernel.py + ascendc_op/,ModelNew 调用 torch.ops.npu.*,adapter 负责复制工程、CMake 构建和 npu-arch patch。适用于 dsl=ascendc 的 autoresearch 任务。
把注册式 AscendC 算子迁移为 direct-invoke 工程的保真原则:kernel 算法和 tiling 公式不乱改,只替换注册框架胶水、入口 ABI、host launch 与 PyTorch extension。
CATLASS TileShape 与 on-chip 缓存容量约束:L1/L0A/L0B/L0C 预算公式、fp16/fp32 Pingpong 双缓冲、512B 对齐与排布对 Tile 选型的影响。调参前必读。
CATLASS Gemm 性能调优:DispatchPolicy、Tile 与分核负载均衡、Swizzle、何时用 padding/Split-K/Preload。面向 AR 修改 catlass_kernel.asc 中的类型别名。
| name | triton-ascend-basics |
| description | Triton Ascend 编程基础,包括核心概念(program_id、block、grid)、内核函数结构、装饰器用法和标准代码模式。适用使用 Triton Ascend、需要了解基本语法结构的任意内核代码生成场景 |
| category | fundamental |
| version | 1.0.0 |
| metadata | {"backend":"ascend","dsl":"triton_ascend","hardware":"Atlas A2, Atlas A3","operator_patterns":"all"} |
@triton.jit
def kernel(
output_ptr, input_ptr, n_elements,
BLOCK_SIZE: tl.constexpr, CORE_NUM: tl.constexpr,
):
pid = tl.program_id(0)
num_blocks = tl.cdiv(n_elements, BLOCK_SIZE)
for block_id in range(pid, num_blocks, CORE_NUM):
offsets = block_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
data = tl.load(input_ptr + offsets, mask=mask, other=0.0)
result = compute(data)
tl.store(output_ptr + offsets, result, mask=mask)
class ModelNew(torch.nn.Module):
def __init__(self):
super().__init__()
try:
import torch
import triton
device = torch.npu.current_device()
properties = triton.runtime.driver.active.utils.get_device_properties(device)
self.VEC_CORE_NUM = properties.get("num_vectorcore", 40)
except:
self.VEC_CORE_NUM = 40
def forward(self, x):
out = torch.empty_like(x)
BLOCK_SIZE = 1024
grid = (self.VEC_CORE_NUM,) # Ascend: 固定为核心数
kernel[grid](out, x, x.numel(), BLOCK_SIZE=BLOCK_SIZE, CORE_NUM=self.VEC_CORE_NUM)
return out
offsets = block_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
data = tl.load(ptr + offsets, mask=mask, other=0.0)
result = tl.where(condition, true_val, false_val)
tl.store(out_ptr + offsets, result, mask=mask)
硬规则:
tl.load 必须带 mask 或 block_ptr boundary_check。tl.store 必须带 mask 或 block_ptr boundary_check,否则最后一个不满 block 会写坏输出。boundary_check=(0, 1);普通指针场景用显式 mask。多维任务可以展平成一维 task,但必须显式写出每一维的分解公式,并用原始 shape / stride 还原全局 offset。不要在代码里留下含义不清的中间索引。
task = tl.program_id(0)
b = task // (M * N)
rem = task - b * M * N
m = rem // N
n = rem - m * N
offset = b * stride_b + m * stride_m + n * stride_n
硬规则:
tl.atomic_add / tl.atomic_max 等原子操作,或改写调度让写唯一。task -> dim0/dim1/... 的公式,再计算 pointer offset;不要把不同维度混在一个不可读表达式里。Autotune 通过自动 benchmark 多组配置参数,找到当前硬件和数据规模下的最优配置并缓存,免去手动调参。
key 参数缓存最佳 config,动态 shape 下每组新 shape 都会触发一次完整 benchmark,反而严重拖慢性能restore_value:列出 kernel 的所有输出指针参数名。autotune benchmark 会对每个 config 反复执行 kernel,restore_value 在每次迭代前保存输出张量副本、迭代后恢复原值,防止不同 config 之间的结果互相污染。不写 restore_value 会导致验证失败。PARAM: tl.constexpr。# 正确写法:有 restore_value,grid 固定核心数
@triton.autotune(
configs=[
triton.Config({'BLOCK_SIZE': 1024}),
triton.Config({'BLOCK_SIZE': 512}),
],
key=['n_elements'],
restore_value=['output_ptr'], # ⚠ 必须:列出所有输出指针参数名
)
@triton.jit
def kernel(input_ptr, output_ptr, n_elements,
BLOCK_SIZE: tl.constexpr):
pass
# Ascend: grid 固定为核心数
grid = (VEC_CORE_NUM,)
kernel[grid](input_ptr, output_ptr, n_elements)
# 错误:缺少 restore_value → CodeChecker 会拦截,验证会失败
@triton.autotune(
configs=[...],
key=[...],
)
@triton.jit
def kernel(input_ptr, output_ptr, ...):
pass
grid = lambda meta: (...)Ascend NPU 有两类计算核心,必须根据算子类型正确选择:
硬约束:涉及 tl.dot / 矩阵乘法运算的算子必须使用 CUBE_CORE_NUM,混合运算(先 matmul 再 elementwise 后处理)也使用 CUBE_CORE_NUM。核心数获取代码和详细策略见 grid-config 文档。
torch.empty / torch.empty_like(避免 zeros/ones 初始化开销)torch.empty_like() 创建的输出默认连续以下 API 在 CUDA Triton 中存在,但在 Ascend Triton 中不支持,使用会导致编译错误:
| 不支持的 API | 替代方案 |
|---|---|
tl.any / tl.all | tl.sum(mask.to(tl.int32)) > 0 |
tl.histogram | 手动实现分桶逻辑 |
tl.sort | 手动排序或分阶段比较 |
tl.gather / tl.scatter (部分) | tl.load / tl.store + 索引计算 |
num_warps / num_ctas / num_stages (autotune 参数) | Ascend 不需要,忽略即可 |