rich7421 commited on
Commit
5c94dea
·
verified ·
1 Parent(s): fa05bf1

Add minimal runnable example (Ray Data GPU actor + Nsight)

Browse files
Files changed (1) hide show
  1. example_min.py +96 -0
example_min.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal Ray Data GPU profiling example (the shape used in the article).
2
+
3
+ The GPU work runs *inside* Ray Data — a `map_batches` call whose UDF is a
4
+ callable class placed on a GPU actor (`num_gpus=1`). Nsight is attached only to
5
+ that actor via `runtime_env`, so the .nsys-rep captures the GPU stage and not
6
+ the driver or the CPU operators.
7
+
8
+ Run (a machine with one NVIDIA GPU, Ray + PyTorch + the `nsys` CLI on PATH):
9
+
10
+ python example_min.py # split: CPU load op -> GPU actor
11
+ python example_min.py --inline # load fused into the GPU UDF
12
+
13
+ Then export the report nsys wrote under the Ray session for analysis:
14
+
15
+ rep=$(ls -t /tmp/ray/session_*/logs/nsight/*.nsys-rep | head -1)
16
+ nsys export --type sqlite --include-blobs=true -o out.sqlite "$rep"
17
+ nsys-ai skill run gpu_idle_gaps out.sqlite -p device=0 --format json
18
+
19
+ Note: on Ray <= a version without the #66094 fix, launch with the venv on PATH
20
+ (activate it, or `export PATH=<venv>/bin:$PATH`) so the profiled worker's bare
21
+ `python` resolves; and let the driver stay alive until the report is written
22
+ (this example does), otherwise teardown can truncate it (ray#60904).
23
+ """
24
+
25
+ import argparse
26
+ import time
27
+
28
+ import numpy as np
29
+ import ray
30
+ import torch
31
+
32
+ ROWS, WIDTH, BATCHES, ITERS = 2048, 8192, 32, 9 # ~64 MiB/batch, ~39 ms GPU/batch
33
+ LOAD_MS = 40 # stand-in for real decode/IO; ~matches the GPU time on purpose
34
+
35
+
36
+ def load_batch(batch):
37
+ """CPU data prep. In `split` mode this is its own Ray Data operator."""
38
+ time.sleep(LOAD_MS / 1000)
39
+ return {"x": np.ones((ROWS, WIDTH), dtype=np.float32)}
40
+
41
+
42
+ class Predict:
43
+ """The GPU stage. A callable class so Ray Data runs it on a GPU actor."""
44
+
45
+ def __init__(self, inline):
46
+ torch.cuda.set_device(0)
47
+ self.inline = inline
48
+ self.weight = torch.eye(WIDTH, device="cuda")
49
+ (torch.ones((ROWS, WIDTH), device="cuda") @ self.weight).cpu() # warm up
50
+
51
+ def __call__(self, batch):
52
+ if self.inline: # data prep fused into the GPU UDF (serial load->compute)
53
+ batch = load_batch(batch)
54
+ x = torch.tensor(batch["x"], device="cuda") # H2D
55
+ for _ in range(ITERS):
56
+ x = x @ self.weight
57
+ return {"out": x[:, 0].cpu().numpy()} # D2H
58
+
59
+
60
+ def main():
61
+ ap = argparse.ArgumentParser()
62
+ ap.add_argument("--inline", action="store_true", help="fuse load into the GPU UDF")
63
+ ap.add_argument("--profile", action="store_true", help="attach Nsight to the actor")
64
+ args = ap.parse_args()
65
+
66
+ ray.init(num_cpus=8, num_gpus=1, include_dashboard=False)
67
+ ds = ray.data.range(ROWS * BATCHES, override_num_blocks=BATCHES)
68
+
69
+ if not args.inline: # CPU prep as its own operator, so it can run ahead
70
+ ds = ds.map_batches(
71
+ load_batch, batch_size=ROWS, batch_format="numpy",
72
+ compute=ray.data.TaskPoolStrategy(size=4), num_cpus=1,
73
+ )
74
+
75
+ gpu_kwargs = dict(
76
+ batch_size=ROWS, batch_format="numpy",
77
+ fn_constructor_args=(args.inline,),
78
+ compute=ray.data.ActorPoolStrategy(size=1, max_tasks_in_flight_per_actor=4),
79
+ num_cpus=1, num_gpus=1, # <-- the GPU work is a Ray Data actor
80
+ )
81
+ if args.profile:
82
+ gpu_kwargs["runtime_env"] = {
83
+ "nsight": {"t": "cuda,nvtx", "sample": "none",
84
+ "cpuctxsw": "none", "stop-on-exit": "true"}
85
+ }
86
+ ds = ds.map_batches(Predict, **gpu_kwargs)
87
+
88
+ t0 = time.perf_counter()
89
+ ds.materialize()
90
+ print(f"mode={'inline' if args.inline else 'split'} "
91
+ f"E2E={time.perf_counter() - t0:.2f}s")
92
+ ray.shutdown()
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()