File size: 4,199 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
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()