Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/gpu-head-to-head/blob/main/bench/shared-model-guard.py # gpu-head-to-head aien-dev/gpu-head-to-head Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `gpu-head-to-head / bench / shared-model-guard.py` 135 lines ยท 5971 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """External benchmark guard. Default checks only; --stop requires all idle/identity gates. 3 4 This is test equipment, not part of Aien architecture or model-serving dependencies. 5 Never invoke against the shared service during an active test. The enclosing controller must 6 record its intent/undo on BOARD before calling, retain the GPU lock, and restore the same setup. 7 """ 8 import argparse 9 import hashlib 10 import json 11 import os 12 from pathlib import Path 13 import select 14 import signal 15 import subprocess 16 import time 17 import urllib.request 18 19 20 class Refused(RuntimeError): 21 pass 22 23 24 def digest(path): 25 with open(path,'rb') as source: 26 return hashlib.file_digest(source,'sha256').hexdigest() 27 28 29 def process_identity(pid, snapshot, expected_sha256, proc_root=Path('/proc')): 30 root=proc_root/str(pid) 31 actual={'exe':os.readlink(root/'exe'),'cwd':os.readlink(root/'cwd'), 32 'argv':(root/'cmdline').read_bytes().decode().rstrip('\0').split('\0')} 33 for key in ['exe','cwd','argv']: 34 if actual[key]!=snapshot[key]: 35 raise Refused('shared model '+key+' changed') 36 if digest(root/'exe')!=expected_sha256 or digest(snapshot['exe'])!=expected_sha256: 37 raise Refused('shared model executable digest changed') 38 env={} 39 for entry in (root/'environ').read_bytes().split(b'\0'): 40 if b'=' in entry: 41 key,value=entry.split(b'=',1) 42 env[key.decode(errors='replace')]=value.decode(errors='replace') 43 for key,value in snapshot.get('env',{}).items(): 44 if env.get(key)!=value: 45 raise Refused('shared model required environment changed: '+key) 46 fields=(root/'stat').read_text().rsplit(') ',1)[1].split() 47 if fields[0] in ['Z','X']: 48 raise Refused('shared model already exited') 49 return {'pid':pid,'starttime_ticks':fields[19],'exe_sha256':expected_sha256, 50 'configuration':'matches saved executable/cwd/argv/required environment'} 51 52 53 def check_observation(pid, health, connections, gpu_pids, board_sha256, reviewed_board_sha256): 54 if board_sha256!=reviewed_board_sha256: 55 raise Refused('shared board changed; review current activity before retrying') 56 expected={'status':'ok','model':'qwen3.6-35b-a3b-fp8','engine':'omega-qwen36-batch', 57 'concurrency':8,'busy':False,'in_flight':0} 58 for key,value in expected.items(): 59 if type(health.get(key)) is not type(value) or health.get(key)!=value: 60 raise Refused('shared model is not the expected healthy idle configuration: '+key) 61 if connections.strip(): 62 raise Refused('shared model has established connections') 63 if type(gpu_pids) is not list or any(type(p) is not int or p<1 for p in gpu_pids) or gpu_pids!=[pid]: 64 raise Refused('GPU inventory is not solely the expected shared model') 65 66 67 def observe(pid, board, reviewed_sha256): 68 request=urllib.request.Request('http://127.0.0.1:18091/health',headers={'Connection':'close'}) 69 with urllib.request.urlopen(request,timeout=3) as response: 70 health=json.load(response) 71 connections=subprocess.check_output(['ss','-tnH','state','established', 72 '( sport = :18091 or dport = :18091 )'],text=True,timeout=5) 73 raw=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid', 74 '--format=csv,noheader,nounits'],text=True,timeout=5) 75 gpu_pids=[int(line.strip()) for line in raw.splitlines() if line.strip()] 76 check_observation(pid,health,connections,gpu_pids,digest(board),reviewed_sha256) 77 return health 78 79 80 def send_term(pidfd): 81 if select.select([pidfd],[],[],0)[0]: 82 raise Refused('bound process exited before stop; no signal sent') 83 signal.pidfd_send_signal(pidfd,signal.SIGTERM) 84 85 86 def guard(pid, snapshot, expected_sha256, board, reviewed_sha256, stop=False): 87 # Open first, then inspect. A numeric PID reused after this point cannot redirect this signal. 88 fd=os.pidfd_open(pid) 89 try: 90 identity=process_identity(pid,snapshot,expected_sha256) 91 samples=[] 92 for _ in range(3): 93 samples.append(observe(pid,board,reviewed_sha256)) 94 time.sleep(1) 95 if process_identity(pid,snapshot,expected_sha256)!=identity: 96 raise Refused('process identity changed during idle checks') 97 samples.append(observe(pid,board,reviewed_sha256)) 98 if select.select([fd],[],[],0)[0]: 99 raise Refused('bound process exited during checks') 100 result={'identity':identity,'idle_samples':len(samples),'stop_sent':False, 101 'reviewed_board_sha256':reviewed_sha256,'scope':'shared-model preflight only'} 102 if stop: 103 send_term(fd) 104 result['stop_sent']=True 105 return result 106 finally: 107 os.close(fd) 108 109 110 def main(): 111 parser=argparse.ArgumentParser(description=__doc__) 112 parser.add_argument('--pid',required=True,type=int) 113 parser.add_argument('--snapshot',required=True,type=Path) 114 parser.add_argument('--binary-sha256',required=True) 115 parser.add_argument('--board',type=Path,default=Path('/home/drakestapleton/handoffs/BOARD.md')) 116 parser.add_argument('--reviewed-board-sha256',required=True) 117 parser.add_argument('--stop',action='store_true') 118 parser.add_argument('--out',required=True,type=Path) 119 args=parser.parse_args() 120 # Refuse a reused receipt before touching a process. 121 with args.out.open('x') as output: 122 try: 123 result=guard(args.pid,json.loads(args.snapshot.read_text()),args.binary_sha256, 124 args.board,args.reviewed_board_sha256,args.stop) 125 status=0 126 except (Refused,OSError,ValueError,TypeError,KeyError,IndexError,AttributeError,subprocess.SubprocessError) as error: 127 result={'status':'REFUSED','reason':str(error),'stop_sent':False} 128 status=75 129 json.dump(result,output,indent=2) 130 output.write('\n') 131 return status 132 133 134 if __name__=='__main__': 135 raise SystemExit(main())