File size: 3,733 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
#!/usr/bin/env python3
"""真实缓存/问题上的alpha0和实际编码接口核验,不运行训练或报告准确率。"""
import hashlib
import json
from pathlib import Path
import sys
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT));sys.path.insert(0,str(ROOT/'scripts'));sys.path.insert(0,str(ROOT/'repos/MEMO'))
from download_assets import atomic,sha


def main():
    import torch
    import torch.nn.functional as F
    from memo.eval.shared_components import RetrievalCLIPEncoder
    from cgvm.retrieval import ResidualRanker
    from cgvm.cached_retrieval import CachedRetriever
    from cgvm.features import features
    torch.set_num_threads(2);torch.manual_seed(17)
    rows=[json.loads(line) for line in (ROOT/'manifests/online_pilot20k.candidate.jsonl').open()]
    q=next(r for r in rows if r['id']=='tco-037986-d2c421747c84')
    token=hashlib.sha256(q['source_video'].encode()).hexdigest()[:24]
    path=ROOT/'data/frozen_causal_cache'/(token+'.pt');cache=torch.load(path,map_location='cpu',weights_only=False)
    text=RetrievalCLIPEncoder(str(ROOT/'weights/clip-vit-large-patch14'),device='cpu')
    with torch.inference_mode():
        inputs=text.processor(text=[q['question']],return_tensors='pt',padding=True,truncation=True,max_length=77)
        value=text.model.text_model(input_ids=inputs['input_ids'],attention_mask=inputs['attention_mask'])
        query=F.normalize(text.model.text_projection(value.pooler_output),dim=-1)[0]
    details=[]
    for variant in ('R1','R2'):
        ranker=ResidualRanker().eval();ranker.alpha.data.zero_()
        # R2此项只验证真实视觉输入和alpha零接口,不捏造尚未生成的Writer特征。
        retriever=CachedRetriever(cache,{'writer_features':{}},ranker,variant,'cpu')
        actual=retriever.query(query,q['query_time'])
        original=retriever.original.query_vec(query,top_k=3,recall_tokens=False)
        if [(r.chunk_id,r.score) for r in actual]!=[(r.chunk_id,r.score) for r in original]:raise ValueError('alpha0未还原原MEMO')
        chunk=next(c for c in cache['chunks'] if not c['terminal_flush'] and c['committed_at']<=q['query_time'])
        inputs,_=features(cache,chunk,variant,q['query_time'])
        with torch.inference_mode():
            keys=ranker.encode(inputs['primary'],inputs['secondary'],inputs['geometry'],inputs['visible_mask'])
            single=ranker(query[None,:],**inputs)
            cached=ranker.score_encoded(query[None,:],keys,inputs['context'])
            matrix=ranker.score_encoded(query[None,:],keys,inputs['context'],all_pairs=True)
        if not torch.isfinite(single).all() or not torch.allclose(single,cached,atol=1e-6) or not torch.allclose(single,matrix[0],atol=1e-6):
            raise ValueError('实际单题/矩阵/冻结编码接口不同')
        details.append(dict(variant=variant,trainable_parameters=sum(p.numel() for p in ranker.parameters()),
            original_and_cached_alpha0_exact=True,chunk_ids=[h.chunk_id for h in actual],scores=[h.score for h in actual],
            scalar_matrix_cached_encoding_agree=True,sequence_tokens=inputs['primary'].shape[1]))
    atomic(ROOT/'provenance/retrieval_contract_after_position_encoding.json',dict(passed=True,QA_id=q['id'],
        source_video=q['source_video'],query_time=q['query_time'],cache_sha256=sha(path),
        code_sha256={name:sha(ROOT/name) for name in ['scripts/check_retrieval_contract.py','cgvm/retrieval.py','cgvm/cached_retrieval.py','cgvm/features.py']},
        scope='real_visual_cache_and_original_question_CPU_contract_not_training_or_CGVM_Writer_validation',
        Writer_features_used=False,details=details))
    print(json.dumps(details))


if __name__=='__main__':main()