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-window.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-window.py` 232 lines ยท 12770 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """External test controller. Requires reviewed BOARD and pinned inputs; never swaps models.""" 3 import argparse 4 import contextlib 5 import datetime 6 import fcntl 7 import importlib.util 8 import json 9 import os 10 from pathlib import Path 11 import select 12 import signal 13 import subprocess 14 import time 15 import urllib.request 16 17 HERE=Path(__file__).resolve().parent 18 spec=importlib.util.spec_from_file_location('shared_guard',HERE/'shared-model-guard.py') 19 guard=importlib.util.module_from_spec(spec); spec.loader.exec_module(guard) 20 21 22 def execute(ops): 23 """Keep the lock through all recovery. Refusal before stop never launches restoration.""" 24 result={'test_exit':None,'restored':False,'status':'INCOMPLETE'} 25 with ops.lock(): 26 ops.preflight() 27 stop_attempted=False 28 try: 29 stop_attempted=True 30 ops.stop() 31 ops.wait_original_exit() 32 ops.before_test() 33 result['test_exit']=ops.run() 34 except Exception as error: 35 result['error']=str(error) 36 finally: 37 if stop_attempted: 38 try: 39 ops.recovery_gate() 40 ops.restore() 41 ops.verify_restored() 42 result['restored']=True 43 except Exception as error: 44 result['recovery_error']=str(error) 45 if result['test_exit']==0 and result['restored'] and 'error' not in result: 46 result['status']='PASS' 47 return result 48 49 50 class Live: 51 def __init__(self,args): 52 self.a=args; self.original_fd=None; self.child=None; self.interrupted=False 53 self.baseline=None; self.snapshot=json.loads(args.snapshot.read_text()) 54 self.pins=json.loads(args.pins.read_text()); self.original=None 55 def event(self,kind,**fields): 56 with (self.a.out/'events.jsonl').open('a') as out: 57 out.write(json.dumps({'at':datetime.datetime.now(datetime.timezone.utc).isoformat(), 58 'event':kind,**fields})+'\n') 59 @contextlib.contextmanager 60 def lock(self): 61 fd=os.open('/tmp/aien-gb10.lock',os.O_WRONLY|os.O_CREAT,0o600) 62 try: 63 fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB) 64 # Runner contract requires descriptor 9. Never overwrite an unknown descriptor. 65 if fd!=9: 66 try: os.fstat(9) 67 except OSError: pass 68 else: raise guard.Refused('descriptor 9 already in use') 69 os.dup2(fd,9); os.close(fd); fd=9 70 self.event('lock_acquired') 71 yield 72 finally: 73 if self.original_fd is not None: os.close(self.original_fd) 74 os.close(fd) 75 def validate_pins(self,restoration=False): 76 required=[self.a.snapshot,self.a.launcher,Path(self.snapshot['exe']), 77 HERE/'shared-model-guard.py',Path(__file__).resolve()] 78 if not restoration: 79 required += [self.a.repo/p for p in ['bench/run_arm.sh','bench/session-lifecycle.sh', 80 'bench/bench.py','bench/quiet.py','bench/coremon.py','prompts/decode.jsonl','prompts/prefill.jsonl']] 81 conf=self.a.repo/'bench/arms.conf' 82 if not restoration and conf.exists(): required.append(conf) 83 for path in required: 84 if str(path.resolve()) not in self.pins: raise guard.Refused('missing pin: '+str(path)) 85 checks={str(p.resolve()):self.pins[str(p.resolve())] for p in required} if restoration else self.pins 86 for name,expected in checks.items(): 87 if guard.digest(name)!=expected: raise guard.Refused('pinned file changed: '+name) 88 def validate_restore_contract(self): 89 expected=['./aien-serve-http','--engine','omega','--model-dir', 90 str(Path.home()/'models/qwen3.6-35b-a3b-fp8-`95a723d0`'),'--port','18091', 91 '--max-context','49152','--max-tokens-cap','16384','--thinking','off','--batch-slots','8'] 92 if self.snapshot['argv']!=expected: 93 raise guard.Refused('snapshot differs from supported same-model restoration contract') 94 cwd=Path(self.snapshot['cwd']) 95 if cwd.parent!=self.a.launcher.parent or str(cwd/'aien-serve-http')!=self.snapshot['exe']: 96 raise guard.Refused('snapshot executable/working directory does not match launcher layout') 97 expected_env={'AIEN_Q36_STROKE':'1','AIEN_SERVE_GPU_LOCK':'/tmp/aien-serve-18091.lock'} 98 if self.snapshot['env']!=expected_env: 99 raise guard.Refused('snapshot environment differs from supported restoration contract') 100 def gpu_empty(self): 101 rows=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid', 102 '--format=csv,noheader,nounits'],text=True,timeout=5) 103 if rows.strip(): raise guard.Refused('GPU processes remain; refusing overlapping model launch') 104 def memory(self): 105 for line in Path('/proc/meminfo').read_text().splitlines(): 106 if line.startswith('MemAvailable:'): 107 parts=line.split() 108 if len(parts)==3 and parts[2]=='kB' and parts[1].isdigit() and int(parts[1])>0: 109 return int(parts[1]) 110 raise guard.Refused('valid MemAvailable unavailable') 111 def preflight(self): 112 self.validate_pins() 113 self.validate_restore_contract() 114 self.sha=self.pins[str(Path(self.snapshot['exe']).resolve())] 115 self.original=int(self.a.pidfile.read_text().strip()) 116 self.original_fd=os.pidfd_open(self.original) 117 self.identity=guard.process_identity(self.original,self.snapshot,self.sha) 118 # Review is a coordinator action, not something inferred from file age or locks. 119 old=self.a.board.read_bytes() 120 import hashlib 121 if hashlib.sha256(old).hexdigest()!=self.a.reviewed_board_sha256: 122 raise guard.Refused('BOARD changed since coordinator review') 123 entry=('\n'+datetime.datetime.now(datetime.timezone.utc).isoformat()+ 124 ' CodexStackCompare EXCLUSIVE35B '+self.a.arm+' '+self.a.round+ 125 ': Drake said "you may stop the model" and "Only you can\'t stop it if it\'s doing a test." '+ 126 'Coordinator reviewed BOARD; idle/identity checks required before stop. '+ 127 'One session capped at60min plus restoration. UNDO: same saved executable/model/flags via '+ 128 str(self.a.launcher)+' with explicit saved batch settings. Evidence '+str(self.a.out)+'\n').encode() 129 with self.a.board.open('ab') as out: out.write(entry) 130 reviewed=hashlib.sha256(old+entry).hexdigest() 131 observation=guard.guard(self.original,self.snapshot,self.sha,self.a.board,reviewed,False) 132 if observation['identity']!=self.identity: raise guard.Refused('original process identity changed') 133 self.reviewed=reviewed 134 self.event('preflight',observation=observation) 135 def stop(self): 136 if self.interrupted: raise guard.Refused('interrupted before stopping shared model') 137 guard.observe(self.original,self.a.board,self.reviewed) 138 guard.send_term(self.original_fd) 139 self.event('shared_stop_sent') 140 def wait_original_exit(self): 141 if not select.select([self.original_fd],[],[],60)[0]: 142 raise guard.Refused('original model did not exit; no force kill') 143 self.event('shared_exited') 144 def before_test(self): 145 self.gpu_empty(); self.baseline=self.memory(); self.validate_pins() 146 self.event('baseline',memavailable_kib=self.baseline) 147 def run(self): 148 if self.interrupted: raise guard.Refused('interrupted before test launch') 149 env=os.environ.copy() 150 env.update(H2H_GPU_LOCK_FD='9',H2H_REPO=str(self.a.repo),H2H_RESULTS=str(self.a.out/'results')) 151 with (self.a.out/'runner.log').open('xb') as log: 152 self.child=subprocess.Popen(['bash',str(self.a.repo/'bench/run_arm.sh'),self.a.arm,self.a.round], 153 env=env,stdout=log,stderr=subprocess.STDOUT,pass_fds=(9,)) 154 # The inner runner owns descendants, containers and its 60-minute watchdog. 155 # Its pre-lock quiet wait can be longer; bound the complete invocation as well. 156 deadline=time.monotonic()+4500 157 while self.child.poll() is None: 158 if self.interrupted or time.monotonic()>deadline: 159 self.child.terminate() 160 try: self.child.wait(timeout=60) 161 except subprocess.TimeoutExpired: 162 raise guard.Refused('runner did not finish cleanup; retain its inherited lock, no restore') 163 raise guard.Refused('test interrupted or outer deadline reached') 164 time.sleep(0.25) 165 self.event('test_exit',code=self.child.returncode) 166 done=self.a.out/'results/logs'/('%s-%s' % (self.a.arm,self.a.round))/'DONE' 167 if self.child.returncode==0 and not done.is_file(): 168 raise guard.Refused('runner returned success without a completed-session marker') 169 return self.child.returncode 170 def recovery_gate(self): 171 if self.child is not None and self.child.poll() is None: 172 raise guard.Refused('runner still active; restoration refused') 173 if not select.select([self.original_fd],[],[],0)[0]: 174 raise guard.Refused('original still present; duplicate restoration refused') 175 self.gpu_empty() 176 after=self.memory() 177 self.event('unloaded',memavailable_kib=after,baseline_kib=self.baseline) 178 if self.baseline is not None and self.baseline-after>2*1024*1024: 179 raise guard.Refused('memory has not recovered within 2 GiB; restoration refused') 180 def restore(self): 181 # An unrelated benchmark-input change must not prevent restoring the saved service. 182 self.validate_pins(restoration=True) 183 env=os.environ.copy() 184 env.update(self.snapshot['env']) 185 env.update(Q36_BATCH_BIN=Path(self.snapshot['cwd']).name,Q36_BATCH_SLOTS='8',Q36_MAX_CONTEXT='49152') 186 with (self.a.out/'restore.log').open('xb') as log: 187 # close_fds prevents the restored service from retaining the global GPU lock. 188 subprocess.run([str(self.a.launcher)],env=env,stdout=log,stderr=subprocess.STDOUT, 189 close_fds=True,timeout=30,check=True) 190 self.event('restore_launched') 191 def verify_restored(self): 192 deadline=time.monotonic()+180 193 last='no health response' 194 while time.monotonic()