cmvr-visual/inference/admin/verify_gpu_priority.py

155 lines
8.0 KiB
Python
Raw Normal View History

"""One-shot administrator integration check; never stop an existing workload."""
import json, pathlib, sqlite3, struct, subprocess, time, urllib.request
ROOT=pathlib.Path('/root/llmuser-gpu-priority-20261110')
PROJECT=pathlib.Path('/data/llmusers/llmuser/workspace/projects/llm-services')
POLICY=pathlib.Path('/var/lib/llmuser-gpu-policy/status.json')
D='/usr/bin/docker'
UUID='GPU-6f547b70-7a25-70cb-e134-888402be61e2'
KEY=(PROJECT/'config/api_key').read_text().strip()
report={'started_at':time.time(),'checks':{},'events':[],'passed':False}
probes={}
job_id=None
def record(phase, **extra):
item={'phase':phase,'time':time.time(),**extra}
report['events'].append(item)
(ROOT/'integration-progress.json').write_text(json.dumps(report,indent=2))
print(json.dumps(item),flush=True)
def api(path, payload=None):
headers={'Authorization':'Bearer '+KEY}
data=None
if payload is not None:
data=json.dumps(payload).encode()
headers['Content-Type']='application/json'
return json.load(urllib.request.urlopen(urllib.request.Request('http://127.0.0.1:18190'+path,data=data,headers=headers),timeout=10))
def status():
s=json.loads(POLICY.read_text())
if s['error'] is not None or time.time()-s['generated_at']>5:
raise RuntimeError('GPU monitor unavailable')
return s
def gpu2():
return next(g for g in status()['gpus'] if g['uuid']==UUID)
def wait_for(predicate, seconds, description):
deadline=time.monotonic()+seconds
while time.monotonic()<deadline:
result=predicate()
if result:return result
time.sleep(.25)
raise RuntimeError('Timed out: '+description)
def inspect(name):
return json.loads(subprocess.check_output([D,'inspect',name],text=True))[0]
def start_probe(name):
assert subprocess.run([D,'inspect',name],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode!=0
code="import torch,time; x=torch.ones((256,256),device='cuda'); print('GPU_PROBE_READY',flush=True); time.sleep(120)"
# A separate admin-launched container is external regardless of its UID.
# Use the volume owner UID to respect the private workspace's mode 0700.
cmd=[D,'run','-d','--name',name,'--gpus','device='+UUID,'--env','NVIDIA_DRIVER_CAPABILITIES=compute,utility','--env','CUDA_VISIBLE_DEVICES='+UUID,'--network','none','--read-only','--user','1013:1014','--cap-drop','ALL','--security-opt','no-new-privileges:true','--cpus','2','--memory','2g','--memory-swap','2g','--pids-limit','128','--mount','type=bind,src=/data/llmusers/llmuser/workspace,dst=/workspace,readonly','--entrypoint','/workspace/envs/vllm/bin/python','llmuser-runtime:multimodal-final-20261110','-c',code]
cmd[2:2]=['--tmpfs','/run/probe:rw,nosuid,nodev,size=128m,mode=1777',
'--env','TMPDIR=/run/probe','--env','XDG_CACHE_HOME=/run/probe/cache',
'--env','CUDA_CACHE_PATH=/run/probe/cuda']
try:
cid=subprocess.check_output(cmd,text=True).strip()
except subprocess.CalledProcessError:
# Docker may have created the named container before runtime failure.
probes[name]=inspect(name)['Id']
raise
probes[name]=cid
def ready():
x=inspect(name)
if not x['State']['Running']:
raise RuntimeError('Probe exited: '+subprocess.check_output([D,'logs',name],text=True))
logs=subprocess.check_output([D,'logs',name],text=True,stderr=subprocess.STDOUT)
return 'GPU_PROBE_READY' in logs and bool(gpu2()['external_pids'])
wait_for(ready,50,'administrator probe GPU allocation')
record('probe_started',name=name,container_id=cid)
return cid
def stop_probe(name):
cid=probes.get(name)
if cid is None:return
x=inspect(name)
assert x['Id']==cid
if x['State']['Running']:
subprocess.run([D,'stop','--time','5',name],check=True,stdout=subprocess.DEVNULL)
report.setdefault('probe_logs',{})[name]=subprocess.check_output([D,'logs',name],text=True,stderr=subprocess.STDOUT)
subprocess.run([D,'rm',name],check=True,stdout=subprocess.DEVNULL)
del probes[name]
record('probe_released',name=name)
try:
assert api('/health')['running_jobs']==0
connection=sqlite3.connect(PROJECT/'state/jobs.sqlite3')
assert connection.execute("SELECT COUNT(*) FROM jobs WHERE state IN ('queued','running')").fetchone()[0]==0
connection.close()
s=status()
assert len(s['gpus'])==4 and not gpu2()['external_pids'] and not gpu2()['own_pids']
report['initial_gpu_status']=s
record('starting')
start_probe('llmuser-priority-validation-wait')
assert all(g['external_pids'] for g in status()['gpus'])
j=api('/jobs',{'task_type':'image.generate','input':{'prompt':'A red ceramic teapot on a light wooden table, soft natural light, realistic product photograph, no text'},'parameters':{'width':512,'height':512,'num_inference_steps':10,'seed':42},'timeout_seconds':300})
job_id=j['id'];report['job_id']=job_id
record('submitted_all_gpus_busy',job_id=job_id)
time.sleep(5)
j=api('/jobs/'+job_id)
assert j['state']=='queued' and j['attempt_count']==0 and j['started_at'] is None
report['checks']['busy_job_stays_queued_without_timeout']=True
report['queued_snapshot']=j
record('verified_waiting',job_id=job_id)
stop_probe('llmuser-priority-validation-wait')
def own_running():
j=api('/jobs/'+job_id)
if j['state'] in ('failed','cancelled','timed_out'):raise RuntimeError(json.dumps(j))
return j if j['state']=='running' and gpu2()['own_pids'] else None
first=wait_for(own_running,150,'first attempt begins on idle GPU')
assert first['gpu_uuid']==UUID and first['attempt_count']==1
report['first_attempt']=first;record('first_attempt_running',job_id=job_id)
start_probe('llmuser-priority-validation-preempt')
def yielded():
j=api('/jobs/'+job_id)
if j['state'] in ('failed','cancelled','timed_out','succeeded'):raise RuntimeError('Expected requeue: '+json.dumps(j))
return j if j['state']=='queued' and j['preemptions']>=1 and not any(g['own_pids'] for g in status()['gpus']) else None
interrupted=wait_for(yielded,30,'llmuser process exit and requeue')
report['checks']['foreign_appearance_preempts_and_requeues']=True
report['checks']['all_llmuser_gpu_processes_released']=True
report['preempted_snapshot']=interrupted
assert inspect('llmuser-priority-validation-preempt')['State']['Running']
report['checks']['foreign_probe_not_terminated']=True
time.sleep(3)
assert api('/jobs/'+job_id)['state']=='queued'
record('verified_preemption_and_foreign_preserved',job_id=job_id)
stop_probe('llmuser-priority-validation-preempt')
def completed():
j=api('/jobs/'+job_id)
if j['state'] in ('failed','cancelled','timed_out'):raise RuntimeError(json.dumps(j))
return j if j['state']=='succeeded' else None
final=wait_for(completed,420,'same job restarts and produces image')
assert final['id']==job_id and final['attempt_count']>=2 and final['preemptions']>=1
assert final['gpu_uuid']==UUID
path=pathlib.Path('/data/llmusers/llmuser/workspace')/pathlib.Path(final['result']['outputs'][0]['path']).relative_to('/workspace')
raw=path.read_bytes();assert raw[:8]==b'\x89PNG\r\n\x1a\n' and struct.unpack('>II',raw[16:24])==(512,512)
assert ('attempt-%04d'%final['attempt_count']) in str(path)
report['checks']['same_job_resumes_from_start_on_available_gpu']=True
report['checks']['retry_has_isolated_valid_image_output']=True
report['final_job']=final
report['passed']=True
record('completed',job_id=job_id,attempt_count=final['attempt_count'],preemptions=final['preemptions'])
except Exception as exc:
report['error']=type(exc).__name__+': '+str(exc)
record('failed',error=report['error'])
if job_id:
try:api('/jobs/'+job_id+'/cancel',{})
except Exception:pass
finally:
for name in list(probes):
try:stop_probe(name)
except Exception as exc:report.setdefault('cleanup_errors',[]).append(str(exc))
report['finished_at']=time.time()
(ROOT/'priority-integration.json').write_text(json.dumps(report,indent=2))