XiangnanW's picture
Upload CGVM R2.6 step-000600 checkpoint, R2.6 source bundle (cgvm-r26-src-v1.tar.gz), and 4-round audit report
4ad9219 verified
Raw History Blame Contribute Delete
10.3 kB
#!/usr/bin/env python3
"""完整官方题单的R0四GPU视频分片;原MEMO计算路径加设备/证据观测适配。"""
import argparse
import hashlib
import json
import logging
import os
from pathlib import Path
import random
import subprocess
import sys
import time
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
from cgvm.benchmark_data import groups, diagnostic_scores
class AuditObserver:
def __init__(self, device, output):
self.device=device;self.output=output
self.query_started=0;self.request={};self.refs={};self.closures=[]
def start_video(self,path,video):
self.path=path;self.refs={};self.closures=[];self.ingested=0
self.sampling={native:float(frame.timestamp) for frame,native in zip(video.frames,video.native_indices)}
self.decode_seconds=time.perf_counter()-self.video_started
self.decoded_rgb_bytes=sum(frame.image.nbytes for frame in video.frames)
def register_frame(self,image,frame,native_index):
self.ingested+=1;self.latest_time=float(frame.timestamp)
self.refs[id(image)] = dict(frame_id=str(native_index),timestamp=float(frame.timestamp),
source_video=self.source_video,rgb_sha256=hashlib.sha256(frame.image.tobytes()).hexdigest(),
width=image.width,height=image.height)
def closed_chunk(self,chunk,pending,segmenter):
support=[self.sampling[frame.frame_idx] for frame in chunk.frames]
assert max(support)<=self.latest_time+1e-6
self.closures.append(dict(chunk_id=chunk.chunk_id,committed_at=self.latest_time,
start=min(support),end=max(support),frame_ids=[f.frame_idx for f in chunk.frames]))
def before_reader(self,q,frames,text,hits,history,current):
refs=[self.refs[id(frame)] for frame in frames]
assert max(r['timestamp'] for r in refs)<=q['timestamp']+1e-6
assert len(frames)<=16
assert min(len(history),8)+min(len(current),8)==len(frames)
self.request=dict(source_video=self.source_video,query_time=q['timestamp'],
max_support_time=max(r['timestamp'] for r in refs),retrieved_frame_ids=refs,
ingested_frames=self.ingested,history_frames=min(len(history),8),current_frames=min(len(current),8),
pixels=sum(f.width*f.height for f in frames),writer_calls=0,writer_tokens=0,
retrieval_seconds=time.perf_counter()-self.query_started)
return frames,text
def reader_inputs(self,q,frames,inputs):
self.request['reader_tokens']=int(inputs.input_ids.shape[-1])
self.request['processed_rgb_pixels']=int(inputs.pixel_values.numel()//3)
if self.request['reader_tokens']>32768:
raise RuntimeError('Reader输入超过共同上限;需要两组共同修复,不能静默丢题')
def after_reader(self,q,raw,evidence,metrics):
import torch
torch.cuda.synchronize(self.device)
elapsed=time.perf_counter()-self.query_started
evidence.update(self.request)
metrics.update(gpu_seconds=elapsed,reader_wall_seconds=elapsed,writer_calls=0,writer_tokens=0,
storage_bytes=Path(self.path).stat().st_size,decoded_rgb_bytes=self.decoded_rgb_bytes,
model_revision='0c351dd01ed87e9c1b53cbc748cba10e6187ff3b',commit=self.commit,
max_gpu_allocated_bytes=torch.cuda.max_memory_allocated(self.device))
return evidence,metrics
def main():
import numpy as np
import torch
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
from memo.configuration import load_config
from memo.eval.shared_components import Qwen3VLAdapter, StageBackend, RetrievalCLIPEncoder, ChunkFrameStore
from cgvm.memo_processor import Processor
parser=argparse.ArgumentParser();parser.add_argument('--benchmark',choices=['ovobench','streamingbench'],required=True)
parser.add_argument('--output-root',default='results/R0');args=parser.parse_args()
assert os.environ.get('CUDA_VISIBLE_DEVICES')=='0,1,2,3'
rank=int(os.environ.get('LOCAL_RANK','0'));world=int(os.environ.get('LOCAL_WORLD_SIZE','1'))
assert world==4
device='cuda:'+str(rank);torch.cuda.set_device(rank)
selected=groups(args.benchmark,rank,world,require_media=True)
expected=[q['id'] for qs in selected.values() for q in qs]
target=ROOT/args.output_root/args.benchmark/f'shard{rank}';target.mkdir(parents=True,exist_ok=True)
output=target/'predictions.jsonl';previous={};attempts={}
if output.exists():
for line in output.read_text().splitlines():
item=json.loads(line);attempts[item['id']]=attempts.get(item['id'],0)+1
if item.get('status')=='answered':previous[item['id']]=item
config=load_config(ROOT/('repos/MEMO/configs/main/'+('ovobench_qwen3.json' if args.benchmark=='ovobench' else 'streamingbench_qwen3.json')))
random.seed(config['seed']);np.random.seed(config['seed']);torch.manual_seed(config['seed'])
state=dict(status='initializing',pid=os.getpid(),rank=rank,device=device,benchmark=args.benchmark,
expected_ids=expected,answered=len(previous),formal_full_shard=True,variant='R0_original_MEMO_with_shared_BT_adapter')
atomic(target/'state.json',state)
if len(previous)==len(expected):
state['status']='completed';atomic(target/'state.json',state);return
adapter=Qwen3VLAdapter(mode='image')
# 与原load相同权重/dtype/processor;仅显式绑定本rank,避免auto跨卡和四worker互抢。
adapter.model=Qwen3VLForConditionalGeneration.from_pretrained(str(ROOT/'weights/Qwen3-VL-8B-Instruct'),
dtype='auto',low_cpu_mem_usage=True,device_map={'':device}).eval()
adapter.processor=AutoProcessor.from_pretrained(str(ROOT/'weights/Qwen3-VL-8B-Instruct'),
min_pixels=256*28*28,max_pixels=1280*28*28)
backend=StageBackend(use_gpu=True)
clip=backend.CLIPEncoder(model_name=str(ROOT/'weights/clip-vit-large-patch14'),device=device)
detector=backend.GroundingDINODetector(weights_path=str(ROOT/'weights/grounding-dino-base'),device=device,
box_threshold=config['box_threshold'],text_threshold=config['text_threshold'])
tracker=backend.SAM2Tracker(checkpoint=str(ROOT/'weights/sam2.1_hiera_large.pt'),model_cfg='configs/sam2.1/sam2.1_hiera_l.yaml',device=device)
perception=backend.PerceptionLayer(clip,detector,tracker,text_prompt=config['detection_prompt'])
store,_,_=backend.build_chunk_store(feat_dim=clip.dim,device=device,cpu_max_size=config['cpu_max_size'])
retriever=backend.ChunkRetriever(store=store,device=device,lambda_global=.6,lambda_local=.4,strategy='ours',random_seed=config['seed'])
text_encoder=RetrievalCLIPEncoder(str(ROOT/'weights/clip-vit-large-patch14'),device=device)
frame_store=ChunkFrameStore(max_total_frames=config['max_store_frames'])
observer=AuditObserver(device,target);observer.commit=subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip()
exceptions_path=ROOT/'configs/verified_media_end_queries.json'
exceptions=json.loads(exceptions_path.read_text()) if exceptions_path.exists() else {}
processor=Processor(config,adapter,perception,store,retriever,text_encoder,frame_store,backend,device=device,observer=observer,
media_end_exceptions=exceptions)
original_answer=processor.answer
def answer(*a,**kw):
torch.cuda.synchronize(device);observer.query_started=time.perf_counter()
return original_answer(*a,**kw)
processor.answer=answer
state['status']='running';atomic(target/'state.json',state)
with output.open('a',buffering=1) as out:
def record(q,raw,evidence,metrics):
item=dict(q,prediction=raw,evidence=evidence,metrics=metrics,status='answered',attempt=attempts.get(q['id'],0),
**diagnostic_scores(q,raw))
out.write(json.dumps(item,ensure_ascii=False)+'\n');out.flush();previous[q['id']]=item
state.update(answered=len(previous),last_id=q['id'],updated_at=time.time());atomic(target/'state.json',state)
print(json.dumps(dict(rank=rank,benchmark=args.benchmark,answered=len(previous),expected=len(expected),id=q['id'])),flush=True)
for path,qs in selected.items():
pending=[q for q in qs if q['id'] not in previous]
if not pending:continue
observer.source_video=qs[0]['source_video'];observer.video_started=time.perf_counter()
try:
stats=processor.process(path,pending,record)
torch.cuda.synchronize(device)
audit=dict(source_video=observer.source_video,video_wall_seconds=time.perf_counter()-observer.video_started,
decode_seconds=observer.decode_seconds,chunk_closures=observer.closures,**stats)
atomic(target/(hashlib.sha256(path.encode()).hexdigest()[:20]+'.video.json'),audit)
except Exception as exc:
# 保留全部失败题和失败原因;不把异常从官方完整分母删除。
reason=type(exc).__name__+':'+str(exc)
for q in pending:
if q['id'] in previous:continue
item=dict(q,status='failed',prediction=None,failure_reason=reason,attempt=attempts.get(q['id'],0),
**diagnostic_scores(q,None))
out.write(json.dumps(item,ensure_ascii=False)+'\n');out.flush()
state.setdefault('failures',[]).append(dict(video=path,error=reason));atomic(target/'state.json',state)
torch.cuda.empty_cache()
state.update(status='completed' if len(previous)==len(expected) else 'completed_with_failures',answered=len(previous),
expected=len(expected),finished_at=time.time())
atomic(target/'state.json',state)
if __name__=='__main__':
logging.basicConfig(level=logging.WARNING)
main()