File size: 8,481 Bytes
7e7a152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""Full HVS control using model-independent common-v3 messages and observation contract."""
import os,sys,json,time,hashlib,argparse,fcntl
from pathlib import Path
R=Path(__file__).resolve().parents[2];sys.path.insert(0,str(R))
from evaluation.fourtask_common_v3.contract import PROTOCOL,messages,parse_action,digest
from evaluation.fourtask_common_v3.registry import MODELS,ready
from evaluation.fourtask_common_v3.new_actors import Actor
from run_sound_search import atomic,read,sha

def main():
 p=argparse.ArgumentParser();p.add_argument('--suite',choices=['static','sound'],required=True);p.add_argument('--gpu',type=int,required=True);p.add_argument('--model',choices=list(MODELS),required=True);a=p.parse_args()
 assert ready(a.model),'Checkpoint not complete or missing'
 profile=MODELS[a.model];track='vision_only' if a.suite=='static' or not profile['audio'] else ('vision_mono' if profile.get('native_audio_track')=='vision_mono' else 'vision_stereo')
 os.environ['CUDA_VISIBLE_DEVICES']=str(a.gpu);os.environ['TOKENIZERS_PARALLELISM']='false'
 import torch,cv2
 from PIL import Image
 from transformers import AutoProcessor,Qwen2_5_VLForConditionalGeneration
 def selection():
  # Identical custom HOS records without importing unused legacy Hstar/API clients.
  custom=read(R/'datasets/omini_360_benchmark_v0_1/public/test.jsonl')
  cmap={r['id']:r for r in read(R/'datasets/omini_360_benchmark_v0_1/private/episode_map.jsonl')}
  return [dict(r,collection='custom',scene=cmap[r['id']]['scene'],clip_id=cmap[r['id']]['clip_id'],task_id=cmap[r['id']]['task_id'],audio=None,native_root=str(R/'datasets/hstar_full_test_v1')) for r in custom if r['task_type']=='HOS']
 from hvs_core import perspective,in_interval
 from sound_search_core import score
 torch.set_num_threads(4);cv2.setNumThreads(1)
 out=R/'runs'/f'fourtask_common_v3_{a.model}_{a.suite}';out.mkdir(parents=True,exist_ok=True)
 lock=(out/'worker.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
 sd=R/'datasets/omini_sound_search_v1'
 eps=sorted(read(sd/'public/test.jsonl'),key=lambda e:(e['task'],e['id'])) if a.suite=='sound' else sorted([dict(e,audio=None) for e in selection() if e['collection']=='custom' and e['task_type']=='HOS'],key=lambda e:e['id'])
 assert len(eps)==(2868 if a.suite=='sound' else 4536)
 cfg=dict(model=a.model,protocol=PROTOCOL,track=track,profile=profile,actors_sha256=sha(R/'evaluation/fourtask_common_v3/new_actors.py'),composite=profile['kind']=='composite',protocol_sha256=digest(PROTOCOL),prompt_source_sha256=sha(R/'evaluation/fourtask_common_v3/contract.py'),runner_sha256=sha(Path(__file__)),selection_sha256=digest(eps),expected=len(eps),audio=track!='vision_only',audio_preprocessing='Stereo: shared canonical Omini32k perchannelRMS (ILD not preserved); mono: mean(L,R) then16k resample; full10s',native_preprocessing=profile.get('preprocessing'),architecture_note='Composite helper evidence explicitly appended; not identical end-to-end prompts' if profile['kind']=='composite' else 'Native serialization of identical semantic prompts')
 if 'parent' in profile:
  cp=Path(profile['parent']);cfg['checkpoint_sha256']=sha(cp/'final.safetensors');done=json.loads((cp/'complete.json').read_text());assert not done.get('checkpoint_sha256') or cfg['checkpoint_sha256']==done['checkpoint_sha256']
 if (out/'config.json').exists():
  previous=json.loads((out/'config.json').read_text())
  assert previous==cfg,'config drift'
 atomic(out/'config.json',cfg);atomic(out/'selection.json',eps)
 results={v['id']:v for f in (out/'episodes').glob('*/result.json') for v in [json.loads(f.read_text())]};assert set(results)<={e['id'] for e in eps}
 def summarize():
  groups={}
  for task,n in ({'HOS':4536} if a.suite=='static' else {'sound_class':716,'duration':1076,'order':1076}).items():
   rs=[x for x in results.values() if x['task']==task];groups[task]=dict(completed=len(rs),expected=n,success_rate=sum(x['success'] for x in rs)/len(rs) if rs else None,invalid_actions=sum(x['invalid_actions'] for x in rs))
  atomic(out/'summary.json',dict(status='complete' if len(results)==len(eps) else 'running',completed=len(results),expected=len(eps),groups=groups,updated_unix=time.time(),protocol='fourtask_common_v3',track=track))
 summarize()
 actor=Actor(a.model,out)
 atomic(out/'model_loaded.json',dict(model=a.model,track=track,profile=profile,trainable_parameters=sum(p.numel() for p in actor.model.parameters() if p.requires_grad)))
 labels={x['id']:x for x in read(sd/'private/labels.jsonl')} if a.suite=='sound' else {}
 def groundtruth(ep):
  if a.suite=='sound':l=labels[ep['id']];return Path(l['panorama']),l
  d=Path(ep['native_root'])/ep['task_id'];fs=list(d.glob('*.png'))+list(d.glob('*.jpg'));assert len(fs)==1,(d,len(fs));return fs[0],json.loads((d/'annotation.json').read_text())[0]
 def scored(pose,label,submitted):return bool(score(pose,label,submitted)['success']) if a.suite=='sound' else bool(submitted and in_interval(pose[0],label['yaw'],True,30) and in_interval(pose[1],label['pitch'],False,20))
 for ep in eps:
  if ep['id'] in results:continue
  torch.manual_seed(42+int(hashlib.sha256(ep['id'].encode()).hexdigest()[:8],16))
  source,label=groundtruth(ep);pano=cv2.imread(str(source));assert pano is not None
  audio=None;audio_source_hash=None;audio_effective_hash=None
  if track!='vision_only':
   import soundfile as sf,numpy as np,math
   from scipy.signal import resample_poly
   wave,sr=sf.read(label['audio_path'],dtype='float32',always_2d=True);assert wave.shape[1]==2 and len(wave)>=sr*10;wave=wave[:sr*10];audio_source_hash=sha(Path(label['audio_path']))
   if track=='vision_mono':
    divisor=math.gcd(sr,16000);audio=resample_poly(wave.mean(axis=1),16000//divisor,sr//divisor).astype(np.float32);assert audio.shape==(160000,)
   else:
    from omini.data.staqa_preprocessing import prepare_staqa_waveform
    audio=prepare_staqa_waveform(wave,sr).cpu().numpy();assert audio.shape==(2,320000)
   audio_effective_hash=hashlib.sha256(audio.tobytes()).hexdigest()
  pose=list(map(int,ep['initial_pose']));history=[];trace=[];submitted=False;folder=out/'episodes'/ep['id'].replace(':','_');folder.mkdir(parents=True,exist_ok=True)
  for step in range(10):
   pic=Image.fromarray(cv2.cvtColor(perspective(pano,*pose),cv2.COLOR_BGR2RGB));pics=[x[0] for x in history]+[pic];actions=[x[1] for x in history]
   ms=messages(ep['instruction'],pose,actions,step+1,track)
   raw=actor.generate(ms,pics,audio,ep['instruction'],pose);action=parse_action(raw,pose);before=pose[:]
   if action:
    op,dy,dp=action
    if op=='submit':submitted=True
    else:pose=[(pose[0]+dy)%360,max(-90,min(90,pose[1]+dp))]
    executed=f'<answer>{op}({dy},{dp})</answer>'
   else:executed='Invalid action; pose unchanged.'
   trace.append(dict(helper_evidence=getattr(actor,'last_helper',None),raw=raw,action=action,pose_before=before,pose_after=pose[:],input_audit=dict(episode_id=ep['id'],state_hash=digest([before,actions,step+1]),track=track,protocol_sha256=digest(PROTOCOL),semantic_prompt_sha256=digest(ms),rgb_sha256=[hashlib.sha256(im.tobytes()).hexdigest() for im in pics],audio_source_sha256=audio_source_hash,audio_effective_sha256=audio_effective_hash)))
   history=(history+[(pic,executed)])[-2:];atomic(folder/'progress.json',trace);print('STEP',ep['id'],step+1,action,flush=True)
   if submitted:break
  result=dict(id=ep['id'],task='HOS' if a.suite=='static' else ep['task'],success=scored(pose,label,submitted),steps=len(trace),invalid_actions=sum(t['action'] is None for t in trace),trace=trace)
  atomic(folder/'result.json',result);results[ep['id']]=result;summarize()
 assert set(results)=={e['id'] for e in eps}
 for ep in eps:
  v=results[ep['id']];pose=list(map(int,ep['initial_pose']));submitted=False;assert 1<=v['steps']<=10
  for t in v['trace']:
   assert t['pose_before']==pose and not submitted;ac=parse_action(t['raw'],pose);assert (list(ac) if ac else None)==t['action'] or ac==t['action']
   if ac:
    if ac[0]=='submit':submitted=True
    else:pose=[(pose[0]+ac[1])%360,max(-90,min(90,pose[1]+ac[2]))]
   assert pose==t['pose_after']
  _,label=groundtruth(ep);assert v['success']==scored(pose,label,submitted)
 atomic(out/'completion_audit.json',dict(expected=len(eps),exact_test_ids=True,action_replay_and_score_recomputation=True,input_prompt_hashes_logged=True,composite_helper_disclosed=profile['kind']=='composite',protocol_sha256=digest(PROTOCOL)))
 print('COMPLETE',flush=True)
if __name__=='__main__':main()