Triton cuda optimization

From mindspore-ai/akg · View interactive version

Triton cuda optimization is an AI agent skill from the GitHub repository mindspore-ai/akg. Triton CUDA 性能优化通用策略、API 限制说明和调试技巧汇总。适用于需要提升 GPU 内核性能、遇到编译/运行错误需要排查、或需要了解 CUDA 平台限制的内核代码生成和优化场景

How to use this skill

Skill file

Triton CUDA 性能优化指南

1. 性能优化策略

1.1 块大小选择

1.2 Warp 和 Stage 调优

CUDA 后端特有的两个重要参数:

@triton.autotune(
    configs=[
        triton.Config({'BLOCK_SIZE': 1024}, num_warps=4, num_stages=3),
        triton.Config({'BLOCK_SIZE': 512}, num_warps=2, num_stages=4),
    ],
    key=['n_elements'],
    restore_value=['output_ptr'],  # 必须:列出所有输出指针参数名
)

1.3 内存访问优化

1.4 算子拆分策略

1.5 Occupancy 优化

GPU 利用率(Occupancy)是性能的关键指标:

2. 数值稳定性

2.1 防溢出处理

Softmax 数值稳定化:

# 减去最大值防止 exp 溢出
max_val = tl.max(scores, axis=0)
scores = scores - max_val
p = tl.exp(scores)  # CUDA 后端直接使用 tl.exp

2.2 防负值开方

# 方差计算前确保非负
variance = tl.maximum(variance, 0.0)
std = tl.sqrt(variance + eps)

2.3 精度提升

accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
# ... 累加计算 ...
result = tl.cast(accumulator, output_dtype)

3. API 使用限制

3.1 禁止使用的语法

禁止使用: return, break, continue, lambda

Triton 内核是一次性执行完整逻辑,不支持提前返回或跳转语句。

# 错误:使用 return
@triton.jit
def kernel(ptr, n, BLOCK: tl.constexpr):
    pid = tl.program_id(0)
    if pid >= n:
        return  # 编译错误!

# 正确:使用 mask
@triton.jit
def kernel(ptr, n, BLOCK: tl.constexpr):
    pid = tl.program_id(0)
    offsets = pid * BLOCK + tl.arange(0, BLOCK)
    mask = offsets < n
    data = tl.load(ptr + offsets, mask=mask, other=0.0)
    # ... 所有代码都在同一层级执行

3.2 tl.constexpr 正确用法

3.3 输出张量创建规范

3.4 Conv 类卷积算子编写注意

torch module 中的卷积算子生成会包含一个随机权重 weight,为保证 triton 实现的结果一致,需要在 host 侧代码中生成对应的 weight:

import torch
import torch.nn as nn
import triton
import triton.language as tl

@triton.jit
def triton_kernel():
    pass

def triton_host():
    args = ...
    weight = nn.Conv2d(**args).weight.to(device)

具体的参数和 nn 中调用的 module 要与 torch 保持一致,device 设置为 "cuda"。调用 triton 之前会固定相同的随机种子,只需正确创建类的实例并导出权重。

4. 性能检查清单

内存访问

并行度配置

算子设计

数值稳定性

最佳实践总结

  1. Autotune: 使用 autotune 搜索最优 BLOCK_SIZE、num_warps、num_stages
  2. 内存合并: 确保同一 warp 内线程访问连续地址
  3. Tensor Core: MatMul 类算子启用 allow_tf32
  4. 流水线: 通过 num_stages 隐藏内存延迟
  5. 数值稳定: 使用 float32 累加,减去最大值防溢出
  6. Occupancy: 平衡寄存器和共享内存使用
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.