triton developer on retainer: tl.store() missing out-of-bounds mask — OOB writes corrupt adjacent gradient tensors when dims not multiple of BLOCK_SIZE — NaN loss on production data — $85,000 — 3 months
triton 2.2.0; torch 2.2.0; Python 3.11; CUDA 12.2; A100 80GB; custom matrix multiplication kernel; tl.load() correctly masked with other=0.0 for K-dimension boundary blocks; tl.store() missing mask for output boundary blocks; N=1500, BLOCK_N=128: last N-block stores 20 rows past tensor end into adjacent gradient tensor memory; NaN gradients; loss = nan after step 1; benchmarks pass (all power-of-2 dims: 4096×4096); 100% training failure on production hidden dim 1500; fix: tl.store(ptr, c, mask=mask_c) • Southfield Triton Kernel Ltd. (2-person; 3 months; 2.0h)
Southfield Triton Kernel Ltd. is a 2-person ML compute startup that rewrote performance-critical attention and feed-forward operations as custom Triton kernels. Their primary target was a BERT-large training loop where replacing PyTorch’s default torch.matmul with a tile-based Triton kernel was expected to deliver 10× throughput improvement through reduced global memory traffic and kernel launch overhead. The team implemented the kernel following the official Triton matrix multiplication tutorial, achieving 310 TFLOPS on their A100 80GB benchmark suite — matching cuBLAS’s 312 TFLOPS. The benchmark suite exclusively used power-of-2 matrix dimensions: M=N=K=4096. Every run passed the correctness check: torch.allclose(out_triton, A @ B, atol=1e-3).
When the kernel was deployed to the production training loop, every training run terminated at step 1 with loss = nan. Production BERT-large training used batch size 16, sequence length 512, and hidden dimension 1500 — giving a feed-forward projection of shape [8192×1500]. The number 1500 is not a multiple of BLOCK_N=128 (1500 ÷ 128 = 11.71875). For the last column tile of the output matrix C[8192×1500], the tile covers columns [1408, 1409, ..., 1535] — but only columns [1408, ..., 1499] are within the allocated tensor. Without a mask, tl.store() writes the full 8192×128 tile including 36 columns (8192×36×2 bytes = 589,824 bytes) past the end of C’s allocation. Those bytes belonged to the LayerNorm weight gradient tensor, which PyTorch’s CUDA caching allocator had placed immediately adjacent in the same pool block.
# matmul_kernel.py — Southfield Triton Kernel Ltd.
# triton 2.2.0; torch 2.2.0; Python 3.11; CUDA 12.2; A100 80GB
import triton
import triton.language as tl
import torch
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128}, num_warps=8, num_stages=3),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 64}, num_warps=4, num_stages=4),
# ... 8 more configs
],
key=["M", "N", "K"],
)
@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)
offs_am = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_bn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
offs_k = tl.arange(0, BLOCK_K)
# Initialize accumulator
c = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
for k in range(0, tl.cdiv(K, BLOCK_K)):
offs_k_this = k * BLOCK_K + offs_k
# Load A tile — CORRECTLY masked for K dimension
mask_a = (offs_am[:, None] < M) & (offs_k_this[None, :] < K)
a = tl.load(
a_ptr + offs_am[:, None] * stride_am + offs_k_this[None, :] * stride_ak,
mask=mask_a,
other=0.0, # out-of-bounds → zero (doesn't affect dot product ✓)
)
# Load B tile — CORRECTLY masked for K dimension
mask_b = (offs_k_this[:, None] < K) & (offs_bn[None, :] < N)
b = tl.load(
b_ptr + offs_k_this[:, None] * stride_bk + offs_bn[None, :] * stride_bn,
mask=mask_b,
other=0.0,
)
c += tl.dot(a, b)
# Compute output offsets
offs_cm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_cn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
# Bug: NO MASK on tl.store()
# When N=1500, BLOCK_N=128:
# pid_n_max = ceil(1500/128) - 1 = 11
# offs_cn for pid_n=11: [1408, 1409, ..., 1535]
# Valid output columns: [1408, ..., 1499] (92 valid)
# OOB columns: [1500, ..., 1535] (36 out-of-bounds)
#
# For M=8192, N=1500:
# OOB write volume: 8192 rows × 36 cols × 2 bytes (fp16) = 589,824 bytes
#
# PyTorch CUDA caching allocator pool layout (typical):
# [... | C tensor [8192×1500×2 bytes] | LayerNorm.weight.grad [1500×2 bytes] | ...]
# ^ ^--- tl.store() writes start HERE
#
# LayerNorm.weight.grad receives 589,824 bytes of junk from the last matmul tile.
# loss.backward() uses these corrupted gradients.
# Corrupted gradient values → optimizer step → parameters contain NaN.
# Next forward pass: NaN activations → NaN loss.
# torch.autograd.set_detect_anomaly(True) catches it at LayerNorm backward.
tl.store(
c_ptr + offs_cm[:, None] * stride_cm + offs_cn[None, :] * stride_cn,
c.to(tl.float16),
# mask=??? ← MISSING
)
# Benchmarks (all pass — power-of-2 dims have no boundary blocks):
# M=N=K=128: torch.allclose(..., atol=1e-3) → True, 42 TFLOPS
# M=N=K=1024: torch.allclose(..., atol=1e-3) → True, 198 TFLOPS
# M=N=K=4096: torch.allclose(..., atol=1e-3) → True, 310 TFLOPS
#
# 4096 % 128 == 0 → no boundary blocks → tl.store() never writes OOB → test passes
#
# Production training fails at step 1:
# M=8192, N=1500, K=1500 → 1500 % 128 == 108 → 20 OOB rows per column block
# (1500 % 128 = 108, so last block needs 128 - 108 = 20 dummy rows masked out)
During the retainer triage, torch.autograd.set_detect_anomaly(True) immediately identified the LayerNorm backward as the source of the first NaN. Printing the LayerNorm weight gradient before backward showed NaN values in the last 20 rows of the gradient tensor — the exact positions corresponding to the out-of-bounds write extent. With BLOCK_N=128 and N=1500, the last N-block covers positions [1408–1535], but only [1408–1499] are valid: 1500 − 1408 = 92 valid, 128 − 92 = 36 columns written OOB. The LayerNorm weight gradient is a 1D tensor of length 1500 elements × 2 bytes = 3,000 bytes, entirely within the 589,824-byte OOB write window. The fix is a one-line addition to tl.store(). The key diagnostic was that the OOB write only occurred when N was not a multiple of BLOCK_N — a condition never tested by the power-of-2 benchmark suite.
Fix: add mask=mask_c to tl.store()
# Fixed matmul_kernel.py — Southfield Triton Kernel Ltd.
# (inside matmul_kernel, after accumulation loop)
offs_cm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_cn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
# Fix: mask output stores for boundary tiles
mask_c = (offs_cm[:, None] < M) & (offs_cn[None, :] < N)
tl.store(
c_ptr + offs_cm[:, None] * stride_cm + offs_cn[None, :] * stride_cn,
c.to(tl.float16),
mask=mask_c, # ← prevents OOB writes for boundary tiles
)
# With mask_c:
# pid_n=11, offs_cn=[1408,...,1535], N=1500:
# mask_c columns: [True×92, False×36]
# Only columns [1408,...,1499] are stored — 1500,...,1535 are skipped.
# No writes beyond C's allocation.
# CI test: always test non-power-of-2 dimensions
def test_matmul_boundary_conditions():
for M in [1, 7, 100, 108, 128, 129, 300, 512, 1500, 4000, 4096]:
for N in [1, 7, 100, 108, 128, 129, 300, 512, 1500, 4000, 4096]:
for K in [128, 256, 512, 1500]:
A = torch.randn(M, K, dtype=torch.float16, device="cuda")
B = torch.randn(K, N, dtype=torch.float16, device="cuda")
ref = (A.float() @ B.float()).half()
out = triton_matmul(A, B)
assert torch.allclose(out, ref, atol=1e-2), (
f"FAIL M={M} N={N} K={K}: max_diff={( out - ref).abs().max():.4f}"
)
print("All boundary condition tests passed.")
# Results after fix — Southfield Triton Kernel Ltd.:
# Correctness test (M=8192, N=1500, K=1500): torch.allclose → True ✓
# Production training step 1 loss: 0.721 (normal)
# Training convergence: 15,000 steps (expected)
# Throughput at M=N=K=4096: 310 TFLOPS (unchanged)
# OOB write volume: 0 bytes (was 589,824)
#
# 2 engineers × 3 months × $14,167/month = $85,000
Related retainer posts
- flash-attn developer on retainer — flash-attn 2.5.6;
padding_side=“right”+flash_attention_2; shorter sequences in batch attend to padding KV entries; quality 2.8/5 vs 4.4/5; fix:padding_side=“left”; 1.5h - vLLM developer on retainer — vllm 0.5.3; DCGM Exporter allocates 1.4 GB GPU memory after vLLM KV cache init; A100 40 GB OOM on 8 concurrent long-context requests; 9 weeks intermittent CUDA OOM; 1.5h
- bitsandbytes developer on retainer — bitsandbytes 0.42.0; NF4 model loaded with
device_map='cpu';model.to('cuda')re-quantizes already-quantized weights; doubly-quantized garbage; inference nonsense; 1.5h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →