File size: 8,586 Bytes
fa05bf1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | """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()
|