okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
7.1 KiB142 linesraw
1#!/usr/bin/env python3
2"""Run R9700 experiments with one UUID, verified HIP BDF and recorded configuration."""
3import argparse
4import ctypes
5from datetime import datetime, timezone
6import fcntl
7import hashlib
8import json
9import os
10from pathlib import Path
11import re
12import subprocess
13import sys
14
15ROOT = Path(__file__).resolve().parents[3]
16UUID = "GPU-1d9ca7a7f0a06a6d"
17BDF = "0000:63:00.0"
18ISOLATION = {"ROCR_VISIBLE_DEVICES": UUID, "HIP_VISIBLE_DEVICES": "0"}
19DEVICE_ENV = {"CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER", "GPU_DEVICE_ORDINAL",
20              "ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "HSA_OVERRIDE_GFX_VERSION"}
21FORBIDDEN = {"--gpus", "--layer-split", "--peer-device", "--helper-device", "--mtp-device",
22             "--split-skip-if-fits", "--expert-cache-device1", "--expert-cache-device2",
23             "--expert-cache-device3", "--expert-cache-remote-placement", "--remote-expert-opt"}
24
25
26def validate_args(args):
27    for index, value in enumerate(args):
28        key, _, inline = value.partition("=")
29        if key in FORBIDDEN or key in DEVICE_ENV:
30            raise ValueError(f"single-GPU experiment forbids {key}")
31        if key in {"--gpu", "--device", "--hip-ordinal"}:
32            ordinal = inline if "=" in value else (args[index + 1] if index + 1 < len(args) else "")
33            if ordinal != "0":
34                raise ValueError(f"{key} must name filtered logical device 0")
35
36
37def validate_config(cfg):
38    if cfg.get("backend") != "hip" or cfg.get("gpu") not in (0, "0"):
39        raise ValueError('config requires backend="hip", gpu=0')
40    if cfg.get("hip_ordinal", 0) not in (0, "0"):
41        raise ValueError("hip_ordinal must be 0")
42    for key in ("gpus", "layer_split", "peer_device", "helper_device", "mtp_device", "split_skip_if_fits"):
43        if key in cfg:
44            raise ValueError(f"single-GPU experiment forbids config key {key}")
45    if cfg.get("vision"):
46        raise ValueError("this text benchmark config must omit the vision worker")
47    validate_args(cfg.get("args", []))
48    for key, value in cfg.get("env", {}).items():
49        if key in DEVICE_ENV and (key not in ISOLATION or str(value) != ISOLATION[key]):
50            raise ValueError(f"config overrides GPU isolation: {key}")
51
52
53def probe(device_binary):
54    # Initialize HIP only after the final environment has been installed.
55    hip = ctypes.CDLL("/opt/rocm/lib/libamdhip64.so")
56    hip.hipGetDeviceCount.argtypes = [ctypes.POINTER(ctypes.c_int)]
57    hip.hipDeviceGetPCIBusId.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
58    count = ctypes.c_int()
59    code = hip.hipGetDeviceCount(ctypes.byref(count))
60    if code or count.value != 1:
61        raise RuntimeError(f"HIP must see exactly one device; code={code}, count={count.value}")
62    bus = ctypes.create_string_buffer(32)
63    code = hip.hipDeviceGetPCIBusId(bus, len(bus), 0)
64    if code or bus.value.decode().lower() != BDF:
65        raise RuntimeError(f"unexpected logical device 0 BDF: {bus.value!r}, code={code}")
66    result = subprocess.run([str(device_binary), "--list-devices"], check=True, capture_output=True, text=True)
67    if (re.findall(r"^device (\d+):", result.stdout, re.M) != ["0"]
68            or "gfx1201" not in result.stdout or "R9700" not in result.stdout
69            or "cannot run" in result.stdout):
70        raise RuntimeError(f"strata-device rejected the target: {result.stdout}")
71    return {"uuid": UUID, "bdf": BDF, "hip_device_count": count.value,
72            "strata_device": result.stdout,
73            "numa_node": (Path("/sys/bus/pci/devices") / BDF / "numa_node").read_text().strip()}
74
75
76def main():
77    parser = argparse.ArgumentParser(description=__doc__)
78    parser.add_argument("--device-binary", type=Path, default=ROOT / "build-r9700/strata-device")
79    parser.add_argument("--config", type=Path, help="validate this config; for serve it is required")
80    parser.add_argument("--record", type=Path, required=True, help="new JSON record, never overwritten")
81    parser.add_argument("--cpu-nodes", help="numactl CPU nodes; omit for unbound product baseline")
82    parser.add_argument("--preferred-node", type=int, help="NUMA preferred memory node (allows fallback)")
83    parser.add_argument("--port", type=int, default=8097)
84    parser.add_argument("action", choices=["check", "run", "serve"])
85    parser.add_argument("command", nargs=argparse.REMAINDER)
86    args = parser.parse_args()
87    command = args.command[1:] if args.command[:1] == ["--"] else args.command
88    cfg = None
89    if args.config:
90        cfg = json.loads(args.config.read_text())
91        validate_config(cfg)
92    if args.action == "serve":
93        if cfg is None or command:
94            parser.error("serve requires --config and takes no command")
95        command = [sys.executable, "-m", "serve.server", "--engine", "strata",
96                   "--config", str(args.config.resolve()), "--host", "127.0.0.1", "--port", str(args.port)]
97    elif args.action == "run" and not command:
98        parser.error("run requires a command after --")
99    elif args.action == "check" and command:
100        parser.error("check takes no command")
101    validate_args(command)
102    # A config passed through `run` needs the same guard as `serve`.
103    for i, value in enumerate(command):
104        if value == "--config" or value.startswith("--config="):
105            path = value.split("=", 1)[1] if "=" in value else command[i + 1]
106            validate_config(json.loads(Path(path).read_text()))
107    env = {k: v for k, v in os.environ.items() if k not in DEVICE_ENV}
108    env.update(ISOLATION)
109    os.environ.clear()
110    os.environ.update(env)
111    # This lock coordinates our experiments; it does not reserve the GPU against other users.
112    lock = open(f"/tmp/strata-r9700-{os.getuid()}-{UUID}.lock", "a")
113    fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
114    device = probe(args.device_binary.resolve())
115    prefix = []
116    if args.cpu_nodes or args.preferred_node is not None:
117        prefix = ["numactl"]
118        if args.cpu_nodes:
119            prefix += ["--cpunodebind=" + args.cpu_nodes]
120        if args.preferred_node is not None:
121            prefix += ["--preferred=" + str(args.preferred_node)]
122    record = {"utc": datetime.now(timezone.utc).isoformat(), "device": device,
123              "command": prefix + command, "cwd": str(ROOT), "config": cfg,
124              "git_head": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),
125              "git_status": subprocess.check_output(["git", "status", "--short"], cwd=ROOT, text=True),
126              "environment": {k: v for k, v in env.items()
127                              if k.startswith(("STRATA_", "HIP_", "ROCR_", "ROCBLAS_", "HIPBLASLT_", "HSA_", "OMP_"))
128                              or k in {"PATH", "LD_LIBRARY_PATH"}},
129              "device_binary_sha256": hashlib.sha256(args.device_binary.read_bytes()).hexdigest()}
130    args.record.parent.mkdir(parents=True, exist_ok=True)
131    with args.record.open("x") as stream:
132        json.dump(record, stream, indent=2)
133        stream.write("\n")
134    print(json.dumps(device), file=sys.stderr, flush=True)
135    if args.action != "check":
136        os.chdir(ROOT)
137        os.set_inheritable(lock.fileno(), True)
138        os.execvpe((prefix + command)[0], prefix + command, env)
139
140
141if __name__ == "__main__":
142    main()