rich7421's picture
Ray Data GPU idle profiles: four modes + before/after pinned-staging, plus repro code
fa05bf1 verified
Raw History Blame Contribute Delete
4.2 kB
import argparse, time
import numpy as np
import nvtx
import ray
import torch
ROWS, WIDTH, BATCHES = 2048, 8192, 32
LOAD_MS, ITER = 40, 9
def load_batch(batch):
with nvtx.annotate("load_cpu"):
time.sleep(LOAD_MS / 1000)
return {"x": np.ones((ROWS, WIDTH), dtype=np.float32)}
import threading
class Predict:
def __init__(self, inline, pinned=False, overlap=False):
self.overlap = overlap
self.tls = threading.local()
torch.set_num_threads(1)
torch.cuda.set_device(0)
self.inline = inline
self.pinned = pinned
self.weight = torch.eye(WIDTH, device="cuda")
if pinned:
self.host = torch.empty((ROWS, WIDTH), dtype=torch.float32, pin_memory=True)
self.dev = torch.empty((ROWS, WIDTH), dtype=torch.float32, device="cuda")
_ = torch.ones((ROWS, WIDTH), device="cuda") @ self.weight
torch.cuda.synchronize()
def _buffers(self):
if not hasattr(self.tls, "stream"):
self.tls.stream = torch.cuda.Stream()
self.tls.host = torch.empty((ROWS, WIDTH), dtype=torch.float32, pin_memory=True)
self.tls.dev = torch.empty((ROWS, WIDTH), dtype=torch.float32, device="cuda")
return self.tls
def __call__(self, batch):
if self.inline:
batch = load_batch(batch)
if self.overlap:
b = self._buffers()
with torch.cuda.stream(b.stream):
with nvtx.annotate("stage_pinned"):
b.host.copy_(torch.from_numpy(batch["x"]))
with nvtx.annotate("H2D"):
b.dev.copy_(b.host, non_blocking=True)
x = b.dev
with torch.inference_mode(), nvtx.annotate("forward"):
for _ in range(ITER):
x = x @ self.weight
with nvtx.annotate("D2H"):
out = x[:, 0].to("cpu", non_blocking=False)
return {"out": out.numpy()}
if self.pinned:
with nvtx.annotate("stage_pinned"):
self.host.copy_(torch.from_numpy(batch["x"]))
with nvtx.annotate("H2D"):
self.dev.copy_(self.host, non_blocking=True)
x = self.dev
else:
with nvtx.annotate("H2D"):
x = torch.tensor(batch["x"], device="cuda")
with torch.inference_mode(), nvtx.annotate("forward"):
for _ in range(ITER):
x = x @ self.weight
with nvtx.annotate("D2H"):
return {"out": x[:, 0].cpu().numpy()}
def main():
p = argparse.ArgumentParser()
p.add_argument("--mode", choices=["inline", "split", "pinned", "overlap"], required=True)
p.add_argument("--profile", action="store_true")
args = p.parse_args()
nsight_env = {"nsight": {"t": "cuda,nvtx", "sample": "none",
"cpuctxsw": "none", "stop-on-exit": "true"}}
ray.init(address="local", num_cpus=8, num_gpus=1, include_dashboard=False)
ds = ray.data.range(ROWS * BATCHES, override_num_blocks=BATCHES)
if args.mode in ("split", "pinned", "overlap"):
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.mode == "inline", args.mode == "pinned", args.mode == "overlap"),
compute=ray.data.ActorPoolStrategy(size=1, max_tasks_in_flight_per_actor=4,
enable_true_multi_threading=(args.mode == "overlap")),
num_cpus=1, num_gpus=1, max_concurrency=2,
)
if args.profile:
gpu_kwargs["runtime_env"] = nsight_env
ds = ds.map_batches(Predict, **gpu_kwargs)
t0 = time.perf_counter()
r = ds.materialize()
print(f"MODE={args.mode} E2E={time.perf_counter()-t0:.3f}s")
for line in r.stats().splitlines():
if "Operator" in line or "Remote wall time" in line or "Ray Data throughput" in line:
print(" ", line.strip()[:110])
ray.shutdown()
if __name__ == "__main__":
main()