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
Download src/scripts/export_qa_packs.py from XiangnanW/CGVM-R2.6-Qwen3VL-8B-step600: direct link, hf CLI and curl.
- Browser
- Download file 6.05 kB
-
https://huggingface.co/XiangnanW/CGVM-R2.6-Qwen3VL-8B-step600/resolve/main/src/scripts/export_qa_packs.py
- Command line
-
hf download hf://XiangnanW/CGVM-R2.6-Qwen3VL-8B-step600/src/scripts/export_qa_packs.py
-
curl -L -o export_qa_packs.py https://huggingface.co/XiangnanW/CGVM-R2.6-Qwen3VL-8B-step600/resolve/main/src/scripts/export_qa_packs.py
6.05 kB
| #!/usr/bin/env python3 | |
| """冻结检索后的合法图像序列证据包;两组使用同一QA ID和自身检索结果。""" | |
| import argparse | |
| import dataclasses | |
| import functools | |
| 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,sha | |
| def main(): | |
| import torch | |
| import torch.nn.functional as F | |
| from transformers import AutoTokenizer | |
| from memo.eval.shared_components import RetrievalCLIPEncoder | |
| from memo.eval.frame_selection import uniform_sample | |
| from cgvm.retrieval import ResidualRanker | |
| from cgvm.evidence import EvidenceBuilder | |
| parser=argparse.ArgumentParser();parser.add_argument('--variant',choices=['R1','R2'],required=True) | |
| parser.add_argument('--manifest',required=True);parser.add_argument('--output-dir',required=True) | |
| parser.add_argument('--evidence-mode',choices=['default','C1_plain_caption'],default='default', | |
| help='证据构建模式:default正式版,C1_plain_caption为从头微调外部普通Caption基线专用') | |
| parser.add_argument('--candidate',action='store_true');args=parser.parse_args() | |
| rank=int(os.environ.get('LOCAL_RANK',os.environ.get('RANK','0'))) | |
| world=int(os.environ.get('LOCAL_WORLD_SIZE',os.environ.get('WORLD_SIZE','1'))) | |
| if world<1:raise RuntimeError('export_qa_packs 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) | |
| rows=[json.loads(line) for line in (ROOT/args.manifest).open()] | |
| byvideo={} | |
| for row in rows:byvideo.setdefault(row['source_video'],[]).append(row) | |
| selected=[(video,qs) for i,(video,qs) in enumerate(sorted(byvideo.items())) if i%world==rank] | |
| output=ROOT/args.output_dir;output.mkdir(parents=True,exist_ok=True) | |
| target=output/f'shard{rank}.jsonl';marker=output/f'shard{rank}.meta.json' | |
| if target.exists():raise FileExistsError('保存旧导出,不能覆盖不明阶段的证据包') | |
| training_root=ROOT/'checkpoints'/args.variant/'retrieval' | |
| checkpoint=training_root/json.loads((training_root/'latest.json').read_text())['directory']/'training.pt' | |
| payload=torch.load(checkpoint,map_location='cpu',weights_only=False) | |
| checkpoint_hash=sha(checkpoint) | |
| expected_s1_steps=payload['config'].get('steps',625) | |
| if payload['config']['variant']!=args.variant or payload['step']!=expected_s1_steps:raise ValueError('检索必须冻结S1末checkpoint') | |
| ranker=ResidualRanker.from_checkpoint_state(payload['model'],device=device).eval() | |
| clip=RetrievalCLIPEncoder(str(ROOT/'weights/clip-vit-large-patch14'),device=device) | |
| tokenizer=AutoTokenizer.from_pretrained(str(ROOT/'weights/Qwen3-VL-8B-Instruct')) | |
| count=0;started=time.perf_counter() | |
| code_commit=subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip() | |
| def encode(question): | |
| with torch.inference_mode(): | |
| inputs=clip.processor(text=[question],return_tensors='pt',padding=True,truncation=True,max_length=77) | |
| inputs={k:v.to(device) for k,v in inputs.items()};value=clip.model.text_model(input_ids=inputs['input_ids'],attention_mask=inputs['attention_mask']) | |
| return F.normalize(clip.model.text_projection(value.pooler_output),dim=-1)[0] | |
| with target.open('w',buffering=1) as stream: | |
| for video,questions in selected: | |
| token=hashlib.sha256(video.encode()).hexdigest()[:24];cache_path=ROOT/'data/frozen_causal_cache'/(token+'.pt') | |
| cache=torch.load(cache_path,map_location='cpu',weights_only=False) | |
| bank_path=ROOT/'data/change_banks'/(token+'.pt');bank=torch.load(bank_path,map_location='cpu',weights_only=False) | |
| bank_hash=sha(bank_path) | |
| if not bank['writer_complete'] or bank['qa_or_answers_read']:raise ValueError('Writer建库未完成或使用了QA') | |
| builder=EvidenceBuilder(cache,bank,ranker,args.variant,device,evidence_mode=args.evidence_mode) | |
| use_writer_cost=(args.variant=='R2') or (args.evidence_mode!='default') | |
| for q in sorted(questions,key=lambda q:(q['query_time'],q['id'])): | |
| torch.cuda.synchronize(device);tick=time.perf_counter() | |
| evidence=builder.build(encode(q['question']),q['query_time'], | |
| 'Answer the question using the observed video frames.\nQuestion: '+q['question']) | |
| if len(tokenizer(evidence['prompt'],add_special_tokens=False).input_ids)>4096: | |
| raise ValueError('共同文本上限超出,不能仅截断某个系统') | |
| torch.cuda.synchronize(device) | |
| pack=dict(evidence,id=q['id'],variant=args.variant,source_video=video,query_time=q['query_time'],answer=q['answer'], | |
| visual_cache_sha256=bank['visual_cache_sha256'],writer_bank_sha256=bank_hash, | |
| retrieval_checkpoint_sha256=checkpoint_hash,pack_export_gpu_seconds=time.perf_counter()-tick, | |
| storage_bytes=cache_path.stat().st_size+(bank_path.stat().st_size if use_writer_cost else 0), | |
| commit=code_commit,model_revision='0c351dd01ed87e9c1b53cbc748cba10e6187ff3b') | |
| stream.write(json.dumps(pack,ensure_ascii=False)+'\n');count+=1 | |
| atomic(output/f'rank{rank}.progress.json',dict(pid=os.getpid(),rank=rank,exported=count,last_video=video)) | |
| atomic(marker,dict(variant=args.variant,rank=rank,count=count,manifest_sha256=sha(ROOT/args.manifest), | |
| final_frozen=not args.candidate,retrieval_checkpoint_sha256=checkpoint_hash, | |
| wall_seconds=time.perf_counter()-started,sha256=sha(target))) | |
| if __name__=='__main__':logging.basicConfig(level=logging.WARNING);main() | |