Download example_min.py from rich7421/ray-data-gpu-idle-profiles: direct link, hf CLI and curl.
- Browser
- Download file 3.61 kB
-
https://huggingface.co/datasets/rich7421/ray-data-gpu-idle-profiles/resolve/main/example_min.py
- Command line
-
hf download hf://datasets/rich7421/ray-data-gpu-idle-profiles/example_min.py
-
curl -L -o example_min.py https://huggingface.co/datasets/rich7421/ray-data-gpu-idle-profiles/resolve/main/example_min.py
3.61 kB
| """Minimal Ray Data GPU profiling example (the shape used in the article). | |
| The GPU work runs *inside* Ray Data — a `map_batches` call whose UDF is a | |
| callable class placed on a GPU actor (`num_gpus=1`). Nsight is attached only to | |
| that actor via `runtime_env`, so the .nsys-rep captures the GPU stage and not | |
| the driver or the CPU operators. | |
| Run (a machine with one NVIDIA GPU, Ray + PyTorch + the `nsys` CLI on PATH): | |
| python example_min.py # split: CPU load op -> GPU actor | |
| python example_min.py --inline # load fused into the GPU UDF | |
| Then export the report nsys wrote under the Ray session for analysis: | |
| rep=$(ls -t /tmp/ray/session_*/logs/nsight/*.nsys-rep | head -1) | |
| nsys export --type sqlite --include-blobs=true -o out.sqlite "$rep" | |
| nsys-ai skill run gpu_idle_gaps out.sqlite -p device=0 --format json | |
| Note: on Ray <= a version without the #66094 fix, launch with the venv on PATH | |
| (activate it, or `export PATH=<venv>/bin:$PATH`) so the profiled worker's bare | |
| `python` resolves; and let the driver stay alive until the report is written | |
| (this example does), otherwise teardown can truncate it (ray#60904). | |
| """ | |
| import argparse | |
| import time | |
| import numpy as np | |
| import ray | |
| import torch | |
| ROWS, WIDTH, BATCHES, ITERS = 2048, 8192, 32, 9 # ~64 MiB/batch, ~39 ms GPU/batch | |
| LOAD_MS = 40 # stand-in for real decode/IO; ~matches the GPU time on purpose | |
| def load_batch(batch): | |
| """CPU data prep. In `split` mode this is its own Ray Data operator.""" | |
| time.sleep(LOAD_MS / 1000) | |
| return {"x": np.ones((ROWS, WIDTH), dtype=np.float32)} | |
| class Predict: | |
| """The GPU stage. A callable class so Ray Data runs it on a GPU actor.""" | |
| def __init__(self, inline): | |
| torch.cuda.set_device(0) | |
| self.inline = inline | |
| self.weight = torch.eye(WIDTH, device="cuda") | |
| (torch.ones((ROWS, WIDTH), device="cuda") @ self.weight).cpu() # warm up | |
| def __call__(self, batch): | |
| if self.inline: # data prep fused into the GPU UDF (serial load->compute) | |
| batch = load_batch(batch) | |
| x = torch.tensor(batch["x"], device="cuda") # H2D | |
| for _ in range(ITERS): | |
| x = x @ self.weight | |
| return {"out": x[:, 0].cpu().numpy()} # D2H | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--inline", action="store_true", help="fuse load into the GPU UDF") | |
| ap.add_argument("--profile", action="store_true", help="attach Nsight to the actor") | |
| args = ap.parse_args() | |
| ray.init(num_cpus=8, num_gpus=1, include_dashboard=False) | |
| ds = ray.data.range(ROWS * BATCHES, override_num_blocks=BATCHES) | |
| if not args.inline: # CPU prep as its own operator, so it can run ahead | |
| ds = ds.map_batches( | |
| load_batch, batch_size=ROWS, batch_format="numpy", | |
| compute=ray.data.TaskPoolStrategy(size=4), num_cpus=1, | |
| ) | |
| gpu_kwargs = dict( | |
| batch_size=ROWS, batch_format="numpy", | |
| fn_constructor_args=(args.inline,), | |
| compute=ray.data.ActorPoolStrategy(size=1, max_tasks_in_flight_per_actor=4), | |
| num_cpus=1, num_gpus=1, # <-- the GPU work is a Ray Data actor | |
| ) | |
| if args.profile: | |
| gpu_kwargs["runtime_env"] = { | |
| "nsight": {"t": "cuda,nvtx", "sample": "none", | |
| "cpuctxsw": "none", "stop-on-exit": "true"} | |
| } | |
| ds = ds.map_batches(Predict, **gpu_kwargs) | |
| t0 = time.perf_counter() | |
| ds.materialize() | |
| print(f"mode={'inline' if args.inline else 'split'} " | |
| f"E2E={time.perf_counter() - t0:.2f}s") | |
| ray.shutdown() | |
| if __name__ == "__main__": | |
| main() | |