okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
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 ): 27for index ,value in enumerate (args ): 28key ,_ ,inline = value .partition ("=" ) 29if key in FORBIDDEN or key in DEVICE_ENV : 30raise ValueError (f"single-GPU experiment forbids { key } " ) 31if key in {"--gpu" ,"--device" ,"--hip-ordinal" }: 32ordinal = inline if "=" in value else (args [index + 1 ]if index + 1 < len (args )else "" ) 33if ordinal != "0" : 34raise ValueError (f" { key } must name filtered logical device 0" ) 35 36 37def validate_config (cfg ): 38if cfg .get ("backend" )!= "hip" or cfg .get ("gpu" )not in (0 ,"0" ): 39raise ValueError ('config requires backend="hip", gpu=0' ) 40if cfg .get ("hip_ordinal" ,0 )not in (0 ,"0" ): 41raise ValueError ("hip_ordinal must be 0" ) 42for key in ("gpus" ,"layer_split" ,"peer_device" ,"helper_device" ,"mtp_device" ,"split_skip_if_fits" ): 43if key in cfg : 44raise ValueError (f"single-GPU experiment forbids config key { key } " ) 45if cfg .get ("vision" ): 46raise ValueError ("this text benchmark config must omit the vision worker" ) 47validate_args (cfg .get ("args" , [])) 48for key ,value in cfg .get ("env" , {}).items (): 49if key in DEVICE_ENV and (key not in ISOLATION or str (value )!= ISOLATION [key ]): 50raise ValueError (f"config overrides GPU isolation: { key } " ) 51 52 53def probe (device_binary ): 54# Initialize HIP only after the final environment has been installed. 55hip = ctypes .CDLL ("/opt/rocm/lib/libamdhip64.so" ) 56hip .hipGetDeviceCount .argtypes = [ctypes .POINTER (ctypes .c_int )] 57hip .hipDeviceGetPCIBusId .argtypes = [ctypes .c_char_p ,ctypes .c_int ,ctypes .c_int ] 58count = ctypes .c_int () 59code = hip .hipGetDeviceCount (ctypes .byref (count )) 60if code or count .value != 1 : 61raise RuntimeError (f"HIP must see exactly one device; code= { code } , count= { count . value } " ) 62bus = ctypes .create_string_buffer (32 ) 63code = hip .hipDeviceGetPCIBusId (bus ,len (bus ),0 ) 64if code or bus .value .decode ().lower ()!= BDF : 65raise RuntimeError (f"unexpected logical device 0 BDF: { bus . value !r } , code= { code } " ) 66result = subprocess .run ([str (device_binary ),"--list-devices" ],check = True ,capture_output = True ,text = True ) 67if (re .findall (r"^device (\d+):" ,result .stdout ,re .M )!= ["0" ] 68or "gfx1201" not in result .stdout or "R9700" not in result .stdout 69or "cannot run" in result .stdout ): 70raise RuntimeError (f"strata-device rejected the target: { result . stdout } " ) 71return {"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 (): 77parser = argparse .ArgumentParser (description = __doc__ ) 78parser .add_argument ("--device-binary" ,type = Path ,default = ROOT / "build-r9700/strata-device" ) 79parser .add_argument ("--config" ,type = Path ,help = "validate this config; for serve it is required" ) 80parser .add_argument ("--record" ,type = Path ,required = True ,help = "new JSON record, never overwritten" ) 81parser .add_argument ("--cpu-nodes" ,help = "numactl CPU nodes; omit for unbound product baseline" ) 82parser .add_argument ("--preferred-node" ,type = int ,help = "NUMA preferred memory node (allows fallback)" ) 83parser .add_argument ("--port" ,type = int ,default = 8097 ) 84parser .add_argument ("action" ,choices = ["check" ,"run" ,"serve" ]) 85parser .add_argument ("command" ,nargs = argparse .REMAINDER ) 86args = parser .parse_args () 87command = args .command [1 :]if args .command [:1 ]== ["--" ]else args .command 88cfg = None 89if args .config : 90cfg = json .loads (args .config .read_text ()) 91validate_config (cfg ) 92if args .action == "serve" : 93if cfg is None or command : 94parser .error ("serve requires --config and takes no command" ) 95command = [sys .executable ,"-m" ,"serve.server" ,"--engine" ,"strata" , 96"--config" ,str (args .config .resolve ()),"--host" ,"127.0.0.1" ,"--port" ,str (args .port )] 97elif args .action == "run" and not command : 98parser .error ("run requires a command after --" ) 99elif args .action == "check" and command : 100parser .error ("check takes no command" ) 101validate_args (command ) 102# A config passed through `run` needs the same guard as `serve`. 103for i ,value in enumerate (command ): 104if value == "--config" or value .startswith ("--config=" ): 105path = value .split ("=" ,1 )[1 ]if "=" in value else command [i + 1 ] 106validate_config (json .loads (Path (path ).read_text ())) 107env = {k :v for k ,v in os .environ .items ()if k not in DEVICE_ENV } 108env .update (ISOLATION ) 109os .environ .clear () 110os .environ .update (env ) 111# This lock coordinates our experiments; it does not reserve the GPU against other users. 112lock = open (f"/tmp/strata-r9700- { os . getuid () } - { UUID } .lock" ,"a" ) 113fcntl .flock (lock ,fcntl .LOCK_EX | fcntl .LOCK_NB ) 114device = probe (args .device_binary .resolve ()) 115prefix = [] 116if args .cpu_nodes or args .preferred_node is not None : 117prefix = ["numactl" ] 118if args .cpu_nodes : 119prefix += ["--cpunodebind=" + args .cpu_nodes ] 120if args .preferred_node is not None : 121prefix += ["--preferred=" + str (args .preferred_node )] 122record = {"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 () 127if k .startswith (("STRATA_" ,"HIP_" ,"ROCR_" ,"ROCBLAS_" ,"HIPBLASLT_" ,"HSA_" ,"OMP_" )) 128or k in {"PATH" ,"LD_LIBRARY_PATH" }}, 129"device_binary_sha256" :hashlib .sha256 (args .device_binary .read_bytes ()).hexdigest ()} 130args .record .parent .mkdir (parents = True ,exist_ok = True ) 131with args .record .open ("x" )as stream : 132json .dump (record ,stream ,indent = 2 ) 133stream .write ("\n" ) 134json .dumps (device ),file = sys .stderr ,flush = True ) 135if args .action != "check" : 136os .chdir (ROOT ) 137os .set_inheritable (lock .fileno (),True ) 138os .execvpe ((prefix + command )[0 ],prefix + command ,env ) 139 140 141if __name__ == "__main__" : 142main ()