1"""
2Triton matmul kernel tuned for NVIDIA Blackwell (B100/B200, sm_100/sm_120).
3
4Computes C = A @ B (+ optional bias) with fp32 accumulation. Supports
5fp16/bf16 as well as fp8 (e4m3/e5m2) operands, since Blackwell's 5th-gen
6tensor cores roughly double fp8 throughput over Hopper and are the main
7reason to reach for Blackwell-specific tuning.
8
9Differences from the Hopper kernel (matmul_hopper.py):
10 - Uses TMA tensor descriptors (`tl.make_tensor_descriptor`) for the A/B/C
11 loads and stores when the installed Triton exposes the API, instead of
12 manual pointer + stride arithmetic. TMA offloads address generation to
13 hardware and is the preferred load path on both Hopper and Blackwell,
14 but Blackwell's larger L2/SMEM makes the bigger tiles below pay off.
15 Falls back to the pointer-based path automatically on older Triton.
16 - Larger default tiles (up to 256x256) and deeper pipelines, sized for
17 Blackwell's bigger shared memory per SM.
18 - Thread-block clusters up to size 4 (`num_ctas`), vs. 2 on Hopper.
19 - fp8 (e4m3/e5m2) input support with fp32 accumulation.
20
21Usage:
22 python matmul_blackwell.py # correctness check + benchmark
23"""
24
25import torch
26import triton
27import triton.language as tl
28
29_HAS_TMA = hasattr(tl, "make_tensor_descriptor")
30
31
32
33
34
35
36TMA_BLOCK_M = 128
37TMA_BLOCK_N = 256
38TMA_BLOCK_K = 64
39
40
41def _blackwell_tma_autotune_configs():
42 configs = []
43 for stages, warps, ctas in [(4, 8, 1), (3, 8, 1), (4, 8, 2), (3, 8, 4)]:
44 kwargs = dict(
45 BLOCK_SIZE_M=TMA_BLOCK_M, BLOCK_SIZE_N=TMA_BLOCK_N, BLOCK_SIZE_K=TMA_BLOCK_K,
46 GROUP_SIZE_M=8,
47 )
48 try:
49 cfg = triton.Config(kwargs, num_ctas=ctas, num_stages=stages, num_warps=warps)
50 except TypeError:
51 if ctas != 1:
52 continue
53 cfg = triton.Config(kwargs, num_stages=stages, num_warps=warps)
54 configs.append(cfg)
55 return configs
56
57
58def _blackwell_autotune_configs():
59 configs = []
60
61 tile_opts = [
62 (128, 256, 64, 4, 8, 1),
63 (256, 128, 64, 4, 8, 1),
64 (256, 256, 64, 3, 8, 1),
65 (128, 128, 128, 4, 4, 1),
66 (256, 128, 128, 4, 8, 1),
67 (128, 256, 128, 4, 8, 1),
68 (64, 256, 64, 4, 4, 1),
69 (256, 64, 64, 4, 4, 1),
70 (128, 128, 64, 4, 4, 1),
71 (128, 64, 64, 4, 4, 1),
72 (64, 32, 64, 5, 2, 1),
73
74
75
76 (128, 256, 64, 4, 8, 2),
77 (256, 128, 64, 4, 8, 2),
78 (256, 256, 64, 3, 8, 4),
79 ]
80 for BM, BN, BK, stages, warps, ctas in tile_opts:
81 kwargs = dict(BLOCK_SIZE_M=BM, BLOCK_SIZE_N=BN, BLOCK_SIZE_K=BK, GROUP_SIZE_M=8)
82 cfg_kwargs = dict(num_stages=stages, num_warps=warps)
83 try:
84 cfg = triton.Config(kwargs, num_ctas=ctas, **cfg_kwargs)
85 except TypeError:
86 if ctas != 1:
87 continue
88 cfg = triton.Config(kwargs, **cfg_kwargs)
89 configs.append(cfg)
90 return configs
91
92
93@triton.autotune(
94 configs=_blackwell_tma_autotune_configs(),
95 key=["M", "N", "K"],
96)
97@triton.jit
98def matmul_kernel_tma(
99 a_desc, b_desc, c_desc,
100 bias_ptr,
101 M, N, K,
102 stride_cn0,
103 BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
104 GROUP_SIZE_M: tl.constexpr,
105 HAS_BIAS: tl.constexpr,
106 ACTIVATION: tl.constexpr,
107):
108 """TMA-descriptor GEMM path (used when Triton exposes make_tensor_descriptor)."""
109 pid = tl.program_id(axis=0)
110 num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
111 num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
112
113 num_pid_in_group = GROUP_SIZE_M * num_pid_n
114 group_id = pid // num_pid_in_group
115 first_pid_m = group_id * GROUP_SIZE_M
116 group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
117 pid_m = first_pid_m + (pid % group_size_m)
118 pid_n = (pid % num_pid_in_group) // group_size_m
119
120 offs_am = pid_m * BLOCK_SIZE_M
121 offs_bn = pid_n * BLOCK_SIZE_N
122
123 acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
124
125 for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
126 offs_k = k * BLOCK_SIZE_K
127
128 a = a_desc.load([offs_am, offs_k])
129 b = b_desc.load([offs_k, offs_bn])
130 acc = tl.dot(a, b, acc)
131
132 if HAS_BIAS:
133 offs_n_bias = offs_bn + tl.arange(0, BLOCK_SIZE_N)
134 bias = tl.load(bias_ptr + offs_n_bias, mask=offs_n_bias < N, other=0.0)
135 acc += bias[None, :].to(tl.float32)
136
137 if ACTIVATION == "relu":
138 acc = tl.maximum(acc, 0.0)
139
140 c_desc.store([offs_am, offs_bn], acc.to(c_desc.dtype))
141
142
143@triton.autotune(
144 configs=_blackwell_autotune_configs(),
145 key=["M", "N", "K"],
146)
147@triton.jit
148def matmul_kernel_ptr(
149 a_ptr, b_ptr, c_ptr, bias_ptr,
150 M, N, K,
151 stride_am, stride_ak,
152 stride_bk, stride_bn,
153 stride_cm, stride_cn,
154 BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
155 GROUP_SIZE_M: tl.constexpr,
156 HAS_BIAS: tl.constexpr,
157 ACTIVATION: tl.constexpr,
158):
159 """Pointer/stride fallback GEMM path for Triton builds without TMA descriptors."""
160 pid = tl.program_id(axis=0)
161 num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
162 num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
163
164 num_pid_in_group = GROUP_SIZE_M * num_pid_n
165 group_id = pid // num_pid_in_group
166 first_pid_m = group_id * GROUP_SIZE_M
167 group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
168 pid_m = first_pid_m + (pid % group_size_m)
169 pid_n = (pid % num_pid_in_group) // group_size_m
170
171 offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
172 offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
173 offs_k = tl.arange(0, BLOCK_SIZE_K)
174
175 a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
176 b_ptrs = b_ptr + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
177
178 acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
179
180 for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
181 k_remaining = K - k * BLOCK_SIZE_K
182 a = tl.load(a_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
183 b = tl.load(b_ptrs, mask=offs_k[:, None] < k_remaining, other=0.0)
184 acc = tl.dot(a, b, acc)
185 a_ptrs += BLOCK_SIZE_K * stride_ak
186 b_ptrs += BLOCK_SIZE_K * stride_bk
187
188 if HAS_BIAS:
189 offs_n_bias = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
190 bias = tl.load(bias_ptr + offs_n_bias, mask=offs_n_bias < N, other=0.0)
191 acc += bias[None, :].to(tl.float32)
192
193 if ACTIVATION == "relu":
194 acc = tl.maximum(acc, 0.0)
195
196 offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
197 offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
198 c_ptrs = c_ptr + stride_cm * offs_cm[:, None] + stride_cn * offs_cn[None, :]
199 c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N)
200 tl.store(c_ptrs, acc.to(c_ptr.dtype.element_ty), mask=c_mask)
201
202
203def matmul(a: torch.Tensor, b: torch.Tensor, bias: torch.Tensor = None, activation: str = "") -> torch.Tensor:
204 assert a.ndim == 2 and b.ndim == 2 and a.shape[1] == b.shape[0], "incompatible shapes"
205 assert a.dtype == b.dtype, "A and B must share a dtype"
206 assert a.is_cuda and b.is_cuda, "inputs must be on GPU"
207
208 M, K = a.shape
209 _, N = b.shape
210 c = torch.empty((M, N), device=a.device, dtype=a.dtype)
211 has_bias = bias is not None
212 if has_bias:
213 assert bias.shape == (N,)
214
215 grid = lambda META: (
216 triton.cdiv(M, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]),
217 )
218
219 if _HAS_TMA:
−
−
−
−
−
−
− a_desc = tl.make_tensor_descriptor(a, [M, K], [a.stride(0), a.stride(1)], [64, 64])
− b_desc = tl.make_tensor_descriptor(b, [K, N], [b.stride(0), b.stride(1)], [64, 64])
− c_desc = tl.make_tensor_descriptor(c, [M, N], [c.stride(0), c.stride(1)], [64, 64])
220
221
222
223
224 a_desc = tl.make_tensor_descriptor(
225 a, [M, K], [a.stride(0), a.stride(1)], [TMA_BLOCK_M, TMA_BLOCK_K]
226 )
227 b_desc = tl.make_tensor_descriptor(
228 b, [K, N], [b.stride(0), b.stride(1)], [TMA_BLOCK_K, TMA_BLOCK_N]
229 )
230 c_desc = tl.make_tensor_descriptor(
231 c, [M, N], [c.stride(0), c.stride(1)], [TMA_BLOCK_M, TMA_BLOCK_N]
232 )
233 matmul_kernel_tma[grid](
234 a_desc, b_desc, c_desc, bias if has_bias else a,
235 M, N, K, 0,
236 HAS_BIAS=has_bias,
237 ACTIVATION=activation,
238 )
239 else:
240 matmul_kernel_ptr[grid](
241 a, b, c, bias if has_bias else a,
242 M, N, K,
243 a.stride(0), a.stride(1),
244 b.stride(0), b.stride(1),
245 c.stride(0), c.stride(1),
246 HAS_BIAS=has_bias,
247 ACTIVATION=activation,
248 )
249 return c
250
251
252def _correctness_check():
253 torch.manual_seed(0)
254 dtypes = [torch.float16, torch.bfloat16]
255 if hasattr(torch, "float8_e4m3fn"):
256 dtypes.append(torch.float8_e4m3fn)
257
258 for dtype in dtypes:
259 for M, N, K in [(128, 128, 128), (513, 761, 391), (4096, 4096, 4096)]:
260 if dtype in (torch.float8_e4m3fn,) and (M % 16 or N % 16 or K % 16):
261 continue
262 scale = 0.1
263 a = (torch.randn((M, K), device="cuda") * scale).to(dtype)
264 b = (torch.randn((K, N), device="cuda") * scale).to(dtype)
265 bias = (torch.randn((N,), device="cuda") * scale).to(dtype)
266
267 out = matmul(a, b, bias=bias, activation="relu")
268 ref = torch.relu((a.float() @ b.float()) + bias.float()).to(dtype)
269
270 atol, rtol = (2e-1, 2e-1) if dtype == torch.float8_e4m3fn else (1e-2, 1e-2)
271 torch.testing.assert_close(out.float(), ref.float(), atol=atol, rtol=rtol)
272 print(f"OK dtype={dtype} M={M} N={N} K={K}")
273
274
275def _benchmark():
276 import triton.testing as tt
277
278 sizes = [1024, 2048, 4096, 8192]
279 for size in sizes:
280 a = torch.randn((size, size), device="cuda", dtype=torch.bfloat16)
281 b = torch.randn((size, size), device="cuda", dtype=torch.bfloat16)
282
283 ms_triton = tt.do_bench(lambda: matmul(a, b))
284 ms_torch = tt.do_bench(lambda: torch.matmul(a, b))
285
286 flops = 2 * size ** 3
287 tflops_triton = flops * 1e-12 / (ms_triton * 1e-3)
288 tflops_torch = flops * 1e-12 / (ms_torch * 1e-3)
289
290 print(
291 f"size={size:5d} triton={ms_triton:7.3f}ms {tflops_triton:7.1f} TFLOP/s "
292 f"torch={ms_torch:7.3f}ms {tflops_torch:7.1f} TFLOP/s"
293 )
294
295
296if __name__ == "__main__":
297 if not torch.cuda.is_available():
298 raise SystemExit("CUDA GPU required (Blackwell, sm_100/sm_120) to run this kernel.")
299 cc = torch.cuda.get_device_capability()
300 if cc[0] < 10:
301 print(f"Warning: device compute capability {cc} is not Blackwell (sm_100+); "
302 f"kernel will still run but tile configs are tuned for B100/B200.")
303
304 print(f"TMA descriptor path: {'enabled' if _HAS_TMA else 'disabled (pointer fallback)'}")
305 _correctness_check()
306 _benchmark()
307
Discussion
No comments yet. Start the discussion. Recorded by @patrick-toulme.