| """Roofline: the ceiling, and whether you are compute- or memory-bound. |
| |
| Measures the device rather than trusting a datasheet -- achieved bandwidth from a large stream-copy, |
| achieved dense throughput from a big GEMM. Both are what you can actually reach, which is the number |
| that matters when deciding where the headroom is. |
| |
| python3 roofline.py --flops 3.4e11 --bytes 2.5e9 --dtype bf16 |
| """ |
| import argparse |
| import torch |
|
|
|
|
| def measured_bandwidth(mb=512): |
| n = mb * 1024 * 1024 // 2 |
| a = torch.empty(n, device="cuda", dtype=torch.bfloat16) |
| b = torch.empty_like(a) |
| for _ in range(3): |
| b.copy_(a) |
| torch.cuda.synchronize() |
| s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) |
| s.record() |
| for _ in range(10): |
| b.copy_(a) |
| e.record(); torch.cuda.synchronize() |
| return 10 * 2 * a.numel() * 2 / (s.elapsed_time(e) / 1e3) |
|
|
|
|
| def measured_flops(dtype=torch.bfloat16, n=8192): |
| a = torch.randn(n, n, device="cuda", dtype=dtype) |
| b = torch.randn(n, n, device="cuda", dtype=dtype) |
| for _ in range(3): |
| a @ b |
| torch.cuda.synchronize() |
| s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) |
| s.record() |
| for _ in range(10): |
| a @ b |
| e.record(); torch.cuda.synchronize() |
| return 10 * 2 * n ** 3 / (s.elapsed_time(e) / 1e3) |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--flops", type=float, default=0.0) |
| ap.add_argument("--bytes", type=float, default=0.0) |
| ap.add_argument("--dtype", default="bf16") |
| a = ap.parse_args() |
|
|
| p = torch.cuda.get_device_properties(0) |
| bw, fl = measured_bandwidth(), measured_flops() |
| print(f"device {p.name} sm_{p.major}{p.minor} SMs={p.multi_processor_count} " |
| f"smem_optin={p.shared_memory_per_block_optin//1024}KB") |
| print(f"measured bandwidth {bw/1e12:.3f} TB/s measured dense bf16 {fl/1e12:.1f} TFLOP/s") |
| if not (a.flops or a.bytes): |
| return |
| t_mem = a.bytes / bw if a.bytes else 0.0 |
| t_cmp = a.flops / fl if a.flops else 0.0 |
| bound = "memory" if t_mem >= t_cmp else "compute" |
| print(f"\nwork {a.flops:.3g} FLOP {a.bytes:.3g} B " |
| f"intensity {(a.flops/a.bytes if a.bytes else float('inf')):.1f} FLOP/B") |
| print(f"floor (memory) {t_mem*1e6:9.1f} us") |
| print(f"floor (compute) {t_cmp*1e6:9.1f} us") |
| print(f"-> {bound}-bound, floor {max(t_mem,t_cmp)*1e6:.1f} us") |
| print("\nNote: this floor comes from an ATTRIBUTION formula, not a physical wall. A kernel that " |
| "moves fewer bytes than counted -- cache reuse, recompute, a better layout -- can beat it. " |
| "Orientation, not a stopping rule.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|