#!/usr/bin/env python3 """接管存活R0之后的GPU串行队列;只恢复已核实的时长异常,不覆盖活跃作业。""" import fcntl import json import os from pathlib import Path import subprocess import sys import time ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'scripts')) from download_assets import atomic def record(stage,**fields): value=dict(stage=stage,pid=os.getpid(),updated_at=time.time(),**fields) atomic(ROOT/'coordination/r0_queue.json',value) print(json.dumps(value,ensure_ascii=False),flush=True) def coverage(benchmark): expected={json.loads(line)['id'] for line in (ROOT/'manifests/eval_questions.jsonl').open() if json.loads(line)['benchmark']==benchmark} rows={} for path in (ROOT/'results/R0'/benchmark).glob('shard*/predictions.jsonl'): for line in path.open(): value=json.loads(line);rows[value['id']]=value answered={key for key,row in rows.items() if row['status']=='answered'} return dict(expected=expected,answered=answered,rows=rows) def run_gpu(benchmark): with (ROOT/'coordination/gpu.lock').open('w') as lock: fcntl.flock(lock,fcntl.LOCK_EX) while True: lines=subprocess.check_output(['nvidia-smi','--query-gpu=index,memory.used','--format=csv,noheader,nounits'],text=True).splitlines() busy=[s for s in lines if int(s.split(',')[0])<4 and int(s.split(',')[1])>256] if not busy:break record('waiting_authorized_GPU_free',memory=busy);time.sleep(30) lock.write(str(os.getpid()));lock.flush() command=[str(ROOT/'.venv/bin/torchrun'),'--standalone','--nproc_per_node=4',str(ROOT/'scripts/evaluate_r0.py'),'--benchmark',benchmark] with (ROOT/'logs'/('r0_queue_'+benchmark+'.log')).open('a') as logfile: process=subprocess.Popen(command,cwd=ROOT,stdout=logfile,stderr=subprocess.STDOUT, env=dict(os.environ,CUDA_VISIBLE_DEVICES='0,1,2,3',OMP_NUM_THREADS='4',TOKENIZERS_PARALLELISM='false',HF_HUB_OFFLINE='1')) record('R0_'+benchmark,torchrun_pid=process.pid,command=command) result=process.wait() if result:raise RuntimeError('R0 '+benchmark+'进程退出'+str(result)+',保留检查点/逐题输出供修复') def main(): # 等待现有持锁GPU作业完成;/proc核查由STATUS与主goal持续进行。 record('waiting_existing_R0_OVO') with (ROOT/'coordination/gpu.lock').open('r+') as lock:fcntl.flock(lock,fcntl.LOCK_EX) state=coverage('ovobench') if state['expected']!=state['answered']: missing=state['expected']-state['answered'];allowed=json.loads((ROOT/'configs/verified_media_end_queries.json').read_text()) allowed_videos={r['source_video'] for r in allowed.values()} for key in missing: value=state['rows'].get(key) if value is None or value.get('source_video') not in allowed_videos or 'Question timestamp exceeds video duration' not in value.get('failure_reason',''): raise RuntimeError('发现未解决的R0失败,不能自动无差别重试:'+key) run_gpu('ovobench') state=coverage('ovobench') if state['expected']!=state['answered']:raise RuntimeError('OVO恢复后覆盖仍未完成') record('R0_OVO_full_coverage',questions=len(state['answered'])) while True: expected=json.loads((ROOT/'manifests/eval_media_expected.json').read_text())['streaming'] inv=json.loads((ROOT/'provenance/eval_media_inventory.json').read_text()) missing=[key for key in expected if 'streaming/'+key not in inv or not (ROOT/inv['streaming/'+key]['path']).exists()] if not missing:break record('waiting_full_Streaming_media',remaining=len(missing));time.sleep(30) record('validating_full_Streaming_media') with (ROOT/'logs/validate_streaming_media.log').open('w') as log: subprocess.run([str(ROOT/'.venv/bin/python'),str(ROOT/'scripts/validate_eval_media.py'),'--benchmark','streamingbench'], cwd=ROOT,stdout=log,stderr=subprocess.STDOUT,check=True) validation=json.loads((ROOT/'provenance/media_validation_streamingbench.json').read_text()) if not validation['metadata_and_query_cutoff_passed']: raise RuntimeError('Streaming时间/媒体异常须先核查官方语义,不能自动删题或改时间') run_gpu('streamingbench') state=coverage('streamingbench') if state['expected']!=state['answered']:raise RuntimeError('Streaming有失败题待修复') record('R0_all_core_questions_answered',OVO=1468,Streaming=2500, remaining='R1_R2_training_evaluation_statistics_and_audits_not_complete') atomic(ROOT/'coordination/R0_full_question_coverage.json',dict(passed=True,OVO=1468,Streaming=2500, goal_complete=False,updated_at=time.time())) if __name__=='__main__': with (ROOT/'coordination/r0_queue.lock').open('w') as lock: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);lock.write(str(os.getpid()));lock.flush() try:main() except BaseException as exc: record('requires_infrastructure_repair',error=type(exc).__name__+':'+str(exc));raise