File size: 16,111 Bytes
4ad9219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/env python3
"""四GPU互斥视频分片,使用原MEMO感知/分块,导出因果冻结键与视觉序列。"""
import argparse
import dataclasses
import hashlib
import json
import logging
import os
import random
from pathlib import Path
import sys
import subprocess
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, safe_torch_save, sha


def main():
    import numpy as np
    import torch
    from PIL import Image
    from memo.configuration import load_config
    from memo.eval.shared_components import StageBackend
    from memo.stage2.stage2_similarity_gpu import SimilarityConfig
    from memo.stage2.stage3_segmentation_gpu import SegmentationConfig, StreamingSceneSegmenter
    from memo.stage3_gpu.stage3_ingestion import _aggregate_global_feature, _extract_entity_features
    from memo.stage1.frame_extractor import FrameExtractor
    from cgvm.sources import source_plan

    parser = argparse.ArgumentParser()
    parser.add_argument('--poll', action='store_true')
    parser.add_argument('--domain',choices=['training','ovobench','streamingbench','tempcompass','videomme','longvideobench','motionbench'],default='training')
    args = parser.parse_args()
    rank = int(os.environ.get('CGVM_SHARD_RANK',os.environ.get('LOCAL_RANK',os.environ.get('RANK','0'))))
    world = int(os.environ.get('CGVM_SHARD_WORLD',os.environ.get('LOCAL_WORLD_SIZE',os.environ.get('WORLD_SIZE','1'))))
    if world < 1:
        raise RuntimeError('预处理WORLD_SIZE必须>=1')
    num_gpus = torch.cuda.device_count()
    if num_gpus < 1:
        raise RuntimeError('未检测到可见CUDA GPU')
    gpu_idx = rank % num_gpus
    device = 'cuda:' + str(gpu_idx)
    torch.cuda.set_device(gpu_idx)
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    torch.manual_seed(17)
    config_path=ROOT/'repos/MEMO/configs/main'/('streamingbench_qwen3.json' if args.domain=='streamingbench' else 'ovobench_qwen3.json')
    cfg = load_config(config_path)
    seed=17 if args.domain=='training' else cfg['seed']
    random.seed(seed);np.random.seed(seed);torch.manual_seed(seed)
    videos,base,_=source_plan(args.domain)
    all_videos = sorted(videos.items())
    # 先处理本rank分片,再动态协助处理其他rank未认领的视频,消除长短视频负载不均并支持随时热加Worker。
    assigned = [all_videos[i] for i in range(len(all_videos)) if i % world == rank] + [
        all_videos[i] for i in range(len(all_videos)) if i % world != rank
    ]
    base.mkdir(parents=True,exist_ok=True)
    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=cfg['box_threshold'],text_threshold=cfg['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=cfg['detection_prompt'])
    # 上游reset把track ID归零;显式追踪generation,避免把边界carry-over与新ID强连。
    generation = 0
    original_reset = perception.reset_tracker
    def reset():
        nonlocal generation
        generation += 1
        original_reset()
    perception.reset_tracker = reset
    original_perceive = perception.process_frame
    current_file = None
    current_time = None
    current_rgb_sha = None
    active_reference = None
    observation = None
    def perceive(*arguments,**kwargs):
        nonlocal observation
        value = original_perceive(*arguments,**kwargs)
        for entity in value.tracked_objects:
            entity.generation = generation
        observation = dict(active_reference,source_video=active_video,timestamp=current_time,
                           width=arguments[0].shape[1],height=arguments[0].shape[0],
                           rgb_sha256=current_rgb_sha or hashlib.sha256(arguments[0].tobytes()).hexdigest(),
                           global_feature=value.global_feature.detach().cpu().clone(),
                           objects=[dict(track_id=o.track_id,generation=o.generation,label=o.label,
                                         bbox=dataclasses.asdict(o.bbox),local_feature=o.local_feature.detach().cpu().clone(),
                                         visibility=True,pixel_area_ratio=o.pixel_area_ratio) for o in value.tracked_objects])
        return value
    perception.process_frame = perceive
    finished = set()
    rank_ledger = ROOT/'logs'/(f'causal_cache_rank{rank}.jsonl' if args.domain=='training' else f'causal_cache_{args.domain}_rank{rank}.jsonl')
    config_hash = sha(config_path)
    from cgvm.commit import code_commit as _code_commit
    code_commit=_code_commit(ROOT)
    script_hash=sha(Path(__file__))
    resources_hash=sha(ROOT/'manifests/resources.json')
    with rank_ledger.open('a',buffering=1) as log:
        while True:
            made_progress = False
            inventory = json.loads((ROOT/'provenance/training_media_inventory.json').read_text()) if args.domain=='training' else {}
            for active_video,meta in assigned:
                token = hashlib.sha256(active_video.encode()).hexdigest()[:24]
                target = base/(token+'.pt')
                marker = base/(token+'.json')
                claim = base/(token+'.claim')
                if marker.exists():
                    finished.add(active_video);continue
                if claim.exists() and (time.time() - claim.stat().st_mtime) < 3600:
                    continue
                try:
                    fd = os.open(str(claim), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
                    os.write(fd, f'{os.getpid()}:{rank}:{time.time()}\n'.encode())
                    os.close(fd)
                except FileExistsError:
                    continue
                decode_seconds=0.;extracted=None
                try:
                    if args.domain=='training':
                        source = active_video.split('/')[0]
                        extract_marker = ROOT/'provenance'/('training_media_extracted_'+source+'.json')
                        video_dir = ROOT/'data/training_frames'/active_video
                        if not extract_marker.exists() and not (os.environ.get('CGVM_SKIP_EXTRACT_MARKER')=='1' and video_dir.is_dir()):
                            claim.unlink(missing_ok=True);continue
                        media = sorted(video_dir.glob('*.jpg'),key=lambda p:int(p.stem)) if video_dir.is_dir() else []
                        media = [p for p in media if int(p.stem) <= meta['max_query_time']]
                        if not media:
                            if os.environ.get('CGVM_SKIP_EXTRACT_MARKER')=='1':
                                claim.unlink(missing_ok=True);continue
                            raise RuntimeError('已提取来源缺候选视频:'+active_video)
                        if extract_marker.exists():
                            if active_video not in inventory and (ROOT/'provenance/training_media_inventory.json').exists():
                                inventory=json.loads((ROOT/'provenance/training_media_inventory.json').read_text())
                            if active_video in inventory and len(media) != inventory[active_video]['files']:
                                raise RuntimeError('媒体清单与实际帧数不一致:'+active_video)
                    else:
                        # 流式解码:与 MEMO FrameExtractor 完全相同的采样索引/时间戳,但不把整段帧驻留内存。
                        tick=time.perf_counter();path=str(ROOT/meta['path'])
                        extracted=None
                        media=None
                    perception.reset_tracker()
                    a,b,g = cfg['similarity_weights']
                    sim = SimilarityConfig(alpha=a,beta=b,gamma=g,device=device,ema_momentum=cfg['ema_momentum'],
                                           max_hidden_frames=cfg['max_hidden_frames'],gamma_app=cfg['gamma_app'],gamma_dis=cfg['gamma_dis'],
                                           max_displacement=cfg['max_displacement'],spatial_alpha=cfg['spatial_alpha'],unmatched_spatial=cfg['unmatched_spatial'])
                    segmenter = StreamingSceneSegmenter(perception,SegmentationConfig(similarity=sim,device=device,
                        adaptive_window=cfg['adaptive_window'],initial_threshold=cfg['initial_threshold'],threshold_k=cfg['threshold_k'],
                        min_chunk_frames=cfg['min_chunk_frames'],cut_confirmation_frames=cfg['cut_confirmation_frames']))
                    observations = []
                    chunks = []
                    def close(chunk,committed_at,terminal=False):
                        if chunk is None:return
                        keys = _aggregate_global_feature([f.global_feature for f in chunk.frames],
                                                           [s.s_total for s in chunk.similarity_scores],device)
                        entities = _extract_entity_features(chunk.entity_buffer,cfg['max_hidden_frames'],device)
                        chunks.append(dict(chunk_id=chunk.chunk_id,start_frame=chunk.start_frame,end_frame=chunk.end_frame,
                                           committed_at=float(committed_at),terminal_flush=terminal,
                                           global_key=keys.detach().cpu().clone(),entity_keys=entities.detach().cpu().clone(),
                                           frame_ids=[f.frame_idx for f in chunk.frames],
                                           similarity_scores=[dataclasses.asdict(s) for s in chunk.similarity_scores]))
                        chunk.release_feature_tensors();segmenter._completed_chunks.clear()
                    torch.cuda.synchronize(device);started = time.perf_counter()
                    if args.domain=='training':
                        from concurrent.futures import ThreadPoolExecutor
                        import io
                        strict_rgb_sha = os.environ.get('CGVM_VERIFY_RGB_SHA', '0') == '1'
                        def _decode_jpeg(f_path):
                            t0 = time.perf_counter()
                            raw_bytes = f_path.read_bytes()
                            with Image.open(io.BytesIO(raw_bytes)) as image:
                                arr = np.asarray(image.convert('RGB')).copy()
                            digest = hashlib.sha256(arr.tobytes() if strict_rgb_sha else raw_bytes).hexdigest()
                            return f_path, arr, digest, time.perf_counter() - t0
                        with ThreadPoolExecutor(max_workers=16) as decode_pool:
                            for current_file, rgb, rgb_Digest, d_sec in decode_pool.map(_decode_jpeg, media):
                                current_time=float(int(current_file.stem));native=int(current_file.stem)
                                current_rgb_sha=rgb_Digest
                                decode_seconds+=d_sec
                                active_reference=dict(frame_id=current_file.relative_to(ROOT/'data/training_frames').as_posix(),
                                                      native_index=native,path=str(current_file))
                                chunk = segmenter.push_frame(rgb,native)
                                observations.append(observation)
                                close(chunk,current_time)
                    else:
                        from cgvm.stream_decode import iter_frames
                        current_rgb_sha=None;seen=0;decode_stats={}
                        for ts,native,rgb in iter_frames(path,cfg['target_fps'],meta['max_query_time'],stats=decode_stats):
                            current_time=float(ts);seen+=1
                            active_reference=dict(frame_id=f'{args.domain}:{active_video}:{native}',native_index=native,
                                                  video_path=path)
                            chunk = segmenter.push_frame(rgb,native)
                            observations.append(observation)
                            close(chunk,current_time)
                        decode_seconds+=decode_stats.get('decode_seconds',0.0)
                        if seen==0:raise RuntimeError('官方截止时间前没有原始MEMO采样帧:'+active_video)
                    # 终点flush只保存为终端记录;普通有限query不能提前把未闭合尾窗当历史。
                    close(segmenter.flush(),max(meta['max_query_time'],current_time),terminal=True)
                    torch.cuda.synchronize(device);seconds = time.perf_counter()-started
                    if args.domain!='training':seconds+=decode_seconds
                    payload = dict(source_video=active_video,causal=True,perception='unmodified_locked_MEMO',
                                   config_hash=config_hash,frames=observations,chunks=chunks,
                                   max_observed_time=current_time,max_query_time=meta['max_query_time'],
                                   rank=rank,world_size=world,wall_seconds=seconds,decode_seconds=decode_seconds,
                                   perception_and_chunk_seconds=seconds-decode_seconds,
                                   omitted_from_export='unused_CLIP_patch_token_archive; original_sampling_retrieves_raw_images',
                                   identity_rule='upstream_tracker_reset_increments_generation; no_forced_cross_generation_identity')
                    payload.update(domain=args.domain,media_sha256=meta.get('media_sha256'),
                                   seed=seed,
                                   code_commit=code_commit,script_sha256=script_hash,resources_manifest_sha256=resources_hash,
                                   sampling='official_1fps_JPEG' if args.domain=='training' else 'locked_MEMO_full_video_native_indices_then_prefix',
                                   raw_frame_archive='original_JPEG' if args.domain=='training' else 'shared_original_MP4_plus_native_index_and_verified_RGB_hash')
                    saved_bytes, saved_sha = safe_torch_save(payload, target)
                    receipt = dict(source_video=active_video,file=str(target),sha256=saved_sha,frames=len(observations),
                                   chunks=len(chunks),wall_seconds=seconds,decode_seconds=decode_seconds,rank=rank,
                                   gpu_seconds=seconds,storage_bytes=saved_bytes,config_hash=config_hash,
                                   causal_index_export=True,writer_complete=False)
                    receipt.update(code_commit=code_commit,script_sha256=script_hash,resources_manifest_sha256=resources_hash,domain=args.domain)
                    atomic(marker,receipt);log.write(json.dumps(receipt,ensure_ascii=False)+'\n')
                    print(json.dumps(dict(rank=rank,source_video=active_video,frames=len(observations),fps=len(observations)/seconds),ensure_ascii=False),flush=True)
                    finished.add(active_video);made_progress=True
                    if extracted is not None:del extracted
                    atomic(ROOT/'coordination'/f'causal_cache_rank{rank}.json',dict(pid=os.getpid(),rank=rank,device=device,
                        assigned=len(assigned),completed=len(finished),last_video=active_video,updated_at=time.time()))
                finally:
                    claim.unlink(missing_ok=True)
            if len(finished)==len(assigned):
                break
            if not args.poll:
                break
            if not made_progress:
                time.sleep(30)


if __name__=='__main__':
    logging.basicConfig(level=logging.WARNING)
    main()