File size: 11,009 Bytes
56fccf8 7202032 56fccf8 7202032 56fccf8 7202032 56fccf8 7202032 56fccf8 7202032 56fccf8 | 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 | """What does THIS machine actually support? Re-derives the tables in ref/ by compiling.
python3 check_toolchain.py [sm_90a] # one target (default: this GPU)
python3 check_toolchain.py --matrix # sm_89 / sm_90a / sm_100a / sm_120a side by side
The reference docs were verified on sm_90a / CUDA 12.8. On a different GPU or toolkit some rows change
-- tcgen05 appears on Blackwell, wgmma disappears below Hopper. Run this instead of trusting the tables.
"""
import json, os, subprocess, sys, tempfile
ARGS = sys.argv[1:]
MATRIX = "--matrix" in ARGS
ARCH = next((a for a in ARGS if a.startswith("sm_")), None)
MATRIX_ARCHS = ["sm_89", "sm_90a", "sm_100a", "sm_120a"]
def _arch():
if ARCH:
return ARCH
try:
import torch
cc = torch.cuda.get_device_capability(0)
a = f"sm_{cc[0]}{cc[1]}"
return a + "a" if cc[0] >= 9 else a # the 'a' target enables wgmma/TMA/setmaxnreg
except Exception:
return "sm_90a"
PTX = [
("ld.global.nc", r'asm volatile("ld.global.nc.f32 %0, [%1];" : "=f"(f) : "l"(pf));', ""),
("ld.global.L2::128B", r'asm volatile("ld.global.L2::128B.f32 %0, [%1];" : "=f"(f) : "l"(pf));', ""),
("ld.global.v4.f32", r'asm volatile("ld.global.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(v0),"=f"(v1),"=f"(v2),"=f"(v3) : "l"(pf));', "float v0,v1,v2,v3;"),
("cp.async.cg", r'asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" :: "r"(smem), "l"(pf));', ""),
("cp.async.bulk.tensor (TMA)", r'asm volatile("cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" :: "r"(smem), "l"(pf), "r"(x), "r"(y), "r"(bar));', ""),
("mbarrier.arrive.expect_tx", r'asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 %0, [%1], %2;" : "=l"(l) : "r"(smem), "r"(x));', ""),
("fence.proxy.async", r'asm volatile("fence.proxy.async.shared::cta;");', ""),
("barrier.cluster", r'asm volatile("barrier.cluster.arrive;"); asm volatile("barrier.cluster.wait;");', ""),
("mma.sync m16n8k16 bf16", r'asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" : "+f"(v0),"+f"(v1),"+f"(v2),"+f"(v3) : "r"(a0),"r"(a1),"r"(a2),"r"(a3),"r"(b0),"r"(b1));', "float v0,v1,v2,v3; unsigned a0=0,a1=0,a2=0,a3=0,b0=0,b1=0;"),
("mma.sync m16n8k32 fp8", r'asm volatile("mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" : "+f"(v0),"+f"(v1),"+f"(v2),"+f"(v3) : "r"(a0),"r"(a1),"r"(a2),"r"(a3),"r"(b0),"r"(b1));', "float v0,v1,v2,v3; unsigned a0=0,a1=0,a2=0,a3=0,b0=0,b1=0;"),
("wgmma.fence/commit/wait", r'asm volatile("wgmma.fence.sync.aligned;"); asm volatile("wgmma.commit_group.sync.aligned;"); asm volatile("wgmma.wait_group.sync.aligned 0;");', ""),
("ldmatrix .x4", r'asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];" : "=r"(a0),"=r"(a1),"=r"(a2),"=r"(a3) : "r"(smem));', "unsigned a0,a1,a2,a3;"),
("stmatrix .x4", r'asm volatile("stmatrix.sync.aligned.m8n8.x4.shared.b16 [%0], {%1,%2,%3,%4};" :: "r"(smem),"r"(a0),"r"(a1),"r"(a2),"r"(a3));', "unsigned a0=0,a1=0,a2=0,a3=0;"),
("redux.sync.add", r'asm volatile("redux.sync.add.u32 %0, %1, -1;" : "=r"(x) : "r"(y));', ""),
("elect.sync", r'asm volatile("{.reg .pred p; .reg .b32 r; elect.sync r|p, -1; }");', ""),
("setmaxnreg", r'asm volatile("setmaxnreg.inc.sync.aligned.u32 232;");', ""),
("griddepcontrol", r'asm volatile("griddepcontrol.wait;");', ""),
("cvt e4m3x2", r'asm volatile("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(h) : "f"(f), "f"(f));', ""),
("ex2.approx.f32", r'asm volatile("ex2.approx.f32 %0, %1;" : "=f"(f) : "f"(f));', ""),
("red.global.add.f32", r'asm volatile("red.global.add.f32 [%0], %1;" :: "l"(pf), "f"(f));', ""),
("tcgen05.fence (Blackwell DC)", r'asm volatile("tcgen05.fence::before_thread_sync;");', ""),
("tcgen05.alloc (tensor memory)", r'asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" :: "r"(smem), "r"(x));', ""),
("cvt e2m1x2 (fp4; dst .b8)", r'asm volatile("{ .reg .b8 t; cvt.rn.satfinite.e2m1x2.f32 t, %1, %2; cvt.u16.u8 %0, t; }" : "=h"(h) : "f"(f), "f"(f));', ""),
("cvt e2m3x2 (fp6)", r'asm volatile("{ .reg .b16 t; cvt.rn.satfinite.e2m3x2.f32 t, %1, %2; mov.b16 %0, t; }" : "=h"(h) : "f"(f), "f"(f));', ""),
("cvt.rz ue8m0x2 (MX scale; .rz only)", r'asm volatile("cvt.rz.satfinite.ue8m0x2.f32 %0, %1, %2;" : "=h"(h) : "f"(f), "f"(f));', ""),
]
TPL = """#include <cuda_fp16.h>
__global__ void k(float* pf, unsigned* pu) {{
float f = 0.f; unsigned x = 0, y = 0, smem = 0, bar = 0; unsigned short h = 0;
unsigned long long l = 0;
{decls}
{body}
if (f == 1.f) pf[0] = f; pu[0] = x + h;
}}
"""
def compile_ok(src, arch, extra=()):
with tempfile.NamedTemporaryFile("w", suffix=".cu", delete=False) as fh:
fh.write(src); p = fh.name
try:
r = subprocess.run(["nvcc", f"-arch={arch}", "-std=c++17", *extra, "-cubin", "-o", os.devnull, p],
capture_output=True, text=True)
return r.returncode == 0
finally:
os.unlink(p)
def wgmma_acc(arch):
"""wgmma.m64nNk16.f32 needs N/2 accumulator registers per thread -- confirm on this target."""
out = {}
for N in (8, 16, 64, 128, 256):
n = N // 2
regs = ",".join(f"%{i}" for i in range(n))
outs = ",".join(f'"+f"(d[{i}])' for i in range(n))
src = f"""__global__ void k(float* o) {{
unsigned long long da=0, db=0; float d[{n}];
#pragma unroll
for (int i=0;i<{n};++i) d[i]=0.f;
asm volatile("wgmma.fence.sync.aligned;");
asm volatile("wgmma.mma_async.sync.aligned.m64n{N}k16.f32.bf16.bf16 {{{regs}}}, %{n}, %{n+1}, 1,1,1,0,0;"
: {outs} : "l"(da), "l"(db));
asm volatile("wgmma.commit_group.sync.aligned;");
for (int i=0;i<{n};++i) o[i]=d[i];
}}"""
out[f"m64n{N}k16"] = (n, compile_ok(src, arch))
return out
def triton_report():
try:
import torch, triton, triton.language as tl
except Exception as e:
return {"error": f"{type(e).__name__}: {e}"}
names = ["dot", "dot_scaled", "make_block_ptr", "make_tensor_descriptor",
"load_tensor_descriptor", "store_tensor_descriptor", "associative_scan",
"inline_asm_elementwise", "assume", "range", "sort", "histogram", "gather"]
rep = {"version": triton.__version__,
"present": [n for n in names if hasattr(tl, n)],
"absent": [n for n in names if not hasattr(tl, n)]}
# the cache_modifier x eviction_policy combination trap
import itertools
@triton.jit
def _k(X, Y, N, BLOCK: tl.constexpr, CM: tl.constexpr, EP: tl.constexpr):
o = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
m = o < N
tl.store(Y + o, tl.load(X + o, mask=m, other=0.0, cache_modifier=CM, eviction_policy=EP), mask=m)
x = torch.randn(4096, device="cuda"); y = torch.empty_like(x)
combos = {}
# a rejected combination makes Triton dump the whole failing PTX to the console; the point here is
# the verdict, not the dump, so silence both fds around the probe.
import contextlib, io
for cm, ep in itertools.product(["", ".ca", ".cg", ".cs"], ["", "evict_first", "evict_last"]):
buf = io.StringIO()
devnull = os.open(os.devnull, os.O_WRONLY)
saved = os.dup(1), os.dup(2)
try:
# flush FIRST: piped stdout is block-buffered, and anything still pending would other-
# wise be flushed into /dev/null once fd 1 is redirected -- silently eating the report.
sys.stdout.flush(); sys.stderr.flush()
os.dup2(devnull, 1); os.dup2(devnull, 2)
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
_k[(4,)](x, y, x.numel(), BLOCK=1024, CM=cm, EP=ep); torch.cuda.synchronize()
v = "ok"
except Exception as e:
v = "PTXAS" if "ptxas" in str(e).lower() else type(e).__name__
finally:
sys.stdout.flush(); sys.stderr.flush()
os.dup2(saved[0], 1); os.dup2(saved[1], 2)
os.close(devnull); os.close(saved[0]); os.close(saved[1])
combos[f"{cm or 'none'}|{ep or 'none'}"] = v
rep["load_modifier_combos"] = combos
return rep
def matrix():
"""Cross-architecture view. Compiling for a target you do not own is still authoritative about
what ASSEMBLES there -- it says nothing about how fast it runs."""
ok = [a for a in MATRIX_ARCHS
if compile_ok(TPL.format(body="", decls=""), a)]
if not ok:
print("no targets supported by this nvcc"); return
w = max(len(l) for l, _, _ in PTX)
print(f"{'instruction':<{w}} " + " ".join(f"{a:>9}" for a in ok))
print("-" * (w + 2 + 11 * len(ok)))
for label, body, decls in PTX:
row = [compile_ok(TPL.format(body=body, decls=decls), a) for a in ok]
print(f"{label:<{w}} " + " ".join(f"{'yes' if r else '-':>9}" for r in row))
print("\n'yes' = assembles on that target. Nothing here is a statement about speed.")
def main():
if MATRIX:
return matrix()
arch = _arch()
nvcc = subprocess.run(["nvcc", "--version"], capture_output=True, text=True).stdout.strip().splitlines()
print(f"target {arch} {nvcc[-1] if nvcc else 'nvcc not found'}\n")
print("PTX instructions")
res = {}
for label, body, decls in PTX:
ok = compile_ok(TPL.format(body=body, decls=decls), arch)
res[label] = ok
print(f" {'ok ' if ok else 'NO '} {label}")
print("\nwgmma accumulator registers per thread (N/2 expected)")
for shape, (n, ok) in wgmma_acc(arch).items():
print(f" {'ok ' if ok else 'NO '} {shape:12s} {n} regs")
print("\nCuTe / CUTLASS")
for inc in ("/opt/pytorch/third_party/cutlass/include", "/usr/local/cutlass/include"):
if os.path.isdir(inc + "/cute"):
ok = compile_ok('#include <cute/tensor.hpp>\n__global__ void k(){}', arch,
(f"-I{inc}", "--expt-relaxed-constexpr"))
print(f" {'ok ' if ok else 'NO '} headers at {inc}")
break
else:
print(" -- no cute headers found")
print("\nTriton")
t = triton_report()
if "error" in t:
print(" " + t["error"])
else:
print(f" version {t['version']}")
print(f" present: {', '.join(t['present'])}")
if t["absent"]:
print(f" absent : {', '.join(t['absent'])}")
bad = [k for k, v in t["load_modifier_combos"].items() if v != "ok"]
print(f" tl.load cache_modifier|eviction_policy combos that FAIL: {', '.join(bad) or 'none'}")
print("\n(ref/*.md was verified on sm_90a / CUDA 12.8; anything above that disagrees wins.)")
if __name__ == "__main__":
main()
|