File size: 12,512 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
#!/usr/bin/env python3
"""以完整媒体/源冲突/因果缓存为依据冻结共同20k及S1辅助清单,不承认partial审计。"""
import argparse
import collections
import hashlib
import heapq
import json
import math
from pathlib import Path
import sys
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
sys.path.insert(0,str(ROOT))
from download_assets import atomic,sha
from cgvm.training_text import caption_text


def token(video):return hashlib.sha256(video.encode()).hexdigest()[:24]


def main():
    parser=argparse.ArgumentParser();parser.add_argument('--apply',action='store_true');args=parser.parse_args()
    videos=json.loads((ROOT/'manifests/training_videos.candidate.json').read_text())
    required={video:dict(media=False,cache=False,writer=False) for video in videos}
    for video,flags in required.items():
        source=video.split('/')[0];key=token(video)
        flags['media']=(ROOT/'provenance'/('training_media_extracted_'+source+'.json')).exists()
        flags['cache']=(ROOT/'data/frozen_causal_cache'/(key+'.json')).exists()
        flags['writer']=(ROOT/'data/change_banks'/(key+'.json')).exists()
    overlap_path=ROOT/'provenance/content_overlap_audit.json'
    overlap=json.loads(overlap_path.read_text()) if overlap_path.exists() else {}
    bank_audit_path=ROOT/'provenance/change_bank_audit.training.json'
    bank_audit=json.loads(bank_audit_path.read_text()) if bank_audit_path.exists() else {}
    ready=all(all(flags.values()) for flags in required.values()) and overlap.get('full_required_coverage',False) and bank_audit.get('passed',False)
    state=dict(phase='freeze_readiness',ready=ready,required_videos=len(required),
               complete_counts={kind:sum(flags[kind] for flags in required.values()) for kind in ('media','cache','writer')},
               content_overlap_complete=overlap.get('full_required_coverage',False),
               actual_change_bank_audit_passed=bank_audit.get('passed',False),
               missing=[dict(source_video=video,missing=[kind for kind,ok in flags.items() if not ok]) for video,flags in required.items() if not all(flags.values())])
    atomic(ROOT/'provenance/training_freeze_readiness.json',state)
    print(json.dumps({k:v for k,v in state.items() if k!='missing'},indent=2),flush=True)
    if not ready:
        if args.apply:raise RuntimeError('尚缺真实前提,不能把候选改名成正式冻结')
        return
    train=[json.loads(line) for line in (ROOT/'manifests/online_pilot20k.candidate.jsonl').open()]
    dev=[json.loads(line) for line in (ROOT/'manifests/online_dev.candidate.jsonl').open()]
    from audit_eval_identity import audit as audit_identity
    identity_path,identity_audit=audit_identity()
    conflicts=set(overlap['training_eval_conflict_videos'])|set(identity_audit['known_parent_conflict_videos'])
    invalid=[row['id'] for row in train if row['source_video'] in conflicts]
    if invalid:
        atomic(ROOT/'provenance/required_joint_manifest_reselection.json',dict(reason='source_content_overlap_with_evaluation',
            videos=sorted(conflicts),QA_ids=invalid,selection_rule='recompute_same_seed17_legal_source_task_strata_after_exclusion; no_download_order_or_score_selection'))
        raise RuntimeError('训练候选存在评测内容冲突,必须按原确定性规则共同补齐20k,不能静默删题')
    # 开发池只作sanity/末epoch检查;对与训练共享内容的开发视频做整视频剔除,保留训练20k。
    dev_conflicts=set()
    for edge in overlap['train_dev_conflicts']:
        for side in ('left','right'):
            if edge[side]['split']=='dev':dev_conflicts.add(edge[side]['source_video'])
    dev=[row for row in dev if row['source_video'] not in conflicts|dev_conflicts]
    if {r['canonical_source'] for r in train}&{r['canonical_source'] for r in dev}:raise RuntimeError('规范化源ID跨train/dev')
    import torch
    # 读取每个视频一次,建立真实存在的帧与合法已闭合chunk关联,避免按caption时间强造QA定位。
    frame_sets={};chunks={};cache_hashes={};bank_hashes={}
    for video in videos:
        key=token(video);cache_path=ROOT/'data/frozen_causal_cache'/(key+'.pt');bank_path=ROOT/'data/change_banks'/(key+'.pt')
        cache=torch.load(cache_path,map_location='cpu',weights_only=False);bank=torch.load(bank_path,map_location='cpu',weights_only=False)
        if not cache['causal'] or not bank['writer_complete'] or bank['qa_or_answers_read']:raise RuntimeError('缓存因果/Writer独立性失败')
        frame_sets[video]={f['native_index'] for f in cache['frames']}
        observed=frame_sets[video]
        if not observed or observed!=set(range(max(observed)+1)):
            raise RuntimeError('公开1FPS前缀不连续/不是从0开始,不能假称完整前缀:'+video)
        chunks[video]=[dict(chunk_id=c['chunk_id'],frames=set(c['frame_ids']),committed_at=c['committed_at']) for c in cache['chunks'] if not c['terminal_flush']]
        cache_hashes[video]=sha(cache_path);bank_hashes[video]=sha(bank_path)
        if cache_hashes[video]!=bank['visual_cache_sha256']:raise RuntimeError('Writer使用了旧版视觉缓存')
    annotation_path=ROOT/'data/TimeChat-Online-139K/time_chat_online_139k_train_flt.jsonl'
    with annotation_path.open('rb') as annotations:
        for row in train+dev:
            annotations.seek(row['annotation_byte_offset']);raw=annotations.readline()
            if hashlib.sha256(raw).hexdigest()!=row['raw_line_sha256']:raise RuntimeError('QA偏移/hash变化')
            original=json.loads(raw)
            actual={int(Path(path).stem) for path in original['videos'][0]}
            if not actual<=frame_sets[row['source_video']]:raise RuntimeError('官方提供的QA图像不完整:'+row['id'])
            if max(actual)>row['query_time']+1e-6:raise RuntimeError('QA query_time早于官方提供的可见帧')
    train_videos={row['source_video'] for row in train};pairs=[];eligible=0;excluded=collections.Counter()
    caption_path=ROOT/'data/TimeChat-Online-139K/annotations_caption_flt.jsonl'
    for index,raw in enumerate(caption_path.open('rb'),1):
        caption=json.loads(raw);video=caption.get('video')
        if video not in train_videos:continue
        timestamp=float(caption['timestamp']);center=math.floor(timestamp)
        # caption不是精确轨迹GT;只接受±1帧量化邻域都在同一真实闭合chunk内的来源关联。
        neighborhood=set(range(max(0,center-1),math.ceil(timestamp)+2))
        matches=[c for c in chunks[video] if neighborhood<=c['frames']]
        if len(matches)!=1:excluded['ambiguous_or_missing_frame_chunk_association']+=1;continue
        chunk=matches[0];source_meta=videos[video]
        if timestamp>source_meta['max_query_time']:excluded['after_selected_source_prefix']+=1;continue
        digest=hashlib.sha256(raw).hexdigest();priority=int(hashlib.sha256(('17:S1:'+digest).encode()).hexdigest(),16)
        clean,sanitized=caption_text(caption['caption'],video)
        item=dict(id='aux-'+digest[:20],source_video=video,caption=clean,timestamp=timestamp,
                  caption_text_sanitization=sanitized,raw_caption_text_sha256=hashlib.sha256(caption['caption'].encode()).hexdigest(),
                  associated_frame_index=center,association_support_indices=sorted(neighborhood),
                  chunk_id=chunk['chunk_id'],chunk_committed_at=chunk['committed_at'],
                  cache_path=str(ROOT/'data/frozen_causal_cache'/(token(video)+'.pt')),
                  writer_bank_path=str(ROOT/'data/change_banks'/(token(video)+'.pt')),
                  raw_line_sha256=digest,annotation_line=index,caption_not_QA_evidence_ground_truth=True,
                  query_time_rule='candidate_source_prefix_end_independent_of_positive_caption_time')
        eligible+=1
        if len(pairs)<20000:heapq.heappush(pairs,(-priority,digest,item))
        elif priority<-pairs[0][0]:heapq.heapreplace(pairs,(-priority,digest,item))
    if len(pairs)<20000:
        atomic(ROOT/'provenance/auxiliary_association_insufficient.json',dict(eligible=eligible,excluded=dict(excluded),
            required=20000,action='jointly_refreeze_actual_auxiliary_budget_before_both_S1_runs; QA20k_unchanged'))
        raise RuntimeError('S1来源关联不足20k,不能伪造;需共同校准辅助预算')
    auxiliary=[item for _,_,item in sorted(pairs,key=lambda value:(-value[0],value[1]))]
    from audit_training_media import main as audit_media
    from prepare_evaluation_clusters import prepare as prepare_clusters
    audit_media()
    media_audit_path=ROOT/'provenance/training_media_prefix_audit.json'
    media_audit=json.loads(media_audit_path.read_text())
    if not media_audit['passed_on_available_sources'] or not media_audit['full_required_media_ready']:
        raise RuntimeError('完整实际媒体前缀/原QA图像核查尚未通过')
    cluster_path,cluster_audit=prepare_clusters()
    from audit_bootstrap_design import audit as audit_bootstrap
    design_path,design_audit=audit_bootstrap(cluster_path)
    if not design_audit['passed']:raise RuntimeError('完整统计重采样设计核查尚未通过')
    audit=dict(passed=True,qa_count=len(train),development_qa=len(dev),development_videos=len({r['source_video'] for r in dev}),
        exact_media_identity_audit_sha256=sha(identity_path),known_eval_parent_conflicts_in_final_train_dev=0,
        full_training_media_prefix_audit_sha256=sha(media_audit_path),
        evaluation_source_cluster_audit_sha256=sha(cluster_path),
        bootstrap_source_design_preflight_sha256=sha(design_path),
        actual_change_bank_audit_sha256=sha(bank_audit_path),
        removed_dev_content_conflict_videos=sorted(dev_conflicts),training_eval_conflicts=0,metadata_canonical_split_disjoint=True,
        content_overlap_report_sha256=sha(overlap_path),all_QA_supplied_frames_exist=True,causal_visual_caches=True,
        writer_no_QA_or_answers=True,auxiliary_pairs=len(auxiliary),auxiliary_source_eligible=eligible,auxiliary_excluded=dict(excluded),
        auxiliary_caption_sanitization_totals={key:sum(r['caption_text_sanitization'][key] for r in auxiliary)
            for key in ('source_ID_substitutions','clock_time_substitutions','metadata_value_substitutions')},
        cache_hashes=cache_hashes,bank_hashes=bank_hashes,time_semantics='official_1fps_frame_index_stream_with_original_clip_and_supplied_frame_endpoint_preserved',
        all_observed_source_frame_indices_contiguous_from_zero=True,
        QA_retimed_to_published_supplied_frame_endpoint=sum(r['supplied_max_frame_index']>r['annotation_end'] for r in train),
        training_time_boundary='公开JPEG的1FPS索引时钟;当提供图像超出metadata.end时延后训练提问到实际提供的末帧,不称为原metadata时刻的在线标注;原视频精确PTS未发布。评测仍用官方原视频精确截止。',
        caption_time_uncertainty='no_trajectory_GT; +/-1_frame_association_margin')
    if not args.apply:
        atomic(ROOT/'provenance/final_data_audit.proposed.json',audit);return
    for name,rows in [('online_pilot20k.frozen.jsonl',train),('online_dev.frozen.jsonl',dev),('auxiliary_caption20k.frozen.jsonl',auxiliary)]:
        target=ROOT/'manifests'/name
        if target.exists():raise FileExistsError('不得覆盖已有正式冻结清单:'+name)
        with target.open('w') as stream:
            for row in rows:stream.write(json.dumps(row,ensure_ascii=False)+'\n')
    atomic(ROOT/'provenance/final_data_audit.json',audit)
    budget=json.loads((ROOT/'configs/S1_budget.candidate.json').read_text());budget.update(status='frozen',
        caption_sanitization='cgvm/training_text.py: remove_exact_source_ID_numeric_clock_and_explicit_metadata_numeric_values; raw_line_hash_preserved',
        source_association='official_caption_timestamp_quantization_neighborhood_in_same_real_closed_chunk',
        auxiliary_manifest_sha256=sha(ROOT/'manifests/auxiliary_caption20k.frozen.jsonl'))
    atomic(ROOT/'configs/S1_budget.frozen.json',budget)
    atomic(ROOT/'provenance/training_frozen.sha256.json',{name:sha(ROOT/name) for name in [
        'manifests/online_pilot20k.frozen.jsonl','manifests/online_dev.frozen.jsonl','manifests/auxiliary_caption20k.frozen.jsonl','configs/S1_budget.frozen.json']})
    print('共同20k QA、独立开发池和S1 20k已按实际证据冻结',flush=True)


if __name__=='__main__':main()