#!/usr/bin/env python3 """32条真实训练QA上的因果MEMO证据与答案mask检查;不是正式R1训练或评测。""" import functools import hashlib import json from pathlib import Path import sys import subprocess ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT));sys.path.insert(0,str(ROOT/'repos/MEMO'));sys.path.insert(0,str(ROOT/'scripts')) from download_assets import atomic def main(): import torch from transformers import AutoProcessor from memo.eval.shared_components import RetrievalCLIPEncoder from memo.eval.frame_selection import uniform_sample from cgvm.reader_data import prepare from cgvm.media import frame_reference import torch.nn.functional as F rows=[json.loads(line) for line in (ROOT/'manifests/online_pilot20k.candidate.jsonl').open()] available={json.loads(p.read_text())['source_video'] for p in (ROOT/'data/frozen_causal_cache').glob('*.json')} rows=[q for q in rows if q['source_video'] in available] rows.sort(key=lambda q:hashlib.sha256(('17:input-probe:'+q['id']).encode()).hexdigest()) chosen=[];sources=set() for q in rows: if q['source_video'] in sources:continue chosen.append(q);sources.add(q['source_video']) if len(chosen)==32:break if len(chosen)<32:raise RuntimeError('真实、不同源视频的可用训练输入不足32') processor=AutoProcessor.from_pretrained(str(ROOT/'weights/Qwen3-VL-8B-Instruct'),min_pixels=256*28*28,max_pixels=1280*28*28) clip=RetrievalCLIPEncoder(str(ROOT/'weights/clip-vit-large-patch14'),device='cpu') packs=[];audits=[] commit=subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip() for q in chosen: token=hashlib.sha256(q['source_video'].encode()).hexdigest()[:24] cache=torch.load(ROOT/'data/frozen_causal_cache'/(token+'.pt'),map_location='cpu',weights_only=False) inputs=clip.processor(text=[q['question']],return_tensors='pt',padding=True,truncation=True,max_length=77) with torch.inference_mode(): encoded=clip.model.text_model(input_ids=inputs['input_ids'],attention_mask=inputs['attention_mask']) vec=F.normalize(clip.model.text_projection(encoded.pooler_output),dim=-1)[0] eligible=[c for c in cache['chunks'] if not c['terminal_flush'] and c['committed_at']<=q['query_time']] scores=[] for c in eligible: global_score=float((F.normalize(c['global_key'],dim=0)*vec).sum());entities=c['entity_keys'] local=float((F.normalize(entities,dim=-1)@vec).max().clamp(min=0.)) if entities.numel() else 0. scores.append((c,.6*global_score+.4*local)) scores.sort(key=lambda p:(-p[1],p[0]['chunk_id']));top=sorted(scores[:3],key=lambda p:p[0]['start_frame']) lookup={f['native_index']:f for f in cache['frames']} history=uniform_sample([lookup[index] for c,_ in top for index in c['frame_ids']],8) end=max((c['end_frame'] for c in eligible),default=-1) current=uniform_sample([f for f in cache['frames'] if f['native_index']>end and f['timestamp']<=q['query_time']],8) frames=[frame_reference(f,role) for role,source in [('history',history),('current',current)] for f in source] frames.sort(key=lambda f:(f['timestamp'],f['frame_id'])) pack=dict(id=q['id'],variant='R1',scope='input_contract_probe_original_MEMO_keys_not_formal_adapted_packs', source_video=q['source_video'],query_time=q['query_time'],frames=frames, prompt='Answer the question using the observed video frames.\nQuestion: '+q['question'],answer=q['answer'], ingested_frames=sum(f['timestamp']<=q['query_time'] for f in cache['frames']),writer_calls=0,writer_tokens=0, storage_bytes=(ROOT/'data/frozen_causal_cache'/(token+'.pt')).stat().st_size, commit=commit,model_revision='0c351dd01ed87e9c1b53cbc748cba10e6187ff3b') data,audit=prepare(pack,processor) assert (data.labels[0,:audit['prompt_masked_tokens']]==-100).all() assert torch.equal(data.labels[data.labels!=-100],data.input_ids[data.labels!=-100]) decoded=processor.tokenizer.decode(data.labels[data.labels!=-100].tolist(),skip_special_tokens=True) if decoded.strip()!=pack['answer'].strip():raise ValueError('监督文本与官方原答案不一致') audit['decoded_supervision_matches_original_answer']=True audit['actual_source_RGB_hash_revalidated']=True packs.append(pack);audits.append(audit) print(json.dumps(dict(id=q['id'],frames=audit['frames'],input_tokens=audit['input_tokens'],answer_tokens=audit['answer_tokens'])),flush=True) target=ROOT/'manifests/reader_input_contract32.jsonl' with target.open('w') as stream: for pack in packs:stream.write(json.dumps(pack,ensure_ascii=False)+'\n') atomic(ROOT/'provenance/reader_real32_input_mask_audit.json',dict(passed=True,scope='input_contract_not_formal_training', count=32,distinct_sources=len(sources),future_time_passed=True,frame_caps_passed=True, answer_only_mask_passed=True,LoRA_gradient_checkpoint_resume='pending_four_GPU_execution',inputs=audits)) if __name__=='__main__':main()