ray-data-gpu-idle-profiles / workload_staged.py
rich7421's picture
Ray Data GPU idle profiles: four modes + before/after pinned-staging, plus repro code
fa05bf1 verified
Raw History Blame Contribute Delete
8.59 kB
"""Compare inline, split, and pinned-staged Ray Data GPU inference.
Run against the patched Ray installation on a CUDA box:
python workload_staged.py --mode split
python workload_staged.py --mode staged
python workload_staged.py --mode staged --profile
E2E measures materialize(), including CPU loading, actor startup, and warmup.
Use unprofiled runs for timing and profiled runs for the CUDA/NVTX timeline.
"""
import argparse
import inspect
import time
from pathlib import Path
import numpy as np
import ray
ROWS = 2048
WIDTH = 8192
ITER = 9
GROUP = 4
BLOCK_ROWS = GROUP * ROWS
LOAD_MS = 40
def load_batch(batch):
"""Generate one feature row per input ID; preserve the input row count."""
n = len(batch["id"])
x = np.empty((n, WIDTH), dtype=np.float32)
for start in range(0, n, ROWS):
time.sleep(LOAD_MS / 1000)
x[start : start + ROWS].fill(1.0)
return {"x": x}
class Predict:
def __init__(self, mode):
import torch
self.torch = torch
self.mode = mode
self.device = torch.device("cuda", 0)
torch.set_num_threads(1)
torch.cuda.set_device(self.device)
torch.set_float32_matmul_precision("highest")
self.weight = torch.eye(WIDTH, dtype=torch.float32, device=self.device)
with torch.inference_mode(), torch.cuda.nvtx.range("warmup"):
warm = torch.ones(
(ROWS, WIDTH), dtype=torch.float32, device=self.device
)
warm = warm @ self.weight
torch.cuda.synchronize(self.device)
del warm
print(
f"Predict ready: mode={mode}, torch={torch.__version__}, "
f"gpu={torch.cuda.get_device_name(self.device)}, "
"dtype=float32, matmul_precision=highest",
flush=True,
)
def __call__(self, batch):
torch = self.torch
with torch.cuda.nvtx.range(f"Predict::{self.mode}"):
if self.mode == "inline":
with torch.cuda.nvtx.range("load_cpu"):
batch = load_batch(batch)
if self.mode == "staged":
x = batch["x"]
if (
not isinstance(x, torch.Tensor)
or x.device != self.device
or x.dtype != torch.float32
):
raise TypeError("staged mode must receive CUDA float32 tensors")
# PinnedPrefetch has already waited/recorded the current stream.
else:
with torch.cuda.nvtx.range("H2D"):
# Preserve the original split/inline baseline transfer.
x = torch.tensor(batch["x"], device=self.device)
if tuple(x.shape) != (ROWS, WIDTH):
raise ValueError(f"Expected {(ROWS, WIDTH)}, got {tuple(x.shape)}")
with torch.inference_mode(), torch.cuda.nvtx.range("forward"):
for _ in range(ITER):
x = x @ self.weight
with torch.cuda.nvtx.range("D2H"):
# Same synchronous column-only D2H as the original Predict.
out = x[:, 0].to("cpu", non_blocking=False)
return {"out": out.numpy()}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--mode", choices=("inline", "split", "staged"), default="staged"
)
parser.add_argument("--profile", action="store_true")
parser.add_argument(
"--blocks", type=int, default=32, help="Input blocks; each has GROUP=4 batches"
)
parser.add_argument("--num-cpus", type=int, default=8)
parser.add_argument("--cpu-workers", type=int, default=4)
args = parser.parse_args()
if args.blocks < 1 or args.cpu_workers < 1 or args.num_cpus < 2:
parser.error("--blocks/--cpu-workers must be positive; --num-cpus must be >= 2")
strategy_args = dict(
size=1,
max_tasks_in_flight_per_actor=4,
max_concurrent_calls_per_actor=1,
enable_true_multi_threading=False,
)
if args.mode == "staged":
parameters = inspect.signature(ray.data.ActorPoolStrategy).parameters
if "pinned_staging" not in parameters:
raise RuntimeError(
f"Imported Ray lacks the pinned-staging patch: {ray.__file__}"
)
from ray.data._internal.block_batching.pinned_staging import PinnedPrefetch
print(f"PinnedPrefetch: {inspect.getfile(PinnedPrefetch)}", flush=True)
strategy_args.update(pinned_staging=True, staging_collate_fn=None)
init_context = ray.init(
address="local",
num_cpus=args.num_cpus,
num_gpus=1,
include_dashboard=False,
)
try:
context = ray.data.DataContext.get_current()
# Four 64-MiB batches form one 256-MiB feature block. The default
# 128-MiB target would split it. Keep all four batches in the block
# presented to the GPU actor, so each task can prefetch N+1.
context.target_max_block_size = 512 * 1024 * 1024
context.enable_progress_bars = False
context.enable_operator_progress_bars = False
total_batches = args.blocks * GROUP
total_rows = total_batches * ROWS
ds = ray.data.range(total_rows, override_num_blocks=args.blocks)
if args.mode in ("split", "staged"):
ds = ds.map_batches(
load_batch,
batch_size=BLOCK_ROWS,
batch_format="numpy",
zero_copy_batch=True,
compute=ray.data.TaskPoolStrategy(size=args.cpu_workers),
num_cpus=1,
)
gpu_args = dict(
batch_size=ROWS,
batch_format="numpy",
# Required at the public API; the staging planner internally
# uses zero-copy CPU views and then makes owned staging copies.
zero_copy_batch=False,
fn_constructor_kwargs={"mode": args.mode},
compute=ray.data.ActorPoolStrategy(**strategy_args),
num_cpus=1,
num_gpus=1,
)
if args.profile:
gpu_args["runtime_env"] = {
"nsight": {
"t": "cuda,nvtx",
"sample": "none",
"cpuctxsw": "none",
"stop-on-exit": "true",
"force-overwrite": "true",
"o": f"workload_{args.mode}_%p",
}
}
ds = ds.map_batches(Predict, **gpu_args)
print(
f"Ray={ray.__version__} ({ray.__file__})\n"
f"MODE={args.mode} PROFILE={args.profile} BLOCKS={args.blocks} "
f"GROUP={GROUP} BATCHES={total_batches} "
f"SHAPE=({ROWS}, {WIDTH}) FP32 MATMULS={ITER}",
flush=True,
)
started = time.perf_counter()
result = ds.materialize()
elapsed = time.perf_counter() - started
print(
f"MODE={args.mode} E2E={elapsed:.3f}s "
f"BATCHES_PER_SEC={total_batches / elapsed:.3f}",
flush=True,
)
print(result.stats(), flush=True)
actual_rows = result.count()
if actual_rows != total_rows:
raise AssertionError(f"Expected {total_rows} rows, got {actual_rows}")
sample = result.take_batch(8, batch_format="numpy")["out"]
np.testing.assert_allclose(sample, 1.0, rtol=1e-5, atol=1e-5)
print(f"CHECK=PASS ROWS={actual_rows}", flush=True)
if args.profile:
report_dir = (
Path(init_context.address_info["session_dir"]) / "logs" / "nsight"
)
print(
f"NSIGHT_REPORTS={report_dir}/workload_{args.mode}_*.nsys-rep\n"
"Reports are finalized when the GPU actor exits.",
flush=True,
)
finally:
if args.profile:
# ray#60904 workaround: give nsys stop-on-exit time to export the
# report before teardown SIGKILLs the profiler's process group.
import glob as _glob, time as _time
nd = str(Path(init_context.address_info["session_dir"]) / "logs" / "nsight")
for _ in range(30):
_time.sleep(1)
r = _glob.glob(nd + "/*.nsys-rep")
if r and __import__("os").path.getsize(r[0]) > 0:
break
print("PROFILER FLUSH WAIT done, reps:", _glob.glob(nd + "/*.nsys-rep"), flush=True)
ray.shutdown()
if __name__ == "__main__":
main()