# 本文件从锁定MEMO处理器机械派生;原始快照不变。 # 仅加入显式rank设备和因果观测回调;默认observer=None时保留原计算路径。 # 原始MIT许可见repos/MEMO/LICENSE和provenance/MEMO.original.tar.gz。 """Causal video processing with independent historical/current frame budgets.""" from collections import deque import time import numpy as np import torch from PIL import Image from transformers import LogitsProcessor from memo.benchmarks.data import prompt from memo.eval.frame_selection import dual_budget, uniform_sample from memo.stage1.frame_extractor import FrameExtractor class TokenClock(LogitsProcessor): def __init__(self): self.times=[] def __call__(self, input_ids, scores): torch.cuda.synchronize() self.times.append(time.perf_counter()) return scores class Processor: def __init__(self, config, adapter, perception, store, retriever, text_encoder, frame_store, backend, device="cuda:0", observer=None, media_end_exceptions=None): self.device=device self.observer=observer self.media_end_exceptions=media_end_exceptions or {} self.cfg=config self.adapter=adapter self.perception=perception self.store=store self.retriever=retriever self.text_encoder=text_encoder self.frame_store=frame_store self.backend=backend self.module_times={} if config['profile'] and perception and hasattr(perception,'detector'): # Profiling deliberately serializes module calls; use separate accuracy runs. perception._stream_clip=None perception._stream_dino=None for obj, name, label in [(perception.clip,'encode_frame_full','clip'), (perception.detector,'detect','grounding_dino'), (perception.tracker,'update','sam2')]: original=getattr(obj,name) def timed(*args, _fn=original, _label=label, **kwargs): self.sync(); start=time.perf_counter() result=_fn(*args,**kwargs) self.sync() self.module_times.setdefault(_label,[]).append((time.perf_counter()-start)*1000) return result setattr(obj,name,timed) def sync(self): if self.cfg['profile']: torch.cuda.synchronize() def process(self, video_path, questions, record): from memo.stage2.stage2_similarity_gpu import SimilarityConfig from memo.stage2.stage3_segmentation_gpu import SegmentationConfig, StreamingSceneSegmenter c=self.cfg extractor=FrameExtractor(fps=c['target_fps'],backend='decord',anchor_end=False) video=extractor.extract(video_path) if self.observer: self.observer.start_video(video_path,video) duration=extractor.get_video_info(video_path).duration if not video.frames: raise ValueError(f'No decoded frames: {video_path}') for q in questions: if q['timestamp'] is not None and q['timestamp']>duration+1e-6: exception=self.media_end_exceptions.get(q['id']) # 仅允许已逐题核实官方切片也在同一媒体终点结束的原始标注;不改query_time。 if exception is None or exception['source_video']!=q.get('source_video') or abs(exception['query_time']-q['timestamp'])>1e-6: raise ValueError(f'Question timestamp exceeds video duration: {video_path}') selected=range(len(video.frames)) if self.store: self.store.clear(); self.frame_store.clear(); self.perception.reset_tracker() self.retriever._rng.seed(c['seed']) segmenter=None if c['variant']!='baseline': a,b,g=c['similarity_weights'] sim=SimilarityConfig(alpha=a,beta=b,gamma=g,device=self.device, ema_momentum=c['ema_momentum'],max_hidden_frames=c['max_hidden_frames'], gamma_app=c['gamma_app'],gamma_dis=c['gamma_dis'],max_displacement=c['max_displacement'], spatial_alpha=c['spatial_alpha'],unmatched_spatial=c['unmatched_spatial']) segmenter=StreamingSceneSegmenter(self.perception,SegmentationConfig(similarity=sim,device=self.device, adaptive_window=c['adaptive_window'],initial_threshold=c['initial_threshold'],threshold_k=c['threshold_k'], min_chunk_frames=c['min_chunk_frames'],cut_confirmation_frames=c['cut_confirmation_frames'])) pending={} # Baseline uniform sampling needs the entire observed prefix; chronology needs only a window. observed=[] if c['variant']=='baseline' else deque(maxlen=c['history_frames']+c['current_frames']) qpos=0 stats={'sampled_frames':len(video.frames),'processed_frames':0,'chunks':0,'push_ms':[],'ingest_ms':[]} def ingest(chunk): if chunk is None: return if self.observer: self.observer.closed_chunk(chunk,pending,segmenter) self.sync(); start=time.perf_counter() if c['variant']=='memo': self.backend.ingest_chunk(chunk,similarity_calc=segmenter.similarity_calc,store=self.store, feat_dim=self.perception.clip.dim) self.frame_store.add(chunk.chunk_id,[image for i,image in pending.items() if chunk.start_frame<=i<=chunk.end_frame]) for i in list(pending): if i<=chunk.end_frame: del pending[i] chunk.release_feature_tensors() # Completed chunks have been materialized in the store; do not retain raw perception frames. segmenter._completed_chunks.clear() self.sync() if c['profile']: stats['ingest_ms'].append((time.perf_counter()-start)*1000) stats['chunks']+=1 def answer_until(t, inclusive=True): nonlocal qpos while qpost or (qt==t and not inclusive): break raw, evidence, metrics=self.answer(q,list(pending.values()),list(observed)) record(q,raw,evidence,metrics) qpos+=1 for index in selected: frame=video.frames[index] answer_until(frame.timestamp,inclusive=False) if qpos==len(questions): break pil=Image.fromarray(frame.image.astype(np.uint8)) if self.observer: self.observer.register_frame(pil,frame,video.native_indices[index]) observed.append(pil) if segmenter is not None: native=video.native_indices[index] pending[native]=pil self.sync(); start=time.perf_counter() chunk=segmenter.push_frame(frame.image,native) self.sync() if c['profile']: stats['push_ms'].append((time.perf_counter()-start)*1000) ingest(chunk) stats['processed_frames']+=1 answer_until(frame.timestamp) if qpos==len(questions): break # Finite times after the last sampled frame still see the active chunk. answer_until(float('inf'),inclusive=False) if qpos1 else None) if self.observer: evidence,metrics=self.observer.after_reader(q,raw,evidence,metrics) return raw,evidence,metrics