Instructions to use XiangnanW/CGVM-R2.6-Qwen3VL-8B-step600 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use XiangnanW/CGVM-R2.6-Qwen3VL-8B-step600 with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
File size: 13,801 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 | #!/usr/bin/env python3
"""在共享因果视觉缓存上运行固定8B Writer,保留全部视觉记录和真实写入成本。"""
import argparse
from dataclasses import asdict
import hashlib
import json
import logging
import os
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 torch
from PIL import Image
from transformers import AutoProcessor,Qwen3VLForConditionalGeneration
from memo.eval.shared_components import Qwen3VLAdapter,RetrievalCLIPEncoder
from cgvm.change_bank import ChangeBank
from cgvm.writer import FixedWriter,_json_default
from cgvm.media import load_images,frame_reference
from cgvm.sources import source_plan
def _clean_bbox(bbox):
if isinstance(bbox,dict):
return {k:(float(v) if hasattr(v,'item') else v) for k,v in bbox.items()}
return bbox
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()
from cgvm.distributed import best_attn_implementation
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('Writer 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)
videos,cache_root,output_root=source_plan(args.domain)
all_videos=sorted(videos)
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
]
output_root.mkdir(parents=True,exist_ok=True)
adapter=Qwen3VLAdapter(mode='image')
adapter.model=Qwen3VLForConditionalGeneration.from_pretrained(str(ROOT/'weights/Qwen3-VL-8B-Instruct'),
dtype=torch.bfloat16,low_cpu_mem_usage=True,device_map={'':device},
attn_implementation=best_attn_implementation()).eval()
adapter.processor=AutoProcessor.from_pretrained(str(ROOT/'weights/Qwen3-VL-8B-Instruct'),min_pixels=256*28*28,max_pixels=1280*28*28)
writer=FixedWriter(adapter,device)
text_encoder=RetrievalCLIPEncoder(str(ROOT/'weights/clip-vit-large-patch14'),device=device)
# 只对语义字段编码,Writer ID/时间元数据不进入S1文本匹配。
def encode(text):
with torch.inference_mode():
inputs=text_encoder.processor(text=[text or 'unknown'],return_tensors='pt',padding=True,truncation=True,max_length=77)
inputs={k:v.to(device) for k,v in inputs.items()}
value=text_encoder.model.text_model(input_ids=inputs['input_ids'],attention_mask=inputs['attention_mask'])
return torch.nn.functional.normalize(text_encoder.model.text_projection(value.pooler_output),dim=-1)[0].cpu()
finished=set()
from cgvm.commit import code_commit as _code_commit
implementation=dict(code_commit=_code_commit(ROOT),
code_sha256={name:sha(ROOT/name) for name in ['scripts/cache_writer_memory.py','cgvm/writer.py','cgvm/change_bank.py','cgvm/media.py']},
method_config_sha256=sha(ROOT/'configs/method.frozen.json'),writer_min_interval=writer.min_interval)
ledger=(ROOT/'logs'/f'writer_{args.domain}_rank{rank}.jsonl').open('a',buffering=1)
calls_ledger=(ROOT/'logs'/f'writer_{args.domain}_calls_rank{rank}.jsonl').open('a',buffering=1)
while True:
progress=False
for video in assigned:
token=hashlib.sha256(video.encode()).hexdigest()[:24];cache_path=cache_root/(token+'.pt')
target=output_root/(token+'.pt');marker=output_root/(token+'.json')
claim=output_root/(token+'.claim')
if marker.exists():finished.add(video);continue
if not cache_path.exists():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
try:
cache=torch.load(cache_path,map_location='cpu',weights_only=False)
byindex={f['native_index']:f for f in cache['frames']}
bank=ChangeBank(video);writer.reset();writer_features={};chunk_records={};started=time.perf_counter()
call_records=[]
include_terminal=os.environ.get('CGVM_WRITER_INCLUDE_TERMINAL','0')=='1'
for chunk in cache['chunks']:
# 默认跳过未闭合的尾块(OVO 的 query_time 在视频中段);对“整段看完再提问”的
# 外部 benchmark,尾块就是已观测到的最后一段,允许写成记忆。
if chunk['terminal_flush'] and not include_terminal:continue
chunk_frames=[byindex[i] for i in chunk['frame_ids']]
references=[frame_reference(f) for f in chunk_frames]
committed=chunk['committed_at'];local_records=[];entity_sequences={}
for f,ref in zip(chunk_frames,references):
for obj in f['objects']:
key=(obj['generation'],obj['track_id'])
entity_sequences.setdefault(key,[]).append((f,ref,obj))
# 无文字窗口也保留视觉变化来源,不用Writer遗漏删除观测。
visual_records=[('scene',0,references,[],[1.]*len(references),{})]
for (generation,track),sequence in sorted(entity_sequences.items()):
support=[entry[1] for entry in sequence];regions=[_clean_bbox(entry[2]['bbox']) for entry in sequence]
phases={}
if len(sequence)>=3:
amplitudes=[float((sequence[i][2]['local_feature']-sequence[i-1][2]['local_feature']).norm()) for i in range(1,len(sequence))]
# 变化峰只提供真实图像差异支持;不据此断言物理动作次数或相机独立运动。
peak=max(range(1,len(sequence)),key=lambda i:amplitudes[i-1])
if amplitudes[peak-1]>.2 and peak<len(sequence)-1:
phases=dict(before=support[peak-1]['frame_id'],during=support[peak]['frame_id'],after=support[peak+1]['frame_id'])
visual_records.append((f'g{generation}:t{track}',generation,support,regions,[1.]*len(support),phases))
for entity,generation,support,regions,visibility,phases in visual_records:
record=bank.append(entity_id=entity,generation=generation,chunk_id=chunk['chunk_id'],frames=support,
committed_at=committed,state_text='',delta_text='',visibility=visibility,regions=regions,
confidence=0.,phase_support=phases,phase_support_basis='observed_local_visual_change_peak_not_physical_event_count')
local_records.append(record.record_id)
call=None
if writer.ready(committed):
# 先按与FixedWriter相同规则选至多8帧,避免为一次8图输入解码整窗。
count=min(len(chunk_frames),8)
indices=[i*(len(chunk_frames)-1)//max(count-1,1) for i in range(count)]
writer_refs=[references[i] for i in indices]
media_cost={};images=load_images([chunk_frames[i] for i in indices],metrics=media_cost)
entities=[]
for (generation,track),sequence in sorted(entity_sequences.items())[:16]:
obj=sequence[-1][2]
entities.append(dict(entity_id=f'g{generation}:t{track}',generation=int(generation),label=obj['label'],bbox=_clean_bbox(obj['bbox'])))
previous=bank.current.get('scene:0');old=previous.state_text if previous else ''
valid_entities={'scene'}|{e['entity_id'] for e in entities}
prior=[dict(record_id=r.record_id,entity_id=r.entity_id,generation=r.generation,
observed_at=r.observed_at,state=r.state_text[:256])
for r in bank.current.values() if r.state_text and r.entity_id in valid_entities]
call=writer.write(images,writer_refs,entities,committed,previous_state=old,previous_records=prior[:17])
call.update(media_cost)
if call is not None:
call_records.append(call)
calls_ledger.write(json.dumps(dict(call,source_video=video,rank=rank,domain=args.domain,
code_commit=implementation['code_commit'],attempt_started_unix=time.time()-call['gpu_seconds']),ensure_ascii=False,default=_json_default)+'\n')
value=call['parsed']
if value:
entity=str(value['entity_id']);generation=0 if entity=='scene' else next(e['generation'] for e in entities if e['entity_id']==entity)
support=call['support'];phases=value['phase_support']
if entity!='scene':
valid={entry[1]['frame_id'] for key,sequence in entity_sequences.items()
if f'g{key[0]}:t{key[1]}'==entity for entry in sequence}
phases={phase:fid for phase,fid in phases.items() if fid in valid}
support=[ref for ref in support if ref['frame_id'] in valid]
if support:
boundary=value['boundary'] if len(phases)>=2 else 'uncertain'
record=bank.append(entity_id=entity,generation=generation,chunk_id=chunk['chunk_id'],frames=support,
committed_at=committed,state_text=value['state'],delta_text=value['delta'],visibility=[1.]*len(support),
regions=[],confidence=value['confidence'],event_boundary=boundary,phase_support=phases,
revision_of=value['revision_of'])
local_records.append(record.record_id)
writer_features[chunk['chunk_id']]=dict(state_key=encode(value['state']),change_key=encode(value['delta']),
record_id=record.record_id,committed_at=committed)
chunk_records[chunk['chunk_id']]=local_records
cache_marker=cache_root/(token+'.json')
cache_sha=json.loads(cache_marker.read_text())['sha256'] if cache_marker.exists() else sha(cache_path)
payload=dict(source_video=video,records=bank.serializable(),chunk_records=chunk_records,writer_features=writer_features,
current_state_pointers={key:r.record_id for key,r in bank.current.items()},inferred_event_counters=bank.events,
writer_calls=call_records,visual_cache_sha256=cache_sha,writer_model_revision='0c351dd01ed87e9c1b53cbc748cba10e6187ff3b',
writer_complete=True,qa_or_answers_read=False,rank=rank,wall_seconds=time.perf_counter()-started)
payload.update(implementation=implementation,domain=args.domain)
saved_bytes,saved_sha=safe_torch_save(payload, target)
receipt=dict(source_video=video,path=str(target),sha256=saved_sha,records=len(bank.records),writer_calls=len(call_records),
writer_tokens=sum(c['writer_tokens'] for c in call_records),writer_generation_gpu_seconds=sum(c['gpu_seconds'] for c in call_records),
wall_gpu_seconds=time.perf_counter()-started,storage_bytes=saved_bytes,
parse_failures=sum(c['parse_status']!='valid' for c in call_records),rank=rank)
receipt.update(image_decode_and_materialization_seconds=sum(c['image_decode_and_materialization_seconds'] for c in call_records),
peak_CPU_raw_decoded_archive_bytes=max((c['CPU_raw_decoded_archive_bytes'] for c in call_records),default=0))
receipt.update(implementation=implementation,domain=args.domain)
atomic(marker,receipt);ledger.write(json.dumps(receipt,ensure_ascii=False,default=_json_default)+'\n');finished.add(video);progress=True
print(json.dumps(receipt,ensure_ascii=False,default=_json_default),flush=True)
finally:
claim.unlink(missing_ok=True)
if len(finished)==len(assigned) or not args.poll:break
if not progress:time.sleep(30)
ledger.close();calls_ledger.close()
if __name__=='__main__':logging.basicConfig(level=logging.WARNING);main()
|