ワンクリックで
triton-cuda-basics
Triton CUDA 编程基础,包括核心概念(program_id、block、grid)、内核函数结构、装饰器用法和标准代码模式。适用于使用 Triton CUDA、需要了解基本语法结构的任意 CUDA 内核代码生成场景
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
メニュー
Triton CUDA 编程基础,包括核心概念(program_id、block、grid)、内核函数结构、装饰器用法和标准代码模式。适用于使用 Triton CUDA、需要了解基本语法结构的任意 CUDA 内核代码生成场景
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
SOC 職業分類に基づく
矩阵乘法矩阵乘法 A[M, K] @ B[K, N] = C[M, N]中,大K维度矩阵乘法(K>>M,N)优化:针对M/N较小但K极大(如M=N=256,K=131072)的场景,Split-K切分K维度并行化、Workspace+Reduce替代全局同步,实现显著性能提升
Triton Ascend hard API restrictions and forbidden syntax. MUST-follow rules that apply to every kernel: forbidden control flow (return/break/continue/lambda/while), tensor slice/index restrictions, scalar conversion rules, BLOCK_SIZE upper bound. Violating any of these produces a compile or runtime error on Ascend.
Triton Ascend 性能优化通用策略: BLOCK_SIZE 选择 (1024-2048 for elementwise, must be <65536), grid configuration (use VEC_CORE_NUM / CUBE_CORE_NUM, 2D/3D grid for matmul / conv / reduce, 1D grid + inner loop for elementwise / pointwise), 256B alignment for memory transfers, autotune block-size patterns, fp16 / fp32 precision conversion. Bind via keywords like matmul, elementwise, reduce, block_size, grid, autotune, alignment, fp16, fp32, tile, interleaved-loop, cube-core, vec-core.
通过 adaptive_search 或 evolve 搜索式 workflow 生成优化算子。 后台 silent mode 执行,轮询监控进度。
适用于归约(reduce)类算子和含归约子步骤的复合算子(如归一化)的优化指南。典型算子包括:sum, mean, max, min, prod, argmax, argmin, cumsum, cumprod, softmax, logsoftmax, layernorm, rmsnorm, groupnorm, instancenorm, batchnorm, l1norm, l2norm, frobeniusnorm, var, std, average_pooling, sum_pooling 等。特别重要:当归约维度不是最后一维(如 dim=1 归约 shape=[B,F,D1,D2]),需要正确处理多维索引和两阶段归约。包含 PyTorch normalized_shape 多轴归一化语义说明。不适用于纯逐元素运算或矩阵乘法。如果算子是损失函数(先逐元素计算再全局归约),应选择 elementwise-reduce-fused 指南。
CPU C++ 算子核心概念、标准结构模式、KernelBench 代码规范和内嵌扩展方法
| name | triton-cuda-basics |
| description | Triton CUDA 编程基础,包括核心概念(program_id、block、grid)、内核函数结构、装饰器用法和标准代码模式。适用于使用 Triton CUDA、需要了解基本语法结构的任意 CUDA 内核代码生成场景 |
| category | fundamental |
| version | 1.0.0 |
| metadata | {"backend":"cuda","dsl":"triton_cuda","operator_patterns":"all"} |
@triton.jit 装饰的 Python 函数,编译后在 GPU 上并行执行(num_blocks_x, num_blocks_y)BLOCK_SIZE = 1024grid_size = ceil(total_elements / block_size)所有 Triton 内核都遵循相同的五步结构模式:
@triton.jit
def standard_kernel(
output_ptr, input_ptr, n_elements,
BLOCK_SIZE: tl.constexpr,
):
# 1. 获取程序 ID 和计算偏移
pid = tl.program_id(0)
offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
# 2. 创建边界掩码
mask = offsets < n_elements
# 3. 加载数据
data = tl.load(input_ptr + offsets, mask=mask)
# 4. 执行计算
result = compute_function(data)
# 5. 存储结果
tl.store(output_ptr + offsets, result, mask=mask)
def launch_kernel(input_tensor, output_tensor):
BLOCK_SIZE = 1024
grid = (triton.cdiv(input_tensor.numel(), BLOCK_SIZE),)
kernel[grid](
output_tensor, input_tensor, input_tensor.numel(),
BLOCK_SIZE=BLOCK_SIZE,
)
class ModelNew(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_tensor):
output_tensor = torch.empty_like(input_tensor)
BLOCK_SIZE = 1024
grid = (triton.cdiv(input_tensor.numel(), BLOCK_SIZE),)
kernel[grid](
output_tensor, input_tensor, input_tensor.numel(),
BLOCK_SIZE=BLOCK_SIZE,
)
return output_tensor
# 基本边界检查
offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
data = tl.load(ptr + offsets, mask=mask, other=0.0)
# 使用 tl.where 进行条件选择
result = tl.where(condition, true_value, false_value)
# 复杂条件的掩码组合
valid_mask = (offsets < n_elements) & (offsets >= 0)
data = tl.load(ptr + offsets, mask=valid_mask, other=0.0)
Autotune 通过自动 benchmark 多组配置参数,找到当前硬件和数据规模下的最优配置并缓存,免去手动调参。
key 参数缓存最佳 config,动态 shape 下每组新 shape 都会触发一次完整 benchmark,反而严重拖慢性能restore_value:列出 kernel 的所有输出指针参数名。autotune benchmark 会对每个 config 反复执行 kernel,restore_value 在每次迭代前保存输出张量副本、迭代后恢复原值,防止不同 config 之间的结果互相污染。不写 restore_value 会导致验证失败。grid = lambda meta: (...),确保 grid 能根据当前 config 动态计算。PARAM: tl.constexpr。# 正确写法:有 restore_value
@triton.autotune(
configs=[
triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 32}, num_stages=4, num_warps=4),
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32}, num_stages=5, num_warps=2),
],
key=['M', 'N', 'K'],
restore_value=['c_ptr'], # ⚠ 必须:列出所有输出指针参数名
)
@triton.jit
def matmul_kernel(
a_ptr, b_ptr, c_ptr,
M, N, K,
stride_am, stride_ak, stride_bk, stride_bn, stride_cm, stride_cn,
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_N: tl.constexpr,
BLOCK_SIZE_K: tl.constexpr,
):
pass
grid = lambda meta: (triton.cdiv(M, meta['BLOCK_SIZE_M']) * triton.cdiv(N, meta['BLOCK_SIZE_N']),)
matmul_kernel[grid](a, b, c, M, N, K, ...)
# 错误:缺少 restore_value → CodeChecker 会拦截,验证会失败
@triton.autotune(
configs=[...],
key=[...],
)
@triton.jit
def kernel(input_ptr, output_ptr, ...):
pass