diff --git a/docs/source/builder-cli.md b/docs/source/builder-cli.md index a4c80025b..6c876b709 100644 --- a/docs/source/builder-cli.md +++ b/docs/source/builder-cli.md @@ -349,7 +349,7 @@ Install a kernels skill for an AI assistant Default value: `cuda-kernels` - Possible values: `cuda-kernels`, `cpu-kernels`, `rocm-kernels`, `xpu-kernels` + Possible values: `cuda-kernels`, `cpu-kernels`, `rocm-kernels`, `triton-kernels`, `xpu-kernels` * `--claude` — Install for Claude * `--codex` — Install for Codex diff --git a/docs/source/builder/agents-guide.md b/docs/source/builder/agents-guide.md index 0e6eb4e3d..3b7b59213 100644 --- a/docs/source/builder/agents-guide.md +++ b/docs/source/builder/agents-guide.md @@ -2,7 +2,7 @@ Code agents are a good fit to build custom kernels because the hard part is not just writing in Domain Specific Language (DSLs) like CUDA. You also need the right project layout, PyTorch bindings, architecture-specific choices, model-specific integration, and trustworthy benchmarks. -Kernels on Hugging Face are compatible with agents via skills and the `hf` CLI. The `cuda-kernels`, `rocm-kernels`, `xpu-kernels`, and `cpu-kernels` skills contain knowledge so an agent can generate and publish a complete kernel project, instead of isolated snippets. +Kernels on Hugging Face are compatible with agents via skills and the `hf` CLI. The `cuda-kernels`, `rocm-kernels`, `xpu-kernels`, `cpu-kernels`, and `triton-kernels` skills contain knowledge so an agent can generate and publish a complete kernel project, instead of isolated snippets. This guide is for **authoring new kernels**. If you only want to **load an existing precompiled kernel**, use `get_kernel()` instead. diff --git a/docs/source/cli-skills.md b/docs/source/cli-skills.md index 90586d1f4..eb17c8913 100644 --- a/docs/source/cli-skills.md +++ b/docs/source/cli-skills.md @@ -6,6 +6,7 @@ Supported skills include: - `rocm-kernels` - `xpu-kernels` - `cpu-kernels` +- `triton-kernels` Skill files are downloaded from the `huggingface/kernels` directory in this [repository](https://github.com/huggingface/kernels/tree/main/kernel-builder/skills). @@ -22,6 +23,15 @@ Example CPU kernels built with this skill (available on the Hub under [`kernels- - [`kernels-community/quantization-gptq`](https://huggingface.co/kernels-community/quantization-gptq) — INT4 quantized GEMM using AVX512. - [`kernels-community/rmsnorm`](https://huggingface.co/kernels-community/rmsnorm) — RMSNorm with AVX2/AVX512 element-wise paths. +> [!TIP] +> **When are Triton kernels useful?** Two main cases: +> - **Portability across NVIDIA and AMD** — a single Triton kernel runs on both CUDA and ROCm without modification. No vendor-specific code needed. +> - **Fusing multiple ops to reduce memory traffic** — operations like softmax (5 PyTorch ops, ~8MN memory ops) become a single kernel (2MN ops) with a ~4x reduction in DRAM round-trips. Any chain of element-wise + reduction ops that PyTorch executes as separate kernels is a fusion opportunity. + +Example Triton kernels built with this skill: + +- [`jaygala223/triton-layernorm`](https://huggingface.co/kernels/jaygala223/triton-layernorm) — fused LayerNorm with fp32 accumulation, ~1.45x faster than PyTorch on V100. + Examples: ```bash diff --git a/kernel-builder/skills/triton-kernels/CHANGELOG.md b/kernel-builder/skills/triton-kernels/CHANGELOG.md new file mode 100644 index 000000000..e3e4b67d8 --- /dev/null +++ b/kernel-builder/skills/triton-kernels/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +## v1.0.0 (2026-06-24) + +- Initial release of vendor-neutral Triton skill +- SKILL.md with core DSL patterns, autotune, numerics, benchmarking, and integration guidance +- Reference kernels: softmax, matmul with tiling, RMSNorm +- references/: autotune guide, kernel patterns (dropout, fused add+norm, SwiGLU, group-major), benchmarking guide +- scripts/: benchmark and correctness test templates +- examples/: fused softmax with correctness test + benchmark harness diff --git a/kernel-builder/skills/triton-kernels/SKILL.md b/kernel-builder/skills/triton-kernels/SKILL.md new file mode 100644 index 000000000..5b6e7c7ab --- /dev/null +++ b/kernel-builder/skills/triton-kernels/SKILL.md @@ -0,0 +1,540 @@ +| name | triton-kernels | +| --- | --- | +| description | Provides guidance for writing and benchmarking portable Triton kernels targeting NVIDIA and AMD GPUs. Covers core DSL patterns, @triton.autotune, numerics (fp16/bf16/fp8), masked loads, reductions, tiling, benchmarking harness, correctness testing, and integration with HuggingFace Kernels Hub (get_kernel). Vendor-neutral: points to rocm-kernels and xpu-kernels for backend-specific tuning. | +| disable-model-invocation | false | +| user-invocable | true | +| allowed-tools | Read, Grep, Glob, Bash | +| argument-hint | kernel type: softmax, matmul, rmsnorm, layernorm, activation, reduction, element-wise, autotune, benchmark, correctness, get_kernel, transformers, diffusers | + +# Portable Triton Kernels + +This skill provides patterns and guidance for developing portable, optimized +Triton kernels that run on NVIDIA and AMD GPUs without modification. For +backend-specific tuning, see [rocm-kernels](../rocm-kernels/SKILL.md) (AMD) and +[xpu-kernels](../xpu-kernels/SKILL.md) (Intel). + +## When This Skill Applies + +Use this skill when: + +- Writing new Triton kernels for normalization, activation, attention, or linear algebra ops +- Deciding block sizes, num_warps, num_stages, and autotune configs +- Handling numerics (fp32 accumulation, bf16/fp16 input/output, masked values) +- Setting up correctness tests against a PyTorch reference +- Benchmarking kernel throughput (GB/s or TFLOPS) +- Publishing a Triton kernel to the HuggingFace Kernels Hub via get_kernel +- Fusing multiple ops into a single kernel to reduce DRAM round-trips + +## Hard Constraints + +1. **BLOCK_SIZE for reductions must cover the full reduction dimension.** Use + `triton.next_power_of_2(dim)` in the Python wrapper. Never autotune BLOCK_SIZE + when it controls the reduction axis — partial rows give wrong results silently. + +2. **Masked loads need a safe `other` value.** Use `other=0.0` for additive + contexts (sum, dot product). Use `other=float('-inf')` for max-based reductions + (softmax numerator). Using the wrong fill value is the #1 cause of subtle + numerical bugs. + +3. **Accumulate in fp32.** Cast inputs to `tl.float32` before reductions. Cast + back to the input dtype only at the final `tl.store`. Half-precision + accumulation compounds rounding errors across hundreds of additions. + +4. **All tensors must be contiguous.** Assert `x.is_contiguous()` in the Python + wrapper, or call `.contiguous()` before computing pointers. Non-contiguous + tensors break flat-offset pointer arithmetic. + +5. **tl.constexpr parameters must be known at compile time.** BLOCK_SIZE, + num_warps, num_stages are compile-time constants. Pass them as kernel + arguments with the `: tl.constexpr` annotation or via autotune configs. + +## Core DSL Patterns + +### Program IDs and Grid Launch + +Every Triton kernel is launched as a grid of programs. Each program gets a unique +ID via `tl.program_id(axis)`. + +```python +@triton.jit +def my_kernel(x_ptr, output_ptr, n_elements, BLOCK_SIZE: tl.constexpr): + pid = tl.program_id(axis=0) + block_start = pid * BLOCK_SIZE + offsets = block_start + tl.arange(0, BLOCK_SIZE) + mask = offsets < n_elements + + x = tl.load(x_ptr + offsets, mask=mask, other=0.0) + # ... compute ... + tl.store(output_ptr + offsets, result, mask=mask) +``` + +Grid sizing: +```python +grid = (triton.cdiv(n_elements, BLOCK_SIZE),) +my_kernel[grid](x, output, n_elements, BLOCK_SIZE=1024) +``` + +For 2D grids (e.g. matmul): +```python +grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N)) +# program_id(0) = row block, program_id(1) = col block +``` + +### Masked Loads and Stores + +Always mask when BLOCK_SIZE may exceed the actual dimension: + +```python +offsets = tl.arange(0, BLOCK_SIZE) +mask = offsets < n_cols +x = tl.load(ptr + offsets, mask=mask, other=0.0) +tl.store(out_ptr + offsets, result, mask=mask) +``` + +### 2D Pointer Arithmetic (Tiling) + +For loading 2D tiles (matmul, attention): + +```python +row_offsets = row_start * BLOCK_M + tl.arange(0, BLOCK_M) +col_offsets = col_start * BLOCK_N + tl.arange(0, BLOCK_N) + +# Broadcasting: [:, None] makes column vector, [None, :] makes row vector +ptrs = base_ptr + row_offsets[:, None] * stride_row + col_offsets[None, :] +mask = (row_offsets[:, None] < M) & (col_offsets[None, :] < N) +tile = tl.load(ptrs, mask=mask, other=0.0) +``` + +### Reductions + +Row-wise reduction (softmax, layernorm, rmsnorm): + +```python +# One program per row. BLOCK_SIZE >= n_cols (next power of 2). +pid = tl.program_id(0) +row_start = pid * stride_row +offsets = tl.arange(0, BLOCK_SIZE) +mask = offsets < n_cols + +x = tl.load(x_ptr + row_start + offsets, mask=mask, other=0.0).to(tl.float32) +row_sum = tl.sum(x, axis=0) +row_max = tl.max(x, axis=0) +``` + +### The dot Product (Tile-Level Matmul) + +`tl.dot(a, b)` performs a tile-level matrix multiply that maps to tensor cores. +Requires both operands to have their K dimension >= 16. + +```python +# a_tile: (BLOCK_M, BLOCK_K), b_tile: (BLOCK_K, BLOCK_N) +acc += tl.dot(a_tile, b_tile) # acc: (BLOCK_M, BLOCK_N) +``` + +## Autotune + +`@triton.autotune` benchmarks multiple kernel configurations at runtime and +caches the fastest one per problem shape. + +```python +@triton.autotune( + configs=[ + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 256, 'BLOCK_K': 64}, num_stages=3, num_warps=8), + triton.Config({'BLOCK_M': 64, 'BLOCK_N': 128, 'BLOCK_K': 32}, num_stages=4, num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'BLOCK_K': 32}, num_stages=4, num_warps=4), + triton.Config({'BLOCK_M': 64, 'BLOCK_N': 64, 'BLOCK_K': 32}, num_stages=5, num_warps=2), + ], + key=['M', 'N', 'K'], # re-tune when these values change +) +@triton.jit +def matmul_kernel(..., BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr): + ... +``` + +Guidelines: + +- **key=** lists the runtime values that affect which config is fastest. Usually + the matrix dimensions. +- **num_warps**: More warps = more threads per program. Large tiles (128x256) need + 8-16 warps. Small tiles (32x64) need 2-4. +- **num_stages**: Software pipelining. With N stages, N-1 tiles are being + prefetched while 1 is being computed. More stages need more SRAM. Use 2-3 for + memory-bound ops, 3-5 for compute-bound. +- **When NOT to autotune**: Never autotune a parameter that controls the reduction + dimension (BLOCK_D for rmsnorm, BLOCK_SIZE for softmax row width). The kernel + silently produces wrong results if the autotuner picks a value smaller than the + actual dimension. +- **Grid as lambda**: When block sizes are autotuned, use a lambda for the grid + since dimensions aren't known until a config is selected: + ```python + grid = lambda meta: (triton.cdiv(M, meta['BLOCK_M']) * triton.cdiv(N, meta['BLOCK_N']),) + ``` + +### num_warps Heuristic + +```python +num_warps = 4 +if BLOCK_SIZE >= 2048: + num_warps = 8 +if BLOCK_SIZE >= 4096: + num_warps = 16 +``` + +### num_stages Heuristic + +```python +# Query SRAM per SM if available, otherwise default to 2 +num_stages = 4 if sram_per_sm > 200_000 else 2 +``` + +## Numerics + +### fp32 Accumulation (Critical) + +```python +# Load in native dtype, cast to fp32 for compute, cast back for store +x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32) +# ... reductions and arithmetic in fp32 ... +tl.store(out_ptr + offsets, result.to(tl.float16), mask=mask) +``` + +Without fp32 accumulation, a sum over 512+ elements in fp16 accumulates visible +rounding error (max_abs_diff > 1e-2 vs torch reference). + +### Safe Softmax Pattern + +```python +x = tl.load(x_ptr + offsets, mask=mask, other=float('-inf')).to(tl.float32) +x_max = tl.max(x, axis=0) +x = x - x_max # shift for numerical stability +numerator = tl.exp(x) # exp(-inf) = 0, harmless +denominator = tl.sum(numerator, axis=0) +result = numerator / denominator +``` + +The `other=float('-inf')` ensures masked positions don't affect the max or the +sum (since exp(-inf) = 0). + +### Dtype Handling + +```python +# Detect input dtype and cast back at the end +input_dtype = x.dtype # only works outside @triton.jit; inside, use tl.float16 etc. + +# Inside kernel: always accumulate in fp32 +x_fp32 = x.to(tl.float32) +# ... compute ... +out = result.to(x_fp32.dtype) # won't work — use explicit dtype +out = result.to(tl.bfloat16) # explicit cast +``` + +## Reference Kernel: Softmax + +Complete fused softmax — one DRAM read, one DRAM write per row: + +```python +@triton.jit +def softmax_kernel(x_ptr, output_ptr, n_cols, stride_row, BLOCK_SIZE: tl.constexpr): + pid = tl.program_id(0) + row_start = pid * stride_row + offsets = tl.arange(0, BLOCK_SIZE) + mask = offsets < n_cols + + x = tl.load(x_ptr + row_start + offsets, mask=mask, other=float('-inf')).to(tl.float32) + x_max = tl.max(x, axis=0) + x = x - x_max + numerator = tl.exp(x) + denominator = tl.sum(numerator, axis=0) + result = numerator / denominator + + tl.store(output_ptr + row_start + offsets, result.to(tl.float16), mask=mask) + + +def softmax(x: torch.Tensor) -> torch.Tensor: + assert x.is_contiguous() + n_rows, n_cols = x.shape + output = torch.empty_like(x) + BLOCK_SIZE = triton.next_power_of_2(n_cols) + num_warps = 4 if BLOCK_SIZE <= 1024 else (8 if BLOCK_SIZE <= 4096 else 16) + softmax_kernel[(n_rows,)]( + x, output, n_cols, x.stride(0), + BLOCK_SIZE=BLOCK_SIZE, num_warps=num_warps, + ) + return output +``` + +Why this beats PyTorch: naive softmax does ~8MN memory ops (max, subtract, exp, +sum, divide — each round-trips through DRAM). This kernel does 2MN (one read, +one write). ~4x reduction in memory traffic. + +## Reference Kernel: Matmul with Tiling + +Blocked matrix multiplication with accumulation loop: + +```python +@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_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, +): + pid_m = tl.program_id(0) + pid_n = tl.program_id(1) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + for k in range(0, K, BLOCK_K): + rk = k + tl.arange(0, BLOCK_K) + + a = tl.load(a_ptr + rm[:, None] * stride_am + rk[None, :] * stride_ak, + mask=(rm[:, None] < M) & (rk[None, :] < K), other=0.0) + b = tl.load(b_ptr + rk[:, None] * stride_bk + rn[None, :] * stride_bn, + mask=(rk[:, None] < K) & (rn[None, :] < N), other=0.0) + + acc += tl.dot(a, b) + + c = acc.to(tl.float16) + tl.store(c_ptr + rm[:, None] * stride_cm + rn[None, :] * stride_cn, c, + mask=(rm[:, None] < M) & (rn[None, :] < N)) +``` + +Key points: +- Accumulate in fp32, store in target dtype +- `other=0.0` for masked positions — zeros don't affect addition +- `tl.dot` requires K dimension >= 16 + +## Reference Kernel: RMSNorm + +```python +@triton.jit +def rmsnorm_kernel( + x_ptr, weight_ptr, out_ptr, + stride_row, D, + eps: tl.constexpr, + HAS_WEIGHT: tl.constexpr, + BLOCK_D: tl.constexpr, +): + row = tl.program_id(0) + offsets = tl.arange(0, BLOCK_D) + mask = offsets < D + + x = tl.load(x_ptr + row * stride_row + offsets, mask=mask, other=0.0).to(tl.float32) + variance = tl.sum(x * x, axis=0) / D + rms_inv = tl.rsqrt(variance + eps) + + if HAS_WEIGHT: + w = tl.load(weight_ptr + offsets, mask=mask, other=1.0).to(tl.float32) + out = x * rms_inv * w + else: + out = x * rms_inv + + tl.store(out_ptr + row * stride_row + offsets, out.to(x.dtype), mask=mask) + + +def triton_rmsnorm(x, weight=None, eps=1e-6): + assert x.is_contiguous() + x_2d = x.view(-1, x.shape[-1]) + out = torch.empty_like(x_2d) + M, D = x_2d.shape + has_weight = weight is not None + if not has_weight: + weight = torch.empty(0, device=x.device) + BLOCK_D = triton.next_power_of_2(D) + num_warps = 4 if BLOCK_D <= 1024 else (8 if BLOCK_D <= 4096 else 16) + rmsnorm_kernel[(M,)]( + x_2d, weight, out, x_2d.stride(0), D, eps, has_weight, + BLOCK_D=BLOCK_D, num_warps=num_warps, num_stages=2, + ) + return out.view_as(x) +``` + +## Benchmarking + +### Throughput Measurement + +Use `triton.testing.do_bench` for accurate GPU timing: + +```python +ms = triton.testing.do_bench(lambda: my_kernel_wrapper(x)) +``` + +### GB/s Calculation + +For memory-bound kernels (softmax, rmsnorm, activations): + +```python +# Total bytes moved = bytes_read + bytes_written +# For in-place-like ops: 2 * numel * element_size (one read + one write) +gbps = 2 * x.numel() * x.element_size() * 1e-9 / (ms * 1e-3) +``` + +### TFLOPS Calculation + +For compute-bound kernels (matmul): + +```python +# Matmul: 2*M*N*K FLOPs (multiply + add for each output element) +tflops = 2 * M * N * K * 1e-12 / (ms * 1e-3) +``` + +### Benchmark Harness Template + +```python +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=['N'], + x_vals=[128 * i for i in range(2, 100)], + line_arg='provider', + line_vals=['triton', 'torch'], + line_names=['Triton', 'PyTorch'], + styles=[('blue', '-'), ('green', '-')], + ylabel='GB/s', + plot_name='kernel-performance', + args={'M': 4096}, + )) +def benchmark(M, N, provider): + x = torch.randn(M, N, device='cuda', dtype=torch.float32) + if provider == 'torch': + ms = triton.testing.do_bench(lambda: torch.softmax(x, dim=-1)) + elif provider == 'triton': + ms = triton.testing.do_bench(lambda: my_softmax(x)) + gbps = 2 * x.numel() * x.element_size() * 1e-9 / (ms * 1e-3) + return gbps + +benchmark.run(save_path='.', print_data=True) +``` + +### Correctness Testing + +Always validate against PyTorch before benchmarking: + +```python +def test_kernel(size, atol=1e-3, rtol=1e-3): + torch.manual_seed(0) + x = torch.randn(size, device='cuda') + y_triton = my_kernel(x) + y_ref = torch_reference(x) + torch.testing.assert_close(y_triton, y_ref, atol=atol, rtol=rtol) + print("PASSED") + +# Test with irregular shapes to verify masking +test_kernel((1823, 781)) +test_kernel((1, 1)) +test_kernel((4096, 4096)) +``` + +## HuggingFace Kernels Hub Integration + +Load pre-compiled kernels from the Hub (no local compilation): + +```python +from kernels import get_kernel, has_kernel + +# Check availability and load +if has_kernel("kernels-community/activation", version=1): + activation = get_kernel("kernels-community/activation", version=1) + y = torch.empty_like(x) + activation.gelu_fast(y, x) +``` + +For Triton kernels specifically, the kernel is packaged as a noarch build (no +per-CUDA-version compilation needed). The `build.toml` uses `backends = ["triton"]`. + +### Publishing Your Own Triton Kernel + +```toml +# build.toml +[general] +name = "my-triton-kernel" +backends = ["triton"] +version = 1 +license = "Apache-2.0" + +[general.hub] +repo-id = "your-username/my-triton-kernel" +``` + +Build and upload: +```bash +kernel-builder build-and-upload +``` + +## Transformers Integration + +Patch model modules with your custom kernel: + +```python +from transformers import AutoModelForCausalLM + +def patch_rmsnorm(model): + for name, module in model.named_modules(): + if type(module).__name__ == 'RMSNorm': + eps = getattr(module, 'variance_epsilon', None) or getattr(module, 'eps', 1e-6) + has_weight = hasattr(module, 'weight') and module.weight is not None + if has_weight: + def make_forward(mod, epsilon): + def forward(x): + return triton_rmsnorm(x, mod.weight, eps=epsilon) + return forward + module.forward = make_forward(module, eps) + +model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype=torch.bfloat16) +model.to("cuda") +patch_rmsnorm(model) +``` + +Key points: +- Use `type(module).__name__` not `isinstance()` (catches all RMSNorm variants) +- Weight may be None if `elementwise_affine=False` +- Inject before `enable_model_cpu_offload()` + +## Common Pitfalls + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Silent wrong results | Autotuned BLOCK_SIZE < reduction dim | Compute BLOCK_SIZE = triton.next_power_of_2(dim) in wrapper, never autotune | +| NaN / huge values | fp16 accumulation overflow | Cast to tl.float32 before reductions | +| Wrong softmax output | other=0.0 in masked load | Use other=float('-inf') for max-reduction inputs | +| Crash on non-contiguous input | Flat offset math assumes contiguity | Assert is_contiguous() or call .contiguous() | +| "K >= 16" error from tl.dot | BLOCK_K too small | Minimum BLOCK_K = 16 (tensor core constraint) | +| Autotune runs every call | Missing key= parameter | Add key=['M', 'N', 'K'] to cache across calls | +| Performance worse than PyTorch at small N | Kernel launch overhead dominates | Triton kernels shine at large N; small N is launch-bound | + +## Performance Profiling + +```bash +# NVIDIA +nsys profile -o profile python your_kernel.py +ncu --set full -o metrics python your_kernel.py + +# AMD (ROCm) — see rocm-kernels skill +rocprof --stats python your_kernel.py +``` + +## See Also + +### Scripts + +- [benchmark_template.py](scripts/benchmark_template.py) — Reusable benchmark harness for any Triton kernel +- [correctness_template.py](scripts/correctness_template.py) — Correctness test template + +### References + +- [autotune-guide.md](references/autotune-guide.md) — Deep dive on autotune configs, key parameter, and pitfalls +- [kernel-patterns.md](references/kernel-patterns.md) — Additional kernel patterns (dropout, fused add+norm, element-wise) +- [benchmarking-guide.md](references/benchmarking-guide.md) — GB/s vs TFLOPS, roofline analysis, when to expect gains + +### Backend-Specific Skills + +- [rocm-kernels](../rocm-kernels/SKILL.md) — AMD MI355X / R9700 tuning, ROCm constraints +- [xpu-kernels](../xpu-kernels/SKILL.md) — Intel XPU Triton tuning + +### External Resources + +- [Triton Documentation](https://triton-lang.org/) +- [HuggingFace Kernels Documentation](https://huggingface.co/docs/kernels/) +- [Community Kernels on Hub](https://huggingface.co/kernels-community) diff --git a/kernel-builder/skills/triton-kernels/examples/fused_softmax.py b/kernel-builder/skills/triton-kernels/examples/fused_softmax.py new file mode 100644 index 000000000..ffa254c39 --- /dev/null +++ b/kernel-builder/skills/triton-kernels/examples/fused_softmax.py @@ -0,0 +1,113 @@ +""" +Example: Fused Softmax kernel in Triton. + +Demonstrates: +- Row-wise reduction with masking +- Numerical stability (subtract max before exp) +- fp32 accumulation +- Correctness test + benchmark vs PyTorch + +This kernel reads each row from DRAM once, does all computation in SRAM, +and writes back once. PyTorch's softmax does ~8MN memory ops; this does 2MN. +""" + +import torch +import triton +import triton.language as tl + +DEVICE = torch.device(f'cuda:{torch.cuda.current_device()}') + + +@triton.jit +def softmax_kernel(x_ptr, output_ptr, n_cols, stride_row, BLOCK_SIZE: tl.constexpr): + # One program per row + pid = tl.program_id(0) + row_start = pid * stride_row + offsets = tl.arange(0, BLOCK_SIZE) + mask = offsets < n_cols + + # Load row into SRAM. Masked positions get -inf (won't affect max or sum). + x = tl.load(x_ptr + row_start + offsets, mask=mask, other=float('-inf')).to(tl.float32) + + # Numerically stable softmax + x_max = tl.max(x, axis=0) + x = x - x_max + numerator = tl.exp(x) # exp(-inf) = 0, harmless in sum + denominator = tl.sum(numerator, axis=0) + result = numerator / denominator + + # Write back. Masked positions are not stored. + tl.store(output_ptr + row_start + offsets, result, mask=mask) + + +def triton_softmax(x: torch.Tensor) -> torch.Tensor: + """Fused softmax along the last dimension.""" + assert x.is_contiguous() + assert x.ndim == 2 + + n_rows, n_cols = x.shape + output = torch.empty_like(x) + + # BLOCK_SIZE must cover the full row (reduction dimension) + BLOCK_SIZE = triton.next_power_of_2(n_cols) + num_warps = 4 if BLOCK_SIZE <= 1024 else (8 if BLOCK_SIZE <= 4096 else 16) + + # One program per row + softmax_kernel[(n_rows,)]( + x, output, n_cols, x.stride(0), + BLOCK_SIZE=BLOCK_SIZE, num_warps=num_warps, + ) + return output + + +# ============================================================ +# Correctness test +# ============================================================ + +def test_softmax(): + torch.manual_seed(0) + # Irregular shape to verify masking + x = torch.randn(1823, 781, device=DEVICE, dtype=torch.float32) + y_triton = triton_softmax(x) + y_ref = torch.softmax(x, dim=-1) + torch.testing.assert_close(y_triton, y_ref, atol=1e-3, rtol=1e-3) + print("Correctness: PASSED") + + +# ============================================================ +# Benchmark +# ============================================================ + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=['N'], + x_vals=[128 * i for i in range(2, 100)], + line_arg='provider', + line_vals=['triton', 'torch'], + line_names=['Triton', 'PyTorch'], + styles=[('blue', '-'), ('green', '-')], + ylabel='GB/s', + plot_name='softmax-performance', + args={'M': 4096}, + )) +def benchmark(M, N, provider): + x = torch.randn(M, N, device=DEVICE, dtype=torch.float32) + + stream = torch.cuda.Stream() + torch.cuda.set_stream(stream) + + if provider == 'torch': + ms = triton.testing.do_bench(lambda: torch.softmax(x, dim=-1)) + elif provider == 'triton': + ms = triton.testing.do_bench(lambda: triton_softmax(x)) + + gbps = 2 * x.numel() * x.element_size() * 1e-9 / (ms * 1e-3) + return gbps + + +if __name__ == "__main__": + test_softmax() + + import sys + if len(sys.argv) > 1 and sys.argv[1] == "--benchmark": + benchmark.run(save_path='.', print_data=True) diff --git a/kernel-builder/skills/triton-kernels/examples/skill_test_layernorm.py b/kernel-builder/skills/triton-kernels/examples/skill_test_layernorm.py new file mode 100644 index 000000000..da298bbaa --- /dev/null +++ b/kernel-builder/skills/triton-kernels/examples/skill_test_layernorm.py @@ -0,0 +1,193 @@ +""" +LayerNorm kernel generated by an AI agent using the triton-kernels skill. + +This kernel was written following the patterns in: + kernel-builder/skills/triton-kernels/SKILL.md + +Demonstrates: +- Row-wise reduction (mean + variance) +- fp32 accumulation +- Masked loads with other=0.0 +- Correctness test against torch.nn.functional.layer_norm +- Benchmark harness (GB/s) +""" + +import torch +import triton +import triton.language as tl + +DEVICE = torch.device(f'cuda:{torch.cuda.current_device()}') + + +@triton.jit +def layernorm_kernel( + x_ptr, weight_ptr, bias_ptr, out_ptr, + stride_row, D, + eps: tl.constexpr, + HAS_WEIGHT: tl.constexpr, + HAS_BIAS: tl.constexpr, + BLOCK_D: tl.constexpr, +): + # One program per row (following SKILL.md reduction pattern) + row = tl.program_id(0) + offsets = tl.arange(0, BLOCK_D) + mask = offsets < D + + # Load row into SRAM, accumulate in fp32 (SKILL.md: Hard Constraint #3) + x = tl.load(x_ptr + row * stride_row + offsets, mask=mask, other=0.0).to(tl.float32) + + # Compute mean + mean = tl.sum(x, axis=0) / D + + # Compute variance — zero out masked positions so they don't contribute + x_centered = tl.where(mask, x - mean, 0.0) + variance = tl.sum(x_centered * x_centered, axis=0) / D + + # Normalize + inv_std = tl.rsqrt(variance + eps) + x_norm = x_centered * inv_std + + # Apply affine transform if weight/bias exist + if HAS_WEIGHT: + w = tl.load(weight_ptr + offsets, mask=mask, other=1.0).to(tl.float32) + x_norm = x_norm * w + if HAS_BIAS: + b = tl.load(bias_ptr + offsets, mask=mask, other=0.0).to(tl.float32) + x_norm = x_norm + b + + # Store back in input dtype (SKILL.md: cast back only at final store) + tl.store(out_ptr + row * stride_row + offsets, x_norm, mask=mask) + + +def triton_layernorm(x, weight=None, bias=None, eps=1e-5): + """LayerNorm wrapper following SKILL.md conventions.""" + # Hard Constraint #4: assert contiguous + assert x.is_contiguous() + + x_2d = x.view(-1, x.shape[-1]) + out = torch.empty_like(x_2d) + M, D = x_2d.shape + + has_weight = weight is not None + has_bias = bias is not None + if not has_weight: + weight = torch.empty(0, device=x.device) + if not has_bias: + bias = torch.empty(0, device=x.device) + + # Hard Constraint #1: BLOCK_D covers full reduction dimension + BLOCK_D = triton.next_power_of_2(D) + # num_warps heuristic from SKILL.md + num_warps = 4 if BLOCK_D <= 1024 else (8 if BLOCK_D <= 4096 else 16) + + layernorm_kernel[(M,)]( + x_2d, weight, bias, out, + x_2d.stride(0), D, eps, + has_weight, has_bias, + BLOCK_D=BLOCK_D, num_warps=num_warps, num_stages=2, + ) + return out.view_as(x) + + +# ============================================================ +# Correctness test (SKILL.md: always validate before benchmarking) +# ============================================================ + +def test_layernorm(): + print("=" * 60) + print("LayerNorm Correctness Tests") + print("=" * 60) + + torch.manual_seed(0) + test_cases = [ + ((1823, 781), "irregular shape"), + ((1, 1), "single element"), + ((4096, 4096), "large square"), + ((32, 127), "small irregular"), + ((2048, 2048), "power of 2"), + ] + + # Test WITHOUT weight/bias + print("\nWithout affine parameters:") + for shape, desc in test_cases: + x = torch.randn(shape, device=DEVICE, dtype=torch.float32) + y_triton = triton_layernorm(x, eps=1e-5) + y_ref = torch.nn.functional.layer_norm(x, [shape[-1]], eps=1e-5) + try: + torch.testing.assert_close(y_triton, y_ref, atol=1e-3, rtol=1e-3) + print(f" PASSED: {desc} {shape}") + except AssertionError as e: + print(f" FAILED: {desc} {shape}: {e}") + + # Test WITH weight and bias + print("\nWith affine parameters:") + for shape, desc in test_cases: + D = shape[-1] + x = torch.randn(shape, device=DEVICE, dtype=torch.float32) + weight = torch.randn(D, device=DEVICE, dtype=torch.float32) + bias = torch.randn(D, device=DEVICE, dtype=torch.float32) + y_triton = triton_layernorm(x, weight=weight, bias=bias, eps=1e-5) + y_ref = torch.nn.functional.layer_norm(x, [D], weight=weight, bias=bias, eps=1e-5) + try: + torch.testing.assert_close(y_triton, y_ref, atol=1e-3, rtol=1e-3) + print(f" PASSED: {desc} {shape}") + except AssertionError as e: + print(f" FAILED: {desc} {shape}: {e}") + + # Test bf16 + print("\nBFloat16:") + x = torch.randn(1024, 1024, device=DEVICE, dtype=torch.bfloat16) + weight = torch.randn(1024, device=DEVICE, dtype=torch.bfloat16) + bias = torch.randn(1024, device=DEVICE, dtype=torch.bfloat16) + y_triton = triton_layernorm(x, weight=weight, bias=bias, eps=1e-5) + y_ref = torch.nn.functional.layer_norm(x, [1024], weight=weight, bias=bias, eps=1e-5) + try: + torch.testing.assert_close(y_triton, y_ref, atol=1e-2, rtol=1e-2) + print(f" PASSED: bf16 (1024, 1024)") + except AssertionError as e: + print(f" FAILED: bf16: {e}") + + print() + + +# ============================================================ +# Benchmark (SKILL.md: GB/s for memory-bound kernels) +# ============================================================ + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=['N'], + x_vals=[128 * i for i in range(2, 80)], + line_arg='provider', + line_vals=['triton', 'torch'], + line_names=['Triton', 'PyTorch'], + styles=[('blue', '-'), ('green', '-')], + ylabel='GB/s', + plot_name='layernorm-performance', + args={'M': 4096}, + )) +def benchmark(M, N, provider): + x = torch.randn(M, N, device=DEVICE, dtype=torch.float32) + weight = torch.randn(N, device=DEVICE, dtype=torch.float32) + bias = torch.randn(N, device=DEVICE, dtype=torch.float32) + + stream = torch.cuda.Stream() + torch.cuda.set_stream(stream) + + if provider == 'torch': + ms = triton.testing.do_bench(lambda: torch.nn.functional.layer_norm(x, [N], weight=weight, bias=bias)) + elif provider == 'triton': + ms = triton.testing.do_bench(lambda: triton_layernorm(x, weight=weight, bias=bias)) + + # Memory: read x + weight + bias, write output + # Approximate as 2 * M * N (dominant terms) + gbps = 2 * x.numel() * x.element_size() * 1e-9 / (ms * 1e-3) + return gbps + + +if __name__ == "__main__": + test_layernorm() + + import sys + if len(sys.argv) > 1 and sys.argv[1] == "--benchmark": + benchmark.run(save_path='.', print_data=True) diff --git a/kernel-builder/skills/triton-kernels/manifest.txt b/kernel-builder/skills/triton-kernels/manifest.txt new file mode 100644 index 000000000..ac093509f --- /dev/null +++ b/kernel-builder/skills/triton-kernels/manifest.txt @@ -0,0 +1,8 @@ +SKILL.md +references/autotune-guide.md +references/kernel-patterns.md +references/benchmarking-guide.md +scripts/benchmark_template.py +scripts/correctness_template.py +examples/fused_softmax.py +CHANGELOG.md diff --git a/kernel-builder/skills/triton-kernels/references/autotune-guide.md b/kernel-builder/skills/triton-kernels/references/autotune-guide.md new file mode 100644 index 000000000..8ffeafc2e --- /dev/null +++ b/kernel-builder/skills/triton-kernels/references/autotune-guide.md @@ -0,0 +1,136 @@ +# Autotune Guide + +## What @triton.autotune Does + +At the first call with a given set of `key` values, Triton compiles every config, +benchmarks each one, picks the fastest, and caches the result. Subsequent calls +with the same key values use the cached winner instantly. When key values change, +it re-benchmarks. + +## Config Structure + +```python +triton.Config( + kwargs={'BLOCK_M': 128, 'BLOCK_N': 256, 'BLOCK_K': 64}, + num_stages=3, + num_warps=8, +) +``` + +- **kwargs**: compile-time constants passed to the kernel +- **num_warps**: number of warps (groups of 32 threads on NVIDIA, 64 on AMD) per program +- **num_stages**: software pipelining depth + +## The key Parameter + +```python +@triton.autotune(configs=[...], key=['M', 'N', 'K']) +``` + +`key` lists the runtime arguments whose values determine which config is fastest. +When any key value changes, the autotuner re-runs. + +Typical choices: +- Matmul: `key=['M', 'N', 'K']` +- Element-wise: `key=['n_elements']` +- Row reduction: `key=['n_cols']` + +## When NOT to Autotune + +Never autotune a parameter that controls the reduction dimension width: + +```python +# DANGEROUS — if autotuner picks BLOCK_D = 64 but D = 2048, only first 64 +# elements of each row are processed. Results are silently wrong. +@triton.autotune(configs=[ + triton.Config({'BLOCK_D': 64}), + triton.Config({'BLOCK_D': 128}), + triton.Config({'BLOCK_D': 256}), +], key=['M']) +def rmsnorm_kernel(..., BLOCK_D: tl.constexpr): + ... +``` + +Instead, compute it in the wrapper: + +```python +def rmsnorm(x, weight, eps=1e-6): + M, D = x.shape + BLOCK_D = triton.next_power_of_2(D) # always covers full row + rmsnorm_kernel[(M,)](x, weight, out, D, BLOCK_D=BLOCK_D) +``` + +Safe things to autotune: +- BLOCK_M, BLOCK_N for matmul output tile (programs handle independent tiles) +- BLOCK_K for the K-loop step size (you loop over the full K regardless) +- num_warps, num_stages + +## num_warps Selection + +| Tile size | Recommended num_warps | +| --- | --- | +| <= 1024 elements | 2-4 | +| 1024-4096 elements | 4-8 | +| >= 4096 elements | 8-16 | + +More warps = more threads = better for larger tiles. But more warps also means +more register pressure per program, which can reduce occupancy (programs per SM). + +## num_stages Selection + +| Workload type | Recommended num_stages | +| --- | --- | +| Memory-bound (softmax, norm, activation) | 2 | +| Compute-bound (matmul) | 3-5 | +| Large SRAM available (>200KB/SM) | 4 | +| Small SRAM (<100KB/SM) | 2 | + +More stages means more tiles "in flight" (being prefetched while current one +computes), but each stage uses SRAM to hold a tile. Too many stages and you +run out of SRAM. + +## Grid as Lambda + +When block sizes are autotuned, the grid can't be computed before the config is +selected. Use a lambda: + +```python +grid = lambda meta: ( + triton.cdiv(M, meta['BLOCK_M']) * triton.cdiv(N, meta['BLOCK_N']), +) +autotuned_kernel[grid](a, b, c, M, N, K) +``` + +## Practical Config Sets + +### Matmul (good starting point) + +```python +configs = [ + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 256, 'BLOCK_K': 64, 'GROUP_SIZE': 8}, num_stages=3, num_warps=8), + triton.Config({'BLOCK_M': 64, 'BLOCK_N': 256, 'BLOCK_K': 32, 'GROUP_SIZE': 8}, num_stages=4, num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'BLOCK_K': 32, 'GROUP_SIZE': 8}, num_stages=4, num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'BLOCK_K': 32, 'GROUP_SIZE': 8}, num_stages=4, num_warps=4), + triton.Config({'BLOCK_M': 64, 'BLOCK_N': 128, 'BLOCK_K': 32, 'GROUP_SIZE': 8}, num_stages=4, num_warps=4), + triton.Config({'BLOCK_M': 64, 'BLOCK_N': 64, 'BLOCK_K': 32, 'GROUP_SIZE': 8}, num_stages=5, num_warps=2), +] +``` + +### Element-wise with varying sizes + +```python +configs = [ + triton.Config({'BLOCK_SIZE': 1024}, num_warps=4), + triton.Config({'BLOCK_SIZE': 2048}, num_warps=8), + triton.Config({'BLOCK_SIZE': 4096}, num_warps=16), +] +``` + +## Debugging Autotune + +Set `TRITON_PRINT_AUTOTUNING=1` environment variable to see which config wins +and the benchmark times for each. + +```bash +TRITON_PRINT_AUTOTUNING=1 python your_script.py +``` diff --git a/kernel-builder/skills/triton-kernels/references/benchmarking-guide.md b/kernel-builder/skills/triton-kernels/references/benchmarking-guide.md new file mode 100644 index 000000000..a4d26b492 --- /dev/null +++ b/kernel-builder/skills/triton-kernels/references/benchmarking-guide.md @@ -0,0 +1,154 @@ +# Benchmarking Guide + +## Two Types of Kernels, Two Metrics + +### Memory-bound kernels (softmax, rmsnorm, activations, dropout) + +These are bottlenecked by how fast you can read/write DRAM, not by compute. +Measure in **GB/s** (gigabytes per second). + +```python +bytes_moved = bytes_read + bytes_written +gbps = bytes_moved * 1e-9 / (ms * 1e-3) +``` + +For most element-wise and reduction ops, `bytes_moved = 2 * numel * element_size` +(one read + one write). + +### Compute-bound kernels (matmul, attention) + +These are bottlenecked by arithmetic throughput. Measure in **TFLOPS**. + +```python +# Matmul: 2*M*N*K flops (one multiply + one add per output element per K step) +tflops = 2 * M * N * K * 1e-12 / (ms * 1e-3) +``` + +## How to Know Which Type You Have + +Use the roofline model. Compute the **arithmetic intensity** (flops per byte of +memory traffic): + +``` +AI = flops / bytes_moved +``` + +Compare to the machine's compute-to-bandwidth ratio: + +``` +machine_balance = peak_tflops / peak_bandwidth_TB_s +``` + +- If AI < machine_balance: memory-bound (measure GB/s) +- If AI > machine_balance: compute-bound (measure TFLOPS) + +Examples: +- Softmax: AI ≈ 5 flops/byte → memory-bound on all GPUs +- Matmul (large): AI ≈ M*N*K / (M*K + K*N + M*N) → compute-bound for large dims +- Matmul (small, e.g. 64x64): often memory-bound due to launch overhead + +## GPU Bandwidth References + +| GPU | HBM Bandwidth | Peak FP32 TFLOPS | +| --- | --- | --- | +| V100 | 900 GB/s | 15.7 | +| A100 | 2.0 TB/s | 19.5 | +| H100 | 3.35 TB/s | 67 | +| MI355X | 8 TB/s | — | + +A kernel achieving >70% of theoretical bandwidth is considered well-optimized +for a memory-bound workload. + +## triton.testing.do_bench + +The standard way to time Triton kernels: + +```python +ms = triton.testing.do_bench(lambda: my_kernel(x)) +``` + +This handles: +- GPU warmup (discards first few runs) +- Synchronization (waits for GPU to finish before timing) +- Multiple iterations (averages over many runs) +- Returns milliseconds + +Do NOT use `time.time()` or `torch.cuda.Event` manually unless you have a good +reason. `do_bench` handles the subtleties correctly. + +## Benchmark Harness + +`triton.testing.perf_report` + `Benchmark` gives you plots and CSV output: + +```python +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=['N'], # x-axis parameter + x_vals=[128 * i for i in range(2, 100)], # x-axis values + line_arg='provider', # what varies across lines + line_vals=['triton', 'torch'], + line_names=['Triton', 'PyTorch'], + styles=[('blue', '-'), ('green', '-')], + ylabel='GB/s', + plot_name='my-kernel-performance', + args={'M': 4096}, # fixed args + )) +def benchmark(M, N, provider): + x = torch.randn(M, N, device='cuda', dtype=torch.float32) + if provider == 'torch': + ms = triton.testing.do_bench(lambda: torch.softmax(x, dim=-1)) + elif provider == 'triton': + ms = triton.testing.do_bench(lambda: my_softmax(x)) + gbps = 2 * x.numel() * x.element_size() * 1e-9 / (ms * 1e-3) + return gbps + +benchmark.run(save_path='.', print_data=True) +``` + +This generates: +- A PNG plot saved to `save_path` +- A CSV with raw data +- Optionally prints a table to stdout + +## When to Expect Gains Over PyTorch + +Triton kernels typically beat PyTorch when: + +1. **Fusion opportunity**: Multiple PyTorch ops that each round-trip through DRAM + can be fused into one kernel. Example: softmax (5 ops → 1 kernel, ~4x fewer + memory ops). + +2. **Large N**: At small N, kernel launch overhead dominates. Triton kernels have + slightly higher launch overhead than PyTorch's pre-compiled CUDA kernels. The + crossover is typically around N=10K-100K elements. + +3. **Non-standard shapes**: PyTorch's kernels are tuned for common shapes. For + unusual dimensions, a Triton kernel with proper masking can outperform. + +Triton kernels typically DON'T beat PyTorch when: + +1. **The op already has a highly optimized CUDA implementation**: cuBLAS matmul, + cuDNN convolution, Flash Attention. These have years of hand-tuning. + +2. **Small inputs**: Launch overhead dominates. + +3. **Single element-wise op**: PyTorch already fuses simple element-wise chains + via torch.compile. + +## Accurate Benchmarking Checklist + +1. Use a dedicated CUDA stream: + ```python + stream = torch.cuda.Stream() + torch.cuda.set_stream(stream) + ``` + +2. Ensure inputs are on GPU and contiguous before timing. + +3. Don't include memory allocation in the timed region. + +4. Run correctness test FIRST — a fast but wrong kernel is useless. + +5. Test multiple input sizes — performance characteristics change with scale. + +6. Report the GPU model, dtype, and input shapes alongside numbers. diff --git a/kernel-builder/skills/triton-kernels/references/kernel-patterns.md b/kernel-builder/skills/triton-kernels/references/kernel-patterns.md new file mode 100644 index 000000000..d59700b8d --- /dev/null +++ b/kernel-builder/skills/triton-kernels/references/kernel-patterns.md @@ -0,0 +1,156 @@ +# Kernel Patterns + +Additional Triton kernel patterns beyond what's covered in SKILL.md. + +## Dropout (In-SRAM Mask Generation) + +The key insight: generate the random mask in SRAM and consume it immediately, +never writing it to DRAM. This reduces memory traffic from ~6N (PyTorch) to 2N. + +```python +@triton.jit +def dropout_kernel(x_ptr, output_ptr, n_elements, p, seed, BLOCK_SIZE: tl.constexpr): + pid = tl.program_id(0) + offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + mask = offsets < n_elements + + x = tl.load(x_ptr + offsets, mask=mask) + random = tl.rand(seed, offsets) # deterministic hash: (seed, offset) -> float in [0,1) + x_keep = random > p + output = tl.where(x_keep, x / (1 - p), 0.0) + tl.store(output_ptr + offsets, output, mask=mask) + + +def triton_dropout(x, p, seed): + assert x.is_contiguous() + output = torch.empty_like(x) + n = x.numel() + BLOCK_SIZE = 1024 + grid = (triton.cdiv(n, BLOCK_SIZE),) + dropout_kernel[grid](x, output, n, p, seed, BLOCK_SIZE=BLOCK_SIZE) + return output +``` + +Key points: +- `tl.rand(seed, offsets)` is a deterministic hash. Same seed + same offset = same + random value. This gives free reproducibility without storing the mask. +- Inverted dropout: scale by `1/(1-p)` during training so no scaling needed at inference. + +## Fused Add + RMSNorm (Residual Connection) + +Fuse the residual addition and normalization into one kernel to avoid an extra +DRAM read/write of the intermediate sum: + +```python +@triton.jit +def fused_add_rmsnorm_kernel( + x_ptr, residual_ptr, weight_ptr, out_ptr, + stride_row, D, eps: tl.constexpr, + BLOCK_D: tl.constexpr, +): + row = tl.program_id(0) + offsets = tl.arange(0, BLOCK_D) + mask = offsets < D + + x = tl.load(x_ptr + row * stride_row + offsets, mask=mask, other=0.0).to(tl.float32) + res = tl.load(residual_ptr + row * stride_row + offsets, mask=mask, other=0.0).to(tl.float32) + + # Fused: add residual then normalize + h = x + res + variance = tl.sum(h * h, axis=0) / D + rms_inv = tl.rsqrt(variance + eps) + w = tl.load(weight_ptr + offsets, mask=mask, other=1.0).to(tl.float32) + out = h * rms_inv * w + + tl.store(out_ptr + row * stride_row + offsets, out.to(tl.float16), mask=mask) +``` + +Without fusion: 3 DRAM passes (read x, read residual, write sum, read sum, write norm). +With fusion: 2 DRAM passes (read x + residual, write norm). + +## Element-wise Activation (SiLU / Swish) + +Simple pattern: one program per block of elements, flat indexing. + +```python +@triton.jit +def silu_kernel(x_ptr, out_ptr, n_elements, BLOCK_SIZE: tl.constexpr): + pid = tl.program_id(0) + offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + mask = offsets < n_elements + + x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32) + result = x * tl.sigmoid(x) + tl.store(out_ptr + offsets, result.to(tl.float16), mask=mask) +``` + +## Fused SiLU * Gate (SwiGLU) + +Common in LLMs (LLaMA MLP): gate and up projections are multiplied element-wise +after SiLU on the gate. If they're stored contiguously as `[..., 2*hidden]`: + +```python +@triton.jit +def swiglu_kernel(x_ptr, out_ptr, stride_in, stride_out, hidden_size, BLOCK_H: tl.constexpr): + row = tl.program_id(0) + offsets = tl.arange(0, BLOCK_H) + mask = offsets < hidden_size + + gate = tl.load(x_ptr + row * stride_in + offsets, mask=mask, other=0.0).to(tl.float32) + value = tl.load(x_ptr + row * stride_in + hidden_size + offsets, mask=mask, other=0.0).to(tl.float32) + + result = (gate * tl.sigmoid(gate)) * value + tl.store(out_ptr + row * stride_out + offsets, result.to(tl.float16), mask=mask) +``` + +## Group-Major PID Ordering (Matmul Optimization) + +Programs assigned to adjacent PIDs often end up on the same SM and share L2 +cache / SRAM. By default, a 2D grid assigns PIDs in row-major order — programs +in the same row share A tiles but need different B tiles. + +Rearranging into square groups improves data sharing: + +```python +# Convert 1D PID to 2D block coordinates with group-major ordering +pid = tl.program_id(0) +num_blocks_n = triton.cdiv(N, BLOCK_N) +num_blocks_m = triton.cdiv(M, BLOCK_M) + +group_id = pid // (GROUP_SIZE * num_blocks_n) +first_row = group_id * GROUP_SIZE +group_size_adj = min(num_blocks_m - first_row, GROUP_SIZE) + +pid_m = first_row + ((pid % (GROUP_SIZE * num_blocks_n)) % group_size_adj) +pid_n = (pid % (GROUP_SIZE * num_blocks_n)) // group_size_adj +``` + +Nearby PIDs form vertical strips (square groups) instead of long rows. Programs +in a group share both A and B tile data through the L2 cache. + +Typical improvement: 5-15% for large matrices. The hardware L2 cache already does +some of this, so gains vary. + +## Pointer Sliding (K-Loop Optimization) + +Instead of recomputing pointer offsets each iteration: + +```python +# Slower: recompute each iteration +for k in range(0, K, BLOCK_K): + rk = k + tl.arange(0, BLOCK_K) + a = tl.load(a_ptr + rm[:, None] * stride_am + rk[None, :] * stride_ak, ...) + +# Faster: slide pointers forward +a_ptrs = a_ptr + rm[:, None] * stride_am + tl.arange(0, BLOCK_K)[None, :] * stride_ak +b_ptrs = b_ptr + tl.arange(0, BLOCK_K)[:, None] * stride_bk + rn[None, :] * stride_bn + +for k in range(0, K, BLOCK_K): + a = tl.load(a_ptrs, mask=..., other=0.0) + b = tl.load(b_ptrs, mask=..., other=0.0) + acc += tl.dot(a, b) + a_ptrs += BLOCK_K * stride_ak + b_ptrs += BLOCK_K * stride_bk +``` + +Saves a few integer multiply-adds per iteration. Marginal but free. diff --git a/kernel-builder/skills/triton-kernels/scripts/benchmark_template.py b/kernel-builder/skills/triton-kernels/scripts/benchmark_template.py new file mode 100644 index 000000000..0b7f70cf7 --- /dev/null +++ b/kernel-builder/skills/triton-kernels/scripts/benchmark_template.py @@ -0,0 +1,114 @@ +""" +Benchmark template for Triton kernels. + +Usage: + python benchmark_template.py + +Generates a performance plot (PNG) and prints a data table comparing +your Triton kernel against the PyTorch baseline. + +To adapt for your kernel: +1. Replace `triton_kernel_wrapper(x)` with your kernel call +2. Replace `torch_reference(x)` with the equivalent PyTorch op +3. Adjust x_vals, args, ylabel, and the gbps/tflops calculation +""" + +import torch +import triton +import triton.language as tl + +DEVICE = torch.device(f'cuda:{torch.cuda.current_device()}') + + +# ============================================================ +# Your kernel here +# ============================================================ + +@triton.jit +def my_kernel(x_ptr, output_ptr, n_cols, stride_row, BLOCK_SIZE: tl.constexpr): + """Replace with your kernel implementation.""" + pid = tl.program_id(0) + row_start = pid * stride_row + offsets = tl.arange(0, BLOCK_SIZE) + mask = offsets < n_cols + + x = tl.load(x_ptr + row_start + offsets, mask=mask, other=float('-inf')).to(tl.float32) + x_max = tl.max(x, axis=0) + x = x - x_max + numerator = tl.exp(x) + denominator = tl.sum(numerator, axis=0) + result = numerator / denominator + + tl.store(output_ptr + row_start + offsets, result, mask=mask) + + +def triton_kernel_wrapper(x): + """Replace with your wrapper function.""" + assert x.is_contiguous() + n_rows, n_cols = x.shape + output = torch.empty_like(x) + BLOCK_SIZE = triton.next_power_of_2(n_cols) + num_warps = 4 if BLOCK_SIZE <= 1024 else (8 if BLOCK_SIZE <= 4096 else 16) + my_kernel[(n_rows,)](x, output, n_cols, x.stride(0), BLOCK_SIZE=BLOCK_SIZE, num_warps=num_warps) + return output + + +def torch_reference(x): + """Replace with the PyTorch equivalent.""" + return torch.softmax(x, dim=-1) + + +# ============================================================ +# Correctness check (always run before benchmarking) +# ============================================================ + +def test_correctness(): + torch.manual_seed(0) + # Test with irregular shape to verify masking + x = torch.randn(1823, 781, device=DEVICE, dtype=torch.float32) + y_triton = triton_kernel_wrapper(x) + y_ref = torch_reference(x) + torch.testing.assert_close(y_triton, y_ref, atol=1e-3, rtol=1e-3) + print("Correctness: PASSED") + + +# ============================================================ +# Benchmark +# ============================================================ + +@triton.testing.perf_report( + triton.testing.Benchmark( + x_names=['N'], + x_vals=[128 * i for i in range(2, 100)], + line_arg='provider', + line_vals=['triton', 'torch'], + line_names=['Triton', 'PyTorch'], + styles=[('blue', '-'), ('green', '-')], + ylabel='GB/s', + plot_name='kernel-performance', + args={'M': 4096}, + )) +def benchmark(M, N, provider): + x = torch.randn(M, N, device=DEVICE, dtype=torch.float32) + + stream = torch.cuda.Stream() + torch.cuda.set_stream(stream) + + if provider == 'torch': + ms = triton.testing.do_bench(lambda: torch_reference(x)) + elif provider == 'triton': + ms = triton.testing.do_bench(lambda: triton_kernel_wrapper(x)) + + # For memory-bound kernels: GB/s + # 2 = one read + one write + gbps = 2 * x.numel() * x.element_size() * 1e-9 / (ms * 1e-3) + return gbps + + # For compute-bound kernels (matmul), use TFLOPS instead: + # tflops = 2 * M * N * K * 1e-12 / (ms * 1e-3) + # return tflops + + +if __name__ == "__main__": + test_correctness() + benchmark.run(save_path='.', print_data=True) diff --git a/kernel-builder/skills/triton-kernels/scripts/correctness_template.py b/kernel-builder/skills/triton-kernels/scripts/correctness_template.py new file mode 100644 index 000000000..2393da6f7 --- /dev/null +++ b/kernel-builder/skills/triton-kernels/scripts/correctness_template.py @@ -0,0 +1,119 @@ +""" +Correctness test template for Triton kernels. + +Usage: + python correctness_template.py + +Tests your kernel against a PyTorch reference across multiple shapes, +dtypes, and edge cases. Always run this before benchmarking. + +To adapt: +1. Replace `triton_kernel_wrapper(x)` with your kernel +2. Replace `torch_reference(x)` with the PyTorch equivalent +3. Adjust test shapes and tolerances for your use case +""" + +import torch +import triton +import triton.language as tl + +DEVICE = torch.device(f'cuda:{torch.cuda.current_device()}') + + +# ============================================================ +# Your kernel here (same as in benchmark_template.py) +# ============================================================ + +def triton_kernel_wrapper(x): + """Replace with your kernel wrapper.""" + raise NotImplementedError("Replace with your kernel") + + +def torch_reference(x): + """Replace with PyTorch equivalent.""" + raise NotImplementedError("Replace with torch reference") + + +# ============================================================ +# Test suite +# ============================================================ + +def test_shape(shape, dtype=torch.float32, atol=1e-3, rtol=1e-3): + """Test a single shape.""" + torch.manual_seed(0) + x = torch.randn(shape, device=DEVICE, dtype=dtype) + y_triton = triton_kernel_wrapper(x) + y_ref = torch_reference(x) + torch.testing.assert_close(y_triton, y_ref, atol=atol, rtol=rtol) + + +def run_tests(): + print("Testing various shapes...") + + # Standard shapes + test_cases = [ + # (shape, description) + ((1, 128), "minimal 1-row"), + ((4, 4), "tiny square"), + ((32, 32), "small square"), + ((1024, 1024), "medium square"), + ((4096, 4096), "large square"), + # Irregular shapes (verify masking works) + ((1823, 781), "irregular"), + ((1, 1), "single element"), + ((1, 12345), "single long row"), + ((10000, 1), "many single-element rows"), + # Powers of 2 (no masking needed) + ((512, 512), "power of 2"), + ((2048, 2048), "large power of 2"), + # Non-power-of-2 that's close to a boundary + ((256, 1023), "just under power of 2"), + ((256, 1025), "just over power of 2"), + ] + + for shape, desc in test_cases: + try: + test_shape(shape) + print(f" PASSED: {desc} {shape}") + except AssertionError as e: + print(f" FAILED: {desc} {shape}") + print(f" {e}") + except Exception as e: + print(f" ERROR: {desc} {shape}") + print(f" {type(e).__name__}: {e}") + + # Dtype tests + print("\nTesting dtypes...") + dtype_configs = [ + (torch.float32, 1e-3, 1e-3), + (torch.float16, 1e-2, 1e-2), # fp16 has lower precision + (torch.bfloat16, 1e-2, 1e-2), + ] + + for dtype, atol, rtol in dtype_configs: + try: + test_shape((1024, 1024), dtype=dtype, atol=atol, rtol=rtol) + print(f" PASSED: {dtype}") + except AssertionError as e: + print(f" FAILED: {dtype}") + print(f" {e}") + except Exception as e: + print(f" ERROR: {dtype}: {type(e).__name__}: {e}") + + # Determinism test + print("\nTesting determinism...") + torch.manual_seed(42) + x = torch.randn(1024, 1024, device=DEVICE) + y1 = triton_kernel_wrapper(x) + y2 = triton_kernel_wrapper(x) + if torch.equal(y1, y2): + print(" PASSED: deterministic") + else: + max_diff = (y1 - y2).abs().max().item() + print(f" WARNING: non-deterministic (max diff: {max_diff})") + + print("\nDone.") + + +if __name__ == "__main__": + run_tests() diff --git a/kernel-builder/src/skills.rs b/kernel-builder/src/skills.rs index f9eaa39f2..daabd05af 100644 --- a/kernel-builder/src/skills.rs +++ b/kernel-builder/src/skills.rs @@ -16,6 +16,7 @@ pub enum SkillId { CudaKernels, CpuKernels, RocmKernels, + TritonKernels, XpuKernels, } @@ -25,6 +26,7 @@ impl SkillId { SkillId::CudaKernels => "cuda-kernels", SkillId::CpuKernels => "cpu-kernels", SkillId::RocmKernels => "rocm-kernels", + SkillId::TritonKernels => "triton-kernels", SkillId::XpuKernels => "xpu-kernels", } }