File size: 8,387 Bytes
f947839
 
 
 
 
 
 
 
 
 
 
 
 
 
2139ef7
f947839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2139ef7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f947839
 
 
2139ef7
 
 
f947839
 
 
2139ef7
f947839
2139ef7
f947839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2139ef7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f947839
 
2139ef7
 
 
f947839
2139ef7
f947839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2139ef7
 
f947839
 
 
 
 
 
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
"""Archive evaluated checkpoints, verify remote bytes, then reclaim local storage.

The user explicitly authorized checkpoint retirement and deletion of previously
verified short-video evaluation MP4s. Active long-video restart points are protected.
Every removal has a durable per-file SHA256 and immutable remote revision receipt.
"""
import argparse
import hashlib
from pathlib import Path
import time

from huggingface_hub import HfApi, CommitOperationAdd
from huggingface_hub.hf_api import RepoFile
from scripts.causal_baselines_b200.common import REPO, ROOT, LONG, MODEL_REPO, read, write, sha
from scripts.vbench_b200.upload_hf_step80 import retry

STATE = REPO / 'reports/storage-archive-20261116/status.json'


def remote_matches(remote, path, digest):
    if remote is None or remote.size != path.stat().st_size:
        return False
    if remote.lfs:
        return remote.lfs.sha256 == digest
    blob = hashlib.sha1(f'blob {path.stat().st_size}\0'.encode() + path.read_bytes()).hexdigest()
    return remote.blob_id == blob


def api_client():
    api = HfApi(token=Path('/nfs/home/svu/e0833524/.cache/huggingface/token').read_text().strip())
    assert api.whoami()['name'] == 'yang29'
    return api


def archive_bundle(api, key, files, context, state):
    if state['bundles'].get(key, {}).get('stage') == 'retired':
        return
    item = state['bundles'].get(key)
    if not item or item.get('stage') != 'verified':
        available = [(name, Path(path)) for name, path in files if Path(path).is_file()]
        if not available:
            return
        inventory = [{'source': str(p), 'remote': f'{key}/{name}', 'bytes': p.stat().st_size,
                      'sha256': sha(p)} for name, p in available]
        operations = [CommitOperationAdd(r['remote'], r['source']) for r in inventory]
        import json
        operations.append(CommitOperationAdd(f'{key}/archive_provenance.json',
            json.dumps(dict(context=context, files=inventory), indent=2).encode()))
        commit = retry(f'Archive {key}', lambda: api.create_commit(MODEL_REPO, repo_type='model', operations=operations,
            commit_message=f'Archive evaluated {key}', num_threads=4))
        remote = {x.path: x for x in api.list_repo_tree(MODEL_REPO, path_in_repo=key,
            repo_type='model', revision=commit.oid, recursive=True) if isinstance(x, RepoFile)}
        for row in inventory:
            p = Path(row['source'])
            assert sha(p) == row['sha256'] and remote_matches(remote.get(row['remote']), p, row['sha256'])
        item = dict(stage='verified', repo_id=MODEL_REPO, revision=commit.oid,
            files=inventory, context=context, retired_bytes=0)
        state['bundles'][key] = item
        write(STATE, state)
    inventory = item['files']
    for row in inventory:
        p = Path(row['source'])
        # Recheck against the verified inventory immediately before removing.
        if p.exists():
            assert p.stat().st_size == row['bytes'] and sha(p) == row['sha256']
            p.unlink()
        row['deleted'] = True
        write(STATE, state)
    item['stage'] = 'retired'
    item['retired_bytes'] = sum(r['bytes'] for r in inventory)
    write(STATE, state)
    print({'archived': key, 'bytes_reclaimed': item['retired_bytes'], 'commit': item['revision']}, flush=True)


def old_short(api, state):
    for step in (80, 160):
        for method, runtime in [('astrolabe', 'afd_astrolabe_b200'), ('advdmd', 'afd_advdmd_b200')]:
            summary = read(REPO / f'.cache/hf_upload_step{step}/payload/results/{method}/summary.json')
            assert summary['checkpoint_step'] == step and not summary['smoke']
            base = Path('/hpctmp/e0833524') / runtime / 'runs/sf-gad200-vbench-aligned24-b4-ga3-lr2p5e6'
            if method == 'astrolabe':
                matches = list(base.glob(f'checkpoints_*/checkpoints/checkpoint-{step}'))
                if not matches:
                    continue
                directory = matches[0]
                files = [(str(p.relative_to(directory)), p) for p in directory.rglob('*') if p.is_file()]
                adapter = directory / 'lora/adapter_model.bin'
            else:
                adapter = base / f'checkpoints/step-{step}.pt'
                files = [(adapter.name, adapter)]
            if adapter.exists():
                assert sha(adapter) == summary['checkpoint_sha256']
            archive_bundle(api, f'short-self-forcing/{method}/step-{step:03d}', files,
                dict(method=method, step=step, evaluated_summary=summary, run_dir=str(base)), state)


def old_long(api, state):
    from scripts.long_vbench_b200.upload_hf import available_plans
    evaluation = LONG / 'evaluations/every10-vbenchlong100-20261114'
    for plan in available_plans(evaluation):
        if plan['method'] == 'base':
            continue
        p = Path(plan['checkpoint'])
        directory = Path(plan['run_dir'])
        full = sorted((directory/'checkpoints').glob('step-*.pt'), key=lambda x:int(x.stem[5:]))
        protected = {int(x.stem[5:]) for x in full[-2:]}
        if plan['checkpoint_step'] in protected:
            continue
        if p.exists():
            assert sha(p) == plan['checkpoint_sha256']
        archive_bundle(api, f"long-self-forcing/{plan['method']}/step-{plan['checkpoint_step']:03d}",
            [(p.name, p)], dict(plan=plan, active_restart_points_preserved=[str(x) for x in full[-2:]]), state)


def old_videos(api, state):
    for step in (80, 160):
        published = read(REPO / f'.cache/hf_upload_step{step}/state.json')
        assert published['stage'] == 'complete' and published['remote_checksums_verified']
        repo_id = published['repo_id']
        revision = api.repo_info(repo_id, repo_type='dataset').sha
        for method in ('astrolabe', 'advdmd'):
            key = f'old-short-videos/{step}/{method}'
            if state['videos'].get(key, {}).get('stage') == 'retired':
                continue
            plan = read(REPO / f'.cache/hf_upload_step{step}/payload/provenance/{method}/plan.json')
            directory = Path(plan['output_dir']) / 'videos'
            remote = {x.path: x for x in api.list_repo_tree(repo_id, repo_type='dataset', revision=revision,
                path_in_repo=f'data/{method}/videos', recursive=True) if isinstance(x, RepoFile)}
            item=state['videos'].get(key)
            if not item or item.get('stage')!='verified':
                from scripts.vbench_b200.common import records
                files = []
                for record in records(plan):
                    p=Path(record['video'])
                    if not p.exists():
                        continue
                    name = f'data/{method}/videos/{p.name}'
                    digest = sha(p)
                    assert remote_matches(remote.get(name), p, digest), f'Remote mismatch: {p}'
                    files.append(dict(source=str(p), remote=name, sha256=digest, bytes=p.stat().st_size))
                item = dict(stage='verified', repo_id=repo_id, revision=revision, files=files,
                    retired_bytes=0, expected_videos=plan['expected_videos'])
                state['videos'][key] = item
                write(STATE, state)
            files=item['files']
            for row in files:
                p = Path(row['source'])
                if p.exists():
                    assert sha(p) == row['sha256'] and p.stat().st_size == row['bytes']
                    p.unlink()
            item['stage'] = 'retired'
            item['retired_bytes']=sum(r['bytes'] for r in files)
            write(STATE, state)
            print({'retired_videos':key, 'bytes_reclaimed':item['retired_bytes']}, flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--checkpoints', action='store_true')
    parser.add_argument('--videos', action='store_true')
    args = parser.parse_args()
    state = read(STATE) if STATE.exists() else dict(bundles={}, videos={})
    api = api_client()
    if args.checkpoints:
        api.create_repo(MODEL_REPO, repo_type='model', exist_ok=True)
        old_short(api,state)
    if args.videos:
        old_videos(api,state)
    if args.checkpoints:
        old_long(api,state)
    state['updated_unix'] = time.time()
    write(STATE,state)


if __name__ == '__main__':
    main()