Repository navigation
Expand file tree
/
Copy pathtest_f4gemm.py
More file actions
778 lines (721 loc) · 28.9 KB
/
Copy pathtest_f4gemm.py
File metadata and controls
778 lines (721 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# SPDX-License-Identifier: MIT
# Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved.
#
# ============================================================================
# gfx1250 F4GEMM ASM Support Matrix
# ----------------------------------------------------------------------------
# OUTTYPE | A_PRESHUFFLE | B_PRESHUFFLE | INTYPE | M | N | K
# ---------+--------------+--------------+--------+--------+--------+--------
# BF16 | 0 | 1 | MXFP4 | %1==0 | %16==0 | %32==0
# BF16 | 0 | 1 | NVFP4 | %1==0 | %16==0 | %32==0
# BF16 | 1 | 1 | MXFP4 | %16==0 | %16==0 | %32==0
# BF16 | 1 | 1 | NVFP4 | %16==0 | %16==0 | %32==0
# FP8 | 0 | 1 | MXFP4 | %1==0 | %16==0 | %32==0
# FP8 | 0 | 1 | NVFP4 | %1==0 | %16==0 | %32==0
# FP8 | 1 | 1 | MXFP4 | %16==0 | %16==0 | %32==0
# FP8 | 1 | 1 | NVFP4 | %16==0 | %16==0 | %32==0
# ----------------------------------------------------------------------------
# Notes:
# - B_PRESHUFFLE is always 1 (B is always pre-shuffled).
# - A_PRESHUFFLE=1 tightens the M constraint from %1==0 to %16==0.
# - K is always a multiple of 32.
# ============================================================================
import argparse
import itertools
import sys
import pandas as pd
import torch
import aiter
from aiter import dtypes
from aiter.benchmark_data_init import (
fill_fp4,
fill_scale_e4m3,
fill_scale_e8m0,
make_generator,
)
from aiter.jit.utils.chip_info import get_gfx_runtime as get_gfx
from aiter.ops.gemm_op_a4w4 import MXFP8_OUT_SCALE_BLOCK, unpack_mxfp8_out_scale
from aiter.ops.shuffle import shuffle_scale_f4, shuffle_weight_f4
from aiter.test_common import (
benchmark,
checkAllclose,
run_perftest,
)
from aiter.utility import fp4_utils
torch.set_default_device("cuda")
torch.set_printoptions(sci_mode=False)
pd.set_option("display.max_columns", 30)
pd.set_option("display.width", 1000)
SUPPORTED_GFX = ["gfx1250"]
_OUT_DTYPE = {"bf16": dtypes.bf16, "fp8": dtypes.fp8}
# gfx1250 F4GEMM .co is a persistent shader: it always launches PERSISTENT_TG
# threadgroups regardless of problem size (must match the .co's WG_MAX).
PERSISTENT_TG = 256
def _report_active_tg(M, N, tile_m, tile_n, label):
"""Warn when the persistent shader's TG slots aren't fully packed.
The .co always launches PERSISTENT_TG (256) threadgroups. The real work is
ceil(M/tile_m) * ceil(N/tile_n) tiles; when that isn't a multiple of 256 the
final wave leaves the leftover TG slots idle (wasted CUs) -> "poor perf".
(Moved here from the cpp dispatch so the report lives with the test.)
"""
tg_m = (M + tile_m - 1) // tile_m
tg_n = (N + tile_n - 1) // tile_n
active_tg = tg_m * tg_n
wave_active = (
PERSISTENT_TG if active_tg % PERSISTENT_TG == 0 else active_tg % PERSISTENT_TG
)
info = (
f"{label}: active {wave_active}/{PERSISTENT_TG} TG "
f"({tg_m} M-tiles x {tg_n} N-tiles, tile_m={tile_m}, tile_n={tile_n})"
)
if active_tg % PERSISTENT_TG == 0:
aiter.logger.info("dispatch to %s", info)
else:
tag = "\033[31mpoor perf\033[0m" if sys.stderr.isatty() else "poor perf"
aiter.logger.warning("dispatch to %s - %s!", info, tag)
PERF_SHAPES = [(16384, 16384, 16384)]
FUNC_SHAPES = [
# pure_compute
(256, 2048, 8192),
(2048, 8192, 8192),
(16384, 16384, 16384),
# (32768, 106496, 16384),
# (32768, 16384, 53248),
# (32768, 18432, 16384),
# (32768, 16384, 16384),
(128, 106496, 16384),
(128, 16384, 53248),
(128, 18432, 16384),
(128, 16384, 16384),
(64, 106496, 16384),
(64, 16384, 53248),
(64, 18432, 16384),
(64, 16384, 16384),
(32, 106496, 16384),
(32, 16384, 53248),
(32, 18432, 16384),
(32, 16384, 16384),
# qkv_proj
(1, 1280, 8192),
(64, 1280, 8192),
(127, 1280, 8192),
(129, 1280, 8192),
(65, 1280, 8192),
(32, 1280, 8192),
(128, 1280, 8192),
(192, 1280, 8192),
(256, 1280, 8192),
(320, 1280, 8192),
(512, 1280, 8192),
(1024, 1280, 8192),
(2048, 1280, 8192),
(4096, 1280, 8192),
(8192, 1280, 8192),
# attn_out
(1, 8192, 1024),
(32, 8192, 1024),
(64, 8192, 1024),
(128, 8192, 1024),
(192, 8192, 1024),
(256, 8192, 1024),
(320, 8192, 1024),
(512, 8192, 1024),
(1024, 8192, 1024),
(2048, 8192, 1024),
(4096, 8192, 1024),
(8192, 8192, 1024),
(16384, 8192, 1024),
# tune
(1552, 8192, 8192),
(1664, 8192, 8192),
(1792, 8192, 8192),
(1920, 8192, 8192),
(3072, 8192, 8192),
(1552, 10240, 8192),
(1664, 10240, 8192),
(1792, 10240, 8192),
(1920, 10240, 8192),
(3072, 10240, 8192),
(1552, 57344, 8192),
(1664, 57344, 8192),
(1792, 57344, 8192),
(1920, 57344, 8192),
(3072, 57344, 8192),
(1552, 8192, 28672),
(1664, 8192, 28672),
(1792, 8192, 28672),
(1920, 8192, 28672),
(3072, 8192, 28672),
(128, 1280, 8224),
# partial_tile
(128, 384, 8192),
(128, 272, 8192),
(65, 384, 8192),
]
MXFP4_SCALE_BLOCK = 32
NVFP4_SCALE_BLOCK = 16
# MXFP8_OUT_SCALE_BLOCK (=128) is imported from gemm_op_a4w4.
# mxfp8 output E8M0 scale, mirrors the fp8out kernel: amax/256, then
# exp[30:23] + guard[22] (single guard-bit round, no RNE). Compared with a
# +-1 e8m0-step tolerance (see the scale checkAllclose below).
def _e8m0_out_scale(amax):
u = (amax / 256.0).view(torch.int32)
return (((u >> 23) & 0xFF) + ((u >> 22) & 1)).to(torch.uint8)
def _quant_mxfp8_blockN(x_f32, block=MXFP8_OUT_SCALE_BLOCK):
"""Golden mxfp8 output quant: per-128-col block amax -> E8M0 scale (kernel-
exact) + e4m3 data. Returns (fp8 [M,N], e8m0 row-major [M, N/block])."""
M, N = x_f32.shape
assert N % block == 0, f"mxfp8 golden requires N % {block} == 0"
xb = x_f32.reshape(M, N // block, block)
amax = xb.abs().amax(dim=-1).clamp(min=torch.finfo(torch.float32).tiny)
scale_e8m0 = _e8m0_out_scale(amax)
scale_f32 = fp4_utils.e8m0_to_f32(scale_e8m0).unsqueeze(-1)
q_fp8 = (xb / scale_f32).reshape(M, N).to(dtypes.fp8)
return q_fp8, scale_e8m0
def _dequant_mxfp8_blockN(q_fp8, scale_e8m0, block=MXFP8_OUT_SCALE_BLOCK):
"""Inverse of :func:`_quant_mxfp8_blockN`; ``scale_e8m0`` must be row-major."""
M, N = q_fp8.shape
scale_f32 = fp4_utils.e8m0_to_f32(scale_e8m0).unsqueeze(-1)
return (q_fp8.float().reshape(M, N // block, block) * scale_f32).reshape(M, N)
# checkAllclose returns 0 when all-close, else the mismatch fraction. Its own
# verdict thresholds: pass (0) / warning (<= tol_err_ratio) / failed (above).
_TOL_ERR_RATIO = 0.05 # matches checkAllclose default tol_err_ratio
def _verdict(err):
if err == 0:
return "pass"
return "warning" if err <= _TOL_ERR_RATIO else "failed"
def _support_reason(outtype, apre, M, N, K):
"""Support matrix gate. Returns None if the (outtype,apre,M,N,K) combo is
supported, else a short reason string (row marked "not support"). Mirrors
the dispatch heuristic in asm_f4gemm.cu so shapes are skipped before the
shuffle/prep step rather than crashing on an assert."""
if outtype not in _OUT_DTYPE:
return f"outtype {outtype}" # no kernel for this output format yet
if K % 32 != 0:
return "K%32" # B 16x16 preshuffle
if N % 16 != 0:
return "N%16" # B 16x16 preshuffle
if apre and M % 16 != 0:
return "apre M%16" # A 16x16 preshuffle
if outtype == "fp8" and N % MXFP8_OUT_SCALE_BLOCK != 0:
return "fp8 N%128" # per-128 output-scale golden limitation
return None
def _e4m3_to_f32(s: torch.Tensor) -> torch.Tensor:
return s.view(torch.float8_e4m3fn).to(torch.float32)
def run_torch_mxfp4(xq, wq, xs, ws):
# Reference only: fp32 math. Returns fp32; the caller casts to bf16 or
# quantizes per outtype. Not timed, not in the table.
x_f32 = fp4_utils.mxfp4_to_f32(xq)
w_f32 = fp4_utils.mxfp4_to_f32(wq)
xs = fp4_utils.e8m0_to_f32(xs).repeat_interleave(MXFP4_SCALE_BLOCK, dim=1)
ws = fp4_utils.e8m0_to_f32(ws).repeat_interleave(MXFP4_SCALE_BLOCK, dim=1)
return (x_f32 * xs) @ (w_f32 * ws).T
def run_torch_nvfp4(xq, wq, xs, ws, gA, gB):
# Reference only: fp32 math. Returns fp32 (see run_torch_mxfp4).
x_f32 = fp4_utils.mxfp4_to_f32(xq)
w_f32 = fp4_utils.mxfp4_to_f32(wq)
xs = _e4m3_to_f32(xs).repeat_interleave(NVFP4_SCALE_BLOCK, dim=1)
ws = _e4m3_to_f32(ws).repeat_interleave(NVFP4_SCALE_BLOCK, dim=1)
return float(gA) * float(gB) * (x_f32 * xs) @ (w_f32 * ws).T
def _prep_mxfp4(M, N, K, apre, data_init, scale_init, gen):
# DATA (fp4 e2m1, packed 2/byte). data & scale are sampled *independently*.
# constant is built inside fill_fp4 via constant=; f4gemm.cpp data_init=0
# keeps A=0x22, B=0x33 (fixed representable e2m1).
xq = fill_fp4((M, K), data_init, gen, constant=0x22)
wq = fill_fp4((N, K), data_init, gen, constant=0x33)
# SCALE (e8m0 per-32). auto -> pow2_binomial for E8M0; constant default is
# the neutral e8m0 byte 0x7F (exp 0 -> 2^0 = 1.0).
xs = fill_scale_e8m0((M, K // MXFP4_SCALE_BLOCK), scale_init, gen)
ws = fill_scale_e8m0((N, K // MXFP4_SCALE_BLOCK), scale_init, gen)
ref = run_torch_mxfp4(xq, wq, xs, ws)
inp = {
"A": shuffle_weight_f4(xq) if apre else xq,
"B": shuffle_weight_f4(wq),
"sA": shuffle_scale_f4(xs, 7),
"sB": shuffle_scale_f4(ws, 7),
"gA": None,
"gB": None,
}
return inp, ref
def _prep_nvfp4(M, N, K, apre, data_init, scale_init, gen):
# DATA (fp4 e2m1). data & scale sampled independently (test_common).
# constant built inside fill_fp4 via constant=; f4gemm.cpp data_init=0 keeps
# A=0x22, B=0x33 (fixed representable e2m1).
xq = fill_fp4((M, K), data_init, gen, constant=0x22)
wq = fill_fp4((N, K), data_init, gen, constant=0x33)
# SCALE (e4m3 per-16). auto -> gaussian(0.34375,0.08) for E4M3; constant
# default is the neutral e4m3 byte 0x38 (exp 7 = bias -> 1.0).
xs = fill_scale_e4m3((M, K // NVFP4_SCALE_BLOCK), scale_init, gen)
ws = fill_scale_e4m3((N, K // NVFP4_SCALE_BLOCK), scale_init, gen)
# Per-tensor global scale is NOT part of the init helpers: keep neutral.
gA = gB = 1.0
ref = run_torch_nvfp4(xq, wq, xs, ws, gA, gB)
inp = {
"A": shuffle_weight_f4(xq) if apre else xq,
"B": shuffle_weight_f4(wq),
"sA": shuffle_scale_f4(xs, 8),
"sB": shuffle_scale_f4(ws, 8),
"gA": gA, # NVFP4 per-tensor global scales (floats)
"gB": gB,
}
return inp, ref
@benchmark() # intype, M, N, K, apre, outtype, data_init, ... -> table columns
def test_gemm(
intype,
M,
N,
K,
apre,
outtype="bf16",
data_init="uniform",
scale_init="auto",
seed=0,
mode="perf",
knl_name=None,
num_warmup=2,
num_iters=None,
test_graph=False,
num_rotate=0,
):
# Skip unsupported combos up front (before prep/shuffle) so they show as
# "not support" rather than crashing on a shape assert.
pre = "ABpreShuffle" if apre else "BpreShuffle"
reason = _support_reason(outtype, apre, M, N, K)
if reason is not None:
base = f"f4gemm_{outtype}_{intype}_{pre}_256x256_4x4_ps"
actual_knl = knl_name if (knl_name and knl_name != "auto") else base
aiter.logger.warning(
"f4gemm not supported (%s): intype=%s outtype=%s apre=%s M=%s N=%s K=%s",
reason,
intype,
outtype,
apre,
M,
N,
K,
)
return {
"gfx": get_gfx(),
"knl_name": actual_knl,
"tile": "256x256",
"cluster": "4x4",
"asm us": float("nan"),
"asm TFLOPS": float("nan"),
"asm TB/s": float("nan"),
"asm err": float("nan"),
"asm result": f"not support ({reason})",
}
block = MXFP4_SCALE_BLOCK if intype == "mxfp4" else NVFP4_SCALE_BLOCK
assert K % block == 0, f"K must be a multiple of {block}"
out_fp8 = outtype == "fp8"
out_dtype = _OUT_DTYPE[outtype]
gen = make_generator(seed) # fixed seed -> bit-identical buffers
prep = _prep_mxfp4 if intype == "mxfp4" else _prep_nvfp4
inp, ref_f32 = prep(M, N, K, apre, data_init, scale_init, gen)
# Reference in the kernel's output form: block-scaled (fp8 e4m3 data + e8m0
# scale) tuple for fp8, else bf16.
if out_fp8:
ref = _quant_mxfp8_blockN(ref_f32) # (ref_fp8, ref_scale_e8m0)
else:
ref = ref_f32.to(out_dtype)
needTrace = mode == "profile"
# --iters overrides; unset keeps the mode default (func=5, perf/profile=101).
num_iters = num_iters if num_iters is not None else (5 if mode == "func" else 101)
# Kernel/.co base name for this config (used for logging, and to derive the
# mangled knl_name when an explicit dispatch is requested). See
# hsa/gfx1250/f4gemm/f4gemm.csv. (`pre` is set above.)
base = f"f4gemm_{outtype}_{intype}_{pre}_256x256_4x4_ps"
# Dispatch mode. Default (knl_name=None) is heuristic: kernelName="" lets the
# aiter op pick the .co from f4gemm.csv by (intype, a_preshuffle, outtype), so
# the test validates the op's dispatch. Explicit is opt-in via --knl-name:
# "auto" uses the per-config derived name below; any other value is used verbatim.
if knl_name is None:
knl = ""
elif knl_name == "auto":
knl = f"_ZN5aiter{len(base)}{base}E"
else:
knl = knl_name
# Pass inputs as ARGS so run_perftest can rotate them (defeats the L2 hot-cache).
if intype == "nvfp4":
def run_asm(A, B, sA, sB, gA, gB):
return aiter.gemm_nvfp4_asm(
A,
B,
sA,
sB,
gA,
gB,
dtype=out_dtype,
a_preshuffle=bool(apre),
kernelName=knl,
)
asm_args = (inp["A"], inp["B"], inp["sA"], inp["sB"], inp["gA"], inp["gB"])
else:
def run_asm(A, B, sA, sB):
return aiter.gemm_mxfp4_asm(
A,
B,
sA,
sB,
dtype=out_dtype,
a_preshuffle=bool(apre),
kernelName=knl,
)
asm_args = (inp["A"], inp["B"], inp["sA"], inp["sB"])
# Only the low-level asm entry is timed/tabled. (fn, args); args are rotated.
candidates = {"asm": (run_asm, asm_args)}
flops = 2 * M * N * K
# Output bytes: fp8 = M*N (fp8) + M*N/128 (e8m0 scale); bf16 = M*N*itemsize.
if out_fp8:
out_bytes = M * N + M * (N // MXFP8_OUT_SCALE_BLOCK)
else:
out_bytes = M * N * out_dtype.itemsize
# Scale bytes use the LOGICAL (unpadded) size: shuffle_scale_f4 pads scale rows
# to fill the preshuffle tile, but the shader clamps its scale dim and never
# reads the padding, so the padded buffer's .nbytes would inflate bandwidth.
# e8m0 (MXFP4) and e4m3 (NVFP4) are both 1 byte/elem; `block` is set above.
scale_bytes = (M + N) * (K // block)
nbytes = inp["A"].nbytes + inp["B"].nbytes + scale_bytes + out_bytes
# Report the actual .co in the table: readable base name for heuristic/"auto",
# the verbatim knl_name otherwise (kept in the table, see main()).
actual_knl = knl_name if (knl_name and knl_name != "auto") else base
ret = {"gfx": get_gfx(), "knl_name": actual_knl}
# Structured algo details (f4gemm.csv columns): F4GEMM tiles are always
# 256x256 with a 4x4 (cluster_x x cluster_y) cluster; no splitk/unroll axis.
ret["tile"] = "256x256"
ret["cluster"] = "4x4"
# Report TG occupancy for the 256x256 tile.
_report_active_tg(M, N, 256, 256, base)
# Only a missing .co is reported as "not support"; any other failure (OOM,
# memory fault, shape assert, ...) must propagate, not show as a green cell.
# An explicit --knl-name that isn't in the cfg is a real error (typo / missing
# build), so "kernel not in cfg" is benign ONLY on the heuristic path (knl == "").
_NOT_SUPPORTED_MARKERS = ("cannot get heuristic kernel",)
if not knl:
_NOT_SUPPORTED_MARKERS += ("kernel not in cfg_f4gemm",)
for name, (fn, fn_args) in candidates.items():
try:
out, us = run_perftest(
fn,
*fn_args,
num_iters=num_iters,
num_warmup=num_warmup,
testGraph=test_graph,
num_rotate_args=num_rotate,
needTrace=needTrace,
)
except Exception as e:
if not any(m in str(e) for m in _NOT_SUPPORTED_MARKERS):
raise
# No .co for this config; mark unsupported, keep going.
aiter.logger.warning(
"f4gemm not supported: intype=%s outtype=%s apre=%s "
"M=%s N=%s K=%s [%s.co]: %s",
intype,
outtype,
apre,
M,
N,
K,
base,
e,
)
ret[f"{name} us"] = float("nan")
ret[f"{name} TFLOPS"] = float("nan")
ret[f"{name} TB/s"] = float("nan")
ret[f"{name} err"] = float("nan")
ret[f"{name} result"] = "not support"
continue
# Func-mode only: check the high-level op contracts by outtype -- bf16 ->
# gemm_a4w4 (single tensor), fp8 -> gemm_a4w4o8 ((data, scale) tuple).
# Not timed/tabled.
if mode == "func":
a4_kwargs = {"apreshuffle": bool(apre)}
if intype == "nvfp4":
# global scales are Optional[Tensor] (schema); a non-None value
# selects the NVFP4 path -- wrap the float scalars as tensors.
a4_kwargs.update(
global_A_scale=torch.tensor(inp["gA"], device=inp["A"].device),
global_B_scale=torch.tensor(inp["gB"], device=inp["A"].device),
)
args = (inp["A"], inp["B"], inp["sA"], inp["sB"])
if out_fp8:
o, s = aiter.gemm_a4w4o8(*args, **a4_kwargs)
assert o.shape == out[0].shape and s.shape == out[1].shape, (
f"gemm_a4w4o8 shape mismatch: {tuple(o.shape)}/{tuple(s.shape)} "
f"vs {tuple(out[0].shape)}/{tuple(out[1].shape)}"
)
else: # bf16
res = aiter.gemm_a4w4(*args, dtype=out_dtype, **a4_kwargs)
assert not isinstance(res, tuple), "gemm_a4w4 must return a tensor"
assert (
res.shape == out.shape
), f"gemm_a4w4 shape mismatch: {tuple(res.shape)} vs {tuple(out.shape)}"
if out_fp8:
# (fp8 data, packed e8m0). Unpack scale to row-major; e8m0 compared
# with a +-1 step tolerance, data dequant with tolerance.
ref_fp8, ref_scale = ref
o_fp8, o_scale = out # o_* avoids shadowing the out_fp8 flag
M_out, N_out = o_fp8.shape
out_scale_rm = unpack_mxfp8_out_scale(o_scale, M_out, N_out)
err_s = checkAllclose(
ref_scale.view(torch.uint8).float(),
out_scale_rm.view(torch.uint8).float(),
rtol=0,
# e8m0 out-scale rounds with a single guard bit (no RNE); allow a
# +-1 e8m0-step slack for rounding-mode drift across shapes/kernels.
atol=1,
msg=f"{intype} {name} fp8 e8m0 (+-1)",
)
err_d = checkAllclose(
_dequant_mxfp8_blockN(ref_fp8, ref_scale),
_dequant_mxfp8_blockN(o_fp8, out_scale_rm),
rtol=1e-1,
atol=1.0,
msg=f"{intype} {name} fp8",
)
err = max(err_s, err_d)
else:
# Compare in fp32: checkAllclose does no dtype promotion, so a bf16
# comparison evaluates atol + rtol*|b| at 8-bit mantissa too. That
# makes the threshold itself jitter ~0.2% and systematically
# under-reports borderline elements.
err = checkAllclose(
ref.to(dtypes.fp32),
out.to(dtypes.fp32),
rtol=1e-1,
atol=1.0,
msg=f"{intype} {name}",
)
ret[f"{name} us"] = round(us, 2)
ret[f"{name} TFLOPS"] = round(flops / us / 1e6, 1)
ret[f"{name} TB/s"] = round(nbytes / us / 1e6, 2)
ret[f"{name} err"] = err
ret[f"{name} result"] = _verdict(err)
if needTrace:
ret[f"{name} trace"] = f"./aiter_logs/gpu_id_{torch.cuda.current_device()}"
return ret
def main():
# Whole-op arch gate goes HERE: @benchmark always returns the call-args dict,
# so an in-fn return would still emit an args-only NaN row.
if get_gfx() not in SUPPORTED_GFX:
aiter.logger.warning(
"gemm_a4w4 (F4GEMM) unsupported on %s; skipping", get_gfx()
)
return
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description="Test/benchmark gfx1250 A4W4 (F4GEMM) via the low-level asm entry",
)
parser.add_argument(
"--mode",
choices=["func", "perf", "profile"],
default="perf",
help="func=acc+timing table (fewer iters), perf=acc+timing table, profile=perf+trace",
)
parser.add_argument(
"--intype",
nargs="*",
choices=["mxfp4", "nvfp4"],
default=["mxfp4", "nvfp4"],
help="fp4 input format(s) to sweep, e.g. --intype nvfp4",
)
parser.add_argument(
"--apre",
type=int,
nargs="*",
choices=[1, 0],
default=None,
help="A-preshuffle sweep list: 1 preshuffles A (M%%16), 0 sends it "
"row-major (M%%1). Default (unset): perf/profile = [1], func = [1, 0].",
)
parser.add_argument(
"--outtype",
nargs="*",
choices=sorted(_OUT_DTYPE),
default=["bf16", "fp8"],
help="output-format sweep list (default: bf16 fp8):\n"
" bf16 = bf16 [M,N]\n"
" fp8 = fp8 e4m3 [M,N] + per-128 E8M0 scale (mxfp8)",
)
parser.add_argument(
"--data-init",
dest="data_init",
nargs="+",
choices=["zero", "constant", "uniform", "norm"],
default=None,
help="DATA init distribution(s) (sampled independently of scale).\n"
"Paired position-wise with --scale-init (length-1 broadcasts).\n"
"Default (unset): perf/profile = 'constant uniform', func = 'uniform'\n"
"(func drops constant: its exact-boundary values trigger e8m0/e4m3\n"
"edge rounding that shows as spurious warnings).\n"
" zero = all-zero e2m1 codes\n"
" constant = A=0x22, B=0x33 (deterministic)\n"
" uniform = FP4 U(-3,3)\n"
" norm = N(0,1) [norm-dist / LLM-like]",
)
parser.add_argument(
"--scale-init",
dest="scale_init",
nargs="+",
choices=["auto", "pow2_binomial", "zero", "constant", "uniform", "norm"],
default=None,
help="SCALE init distribution(s) (by scale format)\n"
"Default (unset): perf/profile = 'constant auto', func = 'auto'\n"
" auto = format-recommended: mxfp4/E8M0 -> pow2_binomial,\n"
" nvfp4/E4M3 -> gaussian(0.34375,0.08)\n"
" pow2_binomial = 2^(Binomial(21,0.5)-11) [E8M0 only]\n"
" zero = all-zero scale bytes\n"
" constant = neutral scale (2^0 = 1.0)\n"
" uniform = U(0.5,2) -> nearest on-wire byte\n"
" norm = N(1,0.25) -> nearest on-wire byte",
)
parser.add_argument(
"--seed",
type=int,
default=0,
help="RNG seed; same seed -> bit-identical data/scale buffers",
)
parser.add_argument(
"--warmup",
type=int,
default=2,
help="warmup iterations before timing (run_perftest num_warmup)",
)
parser.add_argument(
"--iters",
type=int,
default=None,
help="timed iterations (run_perftest num_iters); unset -> mode default "
"(func=5, perf/profile=101)",
)
parser.add_argument(
"--graph",
action="store_true",
help="also time via HIP graph replay (run_perftest testGraph), "
"minimizing inter-kernel gaps",
)
parser.add_argument(
"--rotate",
type=int,
default=0,
help="rotating input-buffer copies to defeat the L2 hot-cache "
"(run_perftest num_rotate_args); 0 = auto-size from L2",
)
parser.add_argument(
"--json",
dest="json_out",
default=None,
help="also write the full summary table (all columns) as JSON records "
"to this path, for CI/regression",
)
parser.add_argument(
"--knl-name",
dest="knl_name",
default=None,
help="dispatch mode. Default (unset) = heuristic: the aiter op picks the "
".co from f4gemm.csv by (intype, a_preshuffle, outtype), validating dispatch. "
"'auto' = force the per-config derived knl_name (explicit). Any other value "
"= use that exact mangled knl_name for all runs (developer experiment/debug).",
)
parser.add_argument(
"-s",
"-mnk",
"--shape",
type=dtypes.str2tuple,
nargs="*",
# Unset -> per-mode defaults: perf=PERF_SHAPES (one big square, throughput),
# func=FUNC_SHAPES (many small/odd shapes, correctness). K must be %32.
default=None,
help="(M,N,K) tuples, e.g. -mnk 2048,2048,2048 16384,16384,16384; "
"unset uses PERF_SHAPES (perf/profile) or FUNC_SHAPES (func)",
)
args = parser.parse_args()
# DATA and SCALE init are paired position-wise (NOT crossed). Mode-aware
# defaults when unset: perf/profile run constant+constant and uniform+auto;
# func drops the constant pair (its exact-boundary values trigger e8m0/e4m3
# edge rounding -> spurious warnings) and runs just uniform+auto. A length-1
# list broadcasts against the other axis.
if args.mode == "func":
default_di, default_si = ["uniform"], ["auto"]
else:
default_di, default_si = ["constant", "uniform"], ["constant", "auto"]
di_list = args.data_init if args.data_init is not None else default_di
si_list = args.scale_init if args.scale_init is not None else default_si
if len(di_list) == 1:
di_list = di_list * len(si_list)
if len(si_list) == 1:
si_list = si_list * len(di_list)
if len(di_list) != len(si_list):
parser.error(
"--data-init and --scale-init must have equal length "
"(or length 1 to broadcast)"
)
init_pairs = list(zip(di_list, si_list))
# Shapes: explicit --shape wins; otherwise func sweeps the many small/odd
# correctness shapes and perf/profile sweep the single throughput square.
if args.shape is not None:
shapes = args.shape
else:
shapes = FUNC_SHAPES if args.mode == "func" else PERF_SHAPES
# A-preshuffle sweep. Mode-aware default when unset: perf/profile exercise only
# the preshuffled path ([1]); func sweeps both ([1, 0]).
if args.apre is not None:
apre_list = args.apre
elif args.mode in ("perf", "profile"):
apre_list = [1]
else:
apre_list = [1, 0]
rows = [
test_gemm(
intype,
M,
N,
K,
apre,
outtype,
di,
si,
seed=args.seed,
mode=args.mode,
knl_name=args.knl_name,
num_warmup=args.warmup,
num_iters=args.iters,
test_graph=args.graph,
num_rotate=args.rotate,
)
for apre, (di, si), intype, outtype, (M, N, K) in itertools.product(
apre_list, init_pairs, args.intype, args.outtype, shapes
)
]
df_full = pd.DataFrame(rows)
# JSON keeps every column (config + algo details + results) so each record is
# self-describing for CI/regression; the markdown table below drops columns
# that are constant within a run for readability.
if args.json_out:
df_full.to_json(args.json_out, orient="records", indent=2)
aiter.logger.info(
"wrote JSON summary (%d rows) to %s", len(df_full), args.json_out
)
# Keep knl_name (the actual .co) + tile; drop columns constant within a table
# (cluster is always 4x4).
df = df_full.drop(
columns=[
"seed",
"gfx",
"mode",
"num_warmup",
"num_iters",
"test_graph",
"num_rotate",
],
errors="ignore",
)
aiter.logger.info(
"gemm_a4w4 (F4GEMM) summary (markdown):\n%s",
df.to_markdown(index=False),
)
if args.mode == "profile":
aiter.logger.info("profiler traces written under ./aiter_logs/")
if __name__ == "__main__":
main()