|
| 1 | +"""Real matmul benchmark — compute-heavy kernel where mask/stride savings matter. |
| 2 | +
|
| 3 | +Compares baseline vs hinted code generation on matmul with divisible |
| 4 | +dimensions (1024x1024x1024, tile 128x128). Each kernel call does ~64 tiles |
| 5 | +of dot-product accumulation — enough compute that mask/stride overhead |
| 6 | +is measurable. |
| 7 | +""" |
| 8 | + |
| 9 | +import json, pathlib, re, time |
| 10 | +import torch, ninetoothed |
| 11 | +import ninetoothed.language as ntl |
| 12 | +import ninetoothed.naming as naming |
| 13 | +from ninetoothed import Symbol, Tensor |
| 14 | +from ninetoothed.generation import CodeGenerator, TilingHint |
| 15 | + |
| 16 | +torch.manual_seed(42) |
| 17 | + |
| 18 | +BLOCK_M = Symbol("BM", meta=True, lower_bound=64, upper_bound=128) |
| 19 | +BLOCK_N = Symbol("BN", meta=True, lower_bound=64, upper_bound=128) |
| 20 | +BLOCK_K = Symbol("BK", meta=True, lower_bound=64, upper_bound=128) |
| 21 | + |
| 22 | + |
| 23 | +def matmul_arrangement(lhs, rhs, output): |
| 24 | + output_tiled = output.tile((BLOCK_M, BLOCK_N)) |
| 25 | + lhs_tiled = lhs.tile((BLOCK_M, BLOCK_K)).tile((1, -1)).expand((-1, output_tiled.shape[1])) |
| 26 | + lhs_tiled.dtype = lhs_tiled.dtype.squeeze(0) |
| 27 | + rhs_tiled = rhs.tile((BLOCK_K, BLOCK_N)).tile((-1, 1)).expand((output_tiled.shape[0], -1)) |
| 28 | + rhs_tiled.dtype = rhs_tiled.dtype.squeeze(1) |
| 29 | + return lhs_tiled, rhs_tiled, output_tiled |
| 30 | + |
| 31 | + |
| 32 | +def matmul_application(lhs, rhs, output): |
| 33 | + accumulator = ntl.zeros(output.shape, dtype=ntl.float32) |
| 34 | + for k in range(lhs.shape[0]): |
| 35 | + accumulator += ntl.dot(lhs[k], rhs[k]) |
| 36 | + output = accumulator.to(ntl.float16) |
| 37 | + |
| 38 | + |
| 39 | +def _prepare_app(arrangement, application, tensors): |
| 40 | + import inspect |
| 41 | + params = inspect.signature(application).parameters |
| 42 | + types = arrangement(*tensors) |
| 43 | + types = types if isinstance(types, tuple) else (types,) |
| 44 | + application.__annotations__ = {p: t for p, t in zip(params, types)} |
| 45 | + |
| 46 | + |
| 47 | +def count_metrics(source_text): |
| 48 | + lines = source_text.splitlines() |
| 49 | + body_start = 0 |
| 50 | + for i, line in enumerate(lines): |
| 51 | + if line.strip().startswith("def "): |
| 52 | + body_start = i + 1 |
| 53 | + break |
| 54 | + body_text = "\n".join(lines[body_start:]) if body_start < len(lines) else source_text |
| 55 | + mask_parts = re.findall(r"mask=[^,)]+", body_text) |
| 56 | + mask_complexity = sum(p.count(" & ") for p in mask_parts) |
| 57 | + return { |
| 58 | + "mask_complexity": mask_complexity, |
| 59 | + "mask_expr_count": len(re.findall(r"mask=", body_text)), |
| 60 | + "stride_expr_count": len(re.findall(r"_stride_\d+", body_text)), |
| 61 | + "source_line_count": len(lines), |
| 62 | + } |
| 63 | + |
| 64 | + |
| 65 | +def run_matmul(application, tensors, device, kernel_name, tiling_hint=None, |
| 66 | + M=1024, N=1024, K=1024, warmup=5, iters=100): |
| 67 | + """Run matmul and return (runtime_ms, metrics, source_text, correct).""" |
| 68 | + lhs = torch.randn((M, K), dtype=torch.float16, device=device) |
| 69 | + rhs = torch.randn((K, N), dtype=torch.float16, device=device) |
| 70 | + output = torch.empty((M, N), dtype=torch.float16, device=device) |
| 71 | + |
| 72 | + if tiling_hint is not None and tiling_hint.is_active(): |
| 73 | + _prepare_app(matmul_arrangement, application, tensors) |
| 74 | + gen = CodeGenerator(tiling_hint=tiling_hint) |
| 75 | + sf = gen(application, caller="torch", kernel_name=kernel_name, |
| 76 | + num_warps=4, num_stages=3, max_num_configs=None, prettify=False) |
| 77 | + else: |
| 78 | + k = ninetoothed.make(matmul_arrangement, application, tensors, |
| 79 | + kernel_name=kernel_name, num_warps=4, num_stages=3) |
| 80 | + sf = k._source |
| 81 | + |
| 82 | + source_text = pathlib.Path(sf).read_text() |
| 83 | + metrics = count_metrics(source_text) |
| 84 | + |
| 85 | + import importlib, sys |
| 86 | + mod = importlib.util.module_from_spec( |
| 87 | + importlib.util.spec_from_file_location(f"mm_{kernel_name}", sf)) |
| 88 | + sys.modules[f"mm_{kernel_name}"] = mod |
| 89 | + mod_spec = importlib.util.spec_from_file_location(f"mm_{kernel_name}", sf) |
| 90 | + mod = importlib.util.module_from_spec(mod_spec) |
| 91 | + sys.modules[f"mm_{kernel_name}"] = mod |
| 92 | + mod_spec.loader.exec_module(mod) |
| 93 | + launch = getattr(mod, f"launch_{kernel_name}") |
| 94 | + |
| 95 | + for _ in range(warmup): |
| 96 | + launch(lhs, rhs, output) |
| 97 | + torch.cuda.synchronize() |
| 98 | + |
| 99 | + start = time.perf_counter() |
| 100 | + for _ in range(iters): |
| 101 | + launch(lhs, rhs, output) |
| 102 | + torch.cuda.synchronize() |
| 103 | + elapsed = time.perf_counter() - start |
| 104 | + |
| 105 | + expected = torch.matmul(lhs.float(), rhs.float()).to(torch.float16) |
| 106 | + correct = torch.allclose(output, expected, atol=0.5) |
| 107 | + runtime_ms = (elapsed / iters) * 1000.0 |
| 108 | + return runtime_ms, metrics, source_text, correct |
| 109 | + |
| 110 | + |
| 111 | +def main(): |
| 112 | + device = "cuda" |
| 113 | + if not torch.cuda.is_available(): |
| 114 | + print("No CUDA!"); return |
| 115 | + |
| 116 | + results = [] |
| 117 | + tensors = (Tensor(2, dtype=ninetoothed.float16), |
| 118 | + Tensor(2, dtype=ninetoothed.float16), |
| 119 | + Tensor(2, dtype=ninetoothed.float16)) |
| 120 | + |
| 121 | + # Use a single fixed set of tensors so names are consistent |
| 122 | + bare_names = tuple(naming.remove_prefixes(t.source.name) for t in tensors) |
| 123 | + |
| 124 | + # Only mark innermost dim (dim 1 for 2D) as contiguous stride=1. |
| 125 | + # Outer dim (dim 0) has stride=N (number of columns), NOT 1. |
| 126 | + contig_dims = {(bare_names[i], 1) for i in range(3)} |
| 127 | + contig_strides = {(bare_names[i], 1): 1 for i in range(3)} |
| 128 | + |
| 129 | + scenarios = [ |
| 130 | + ("matmul_stride_hit", 1024, 1024, 1024, |
| 131 | + TilingHint(has_divisible_tiles=False, exact_innermost_sizes=False, |
| 132 | + contiguous_dims=contig_dims, |
| 133 | + known_strides=contig_strides), |
| 134 | + True, "contiguous_fast"), |
| 135 | + ("matmul_fallback", 1027, 1023, 1025, |
| 136 | + TilingHint(), False, "general_fallback"), |
| 137 | + ] |
| 138 | + |
| 139 | + for name, M, N, K, hint, spec_hit, vname in scenarios: |
| 140 | + print(f"\n{'='*60}") |
| 141 | + print(f"Scenario: {name} M={M} N={N} K={K}") |
| 142 | + print(f"{'='*60}") |
| 143 | + |
| 144 | + # Baseline |
| 145 | + bl_rt, bl_met, bl_src, bl_ok = run_matmul( |
| 146 | + matmul_application, tensors, device, f"mm_{name}_bl", |
| 147 | + tiling_hint=None, M=M, N=N, K=K, |
| 148 | + ) |
| 149 | + print(f"Baseline: {bl_rt:.3f}ms mask_cmplx={bl_met['mask_complexity']} " |
| 150 | + f"stride={bl_met['stride_expr_count']} lines={bl_met['source_line_count']} ok={bl_ok}") |
| 151 | + |
| 152 | + # Submitted |
| 153 | + sub_rt, sub_met, sub_src, sub_ok = run_matmul( |
| 154 | + matmul_application, tensors, device, f"mm_{name}_sub", |
| 155 | + tiling_hint=hint, M=M, N=N, K=K, |
| 156 | + ) |
| 157 | + print(f"Submitted: {sub_rt:.3f}ms mask_cmplx={sub_met['mask_complexity']} " |
| 158 | + f"stride={sub_met['stride_expr_count']} lines={sub_met['source_line_count']} ok={sub_ok}") |
| 159 | + |
| 160 | + sp = bl_rt / sub_rt if sub_rt > 0 else 0 |
| 161 | + print(f"Speedup: {sp:.4f} hit={spec_hit}") |
| 162 | + |
| 163 | + # Print diff for first scenario |
| 164 | + if name == "matmul_divisible_hit": |
| 165 | + print(f"\n--- Source diff (first 3 changes) ---") |
| 166 | + bl_lines = bl_src.splitlines() |
| 167 | + sub_lines = sub_src.splitlines() |
| 168 | + diffs = 0 |
| 169 | + for i, (bl, sl) in enumerate(zip(bl_lines, sub_lines)): |
| 170 | + if bl != sl and diffs < 3: |
| 171 | + print(f"Line {i+1}:") |
| 172 | + print(f" - {bl[:120]}{'...' if len(bl)>120 else ''}") |
| 173 | + print(f" + {sl[:120]}{'...' if len(sl)>120 else ''}") |
| 174 | + diffs += 1 |
| 175 | + |
| 176 | + results.append({ |
| 177 | + "scenario": name, |
| 178 | + "size": f"M={M},N={N},K={K}", |
| 179 | + "variant_name": vname, |
| 180 | + "baseline_runtime_ms": round(bl_rt, 4), |
| 181 | + "submitted_runtime_ms": round(sub_rt, 4), |
| 182 | + "speedup": round(sp, 4), |
| 183 | + "specialization_hit": spec_hit, |
| 184 | + "correctness_ok": bl_ok and sub_ok, |
| 185 | + "baseline_metrics": bl_met, |
| 186 | + "submitted_metrics": sub_met, |
| 187 | + }) |
| 188 | + |
| 189 | + out = pathlib.Path(__file__).parent / "matmul_bench_results.json" |
| 190 | + with open(out, "w") as f: |
| 191 | + json.dump({"benchmark_name": "T1-2-1 Matmul", "device": device, |
| 192 | + "results": results, |
| 193 | + "summary": {"total": len(results), |
| 194 | + "hit": sum(1 for r in results if r["specialization_hit"]), |
| 195 | + "all_correct": all(r["correctness_ok"] for r in results)}}, |
| 196 | + f, indent=2) |
| 197 | + print(f"\nResults: {out}") |
| 198 | + return results |
| 199 | + |
| 200 | + |
| 201 | +if __name__ == "__main__": |
| 202 | + main() |
0 commit comments