ariG23498 HF Staff commited on
Commit
8e23137
·
verified ·
1 Parent(s): ff7514a

Create 01_matmul_add.py

Browse files
Files changed (1) hide show
  1. 01_matmul_add.py +77 -0
01_matmul_add.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import torch
4
+
5
+
6
+ def parse_arguments():
7
+ p = argparse.ArgumentParser()
8
+ p.add_argument("--size", type=int, default=64)
9
+ p.add_argument("--dtype", choices=["bf16", "fp32"], default="bf16")
10
+ p.add_argument("--compile", action="store_true")
11
+ p.add_argument("--warmup", action="store_true")
12
+ p.add_argument("--trace_dir", default="./traces/01_matmul_add")
13
+ return p.parse_args()
14
+
15
+
16
+ def main():
17
+ args = parse_arguments()
18
+
19
+ device = "cuda"
20
+ dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float32
21
+
22
+ x = torch.randn(args.size, args.size, device=device, dtype=dtype)
23
+ w = torch.randn(args.size, args.size, device=device, dtype=dtype)
24
+ b = torch.randn(args.size, args.size, device=device, dtype=dtype)
25
+
26
+ def fn(x, w, b):
27
+ return torch.add(torch.matmul(x, w), b)
28
+
29
+ fn = torch.compile(fn) if args.compile else fn
30
+
31
+ def step():
32
+ with torch.profiler.record_function("matmul_add"):
33
+ return fn(x, w, b)
34
+
35
+ if args.warmup:
36
+ for _ in range(3):
37
+ step()
38
+ # you're flushing the queue so the upcoming profiled steps aren't credited for prior work
39
+ torch.cuda.synchronize()
40
+
41
+ os.makedirs(args.trace_dir, exist_ok=True)
42
+ compile_tag = "compile" if args.compile else "eager"
43
+ warmup_tag = "warm" if args.warmup else "cold"
44
+ tag = f"{args.size}_{args.dtype}_{warmup_tag}_{compile_tag}"
45
+
46
+ table_path = os.path.join(args.trace_dir, f"{tag}.txt")
47
+ trace_path = os.path.join(args.trace_dir, f"{tag}.json")
48
+
49
+ # wait skips noisy init, warmup runs through the profiler without
50
+ # recording (so caches/autotune settle), active is what shows up in
51
+ # the table/trace.
52
+ schedule = torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1)
53
+ with torch.profiler.profile(
54
+ activities=[
55
+ torch.profiler.ProfilerActivity.CPU,
56
+ torch.profiler.ProfilerActivity.CUDA,
57
+ ],
58
+ schedule=schedule,
59
+ record_shapes=False, # adds CPU overhead
60
+ profile_memory=False, # adds CPU overhead
61
+ with_stack=False,
62
+ ) as prof:
63
+ for _ in range(5):
64
+ step()
65
+ prof.step()
66
+
67
+ torch.cuda.synchronize()
68
+
69
+ print(f"saving traces ... {trace_path}")
70
+ prof.export_chrome_trace(trace_path)
71
+
72
+ with open(table_path, "w") as f:
73
+ f.write(prof.key_averages().table(sort_by="cuda_time_total", row_limit=15))
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()