data-loader commited on
Commit
73feb3c
·
verified ·
1 Parent(s): aca3a4b

Add portable SimLingo post-train buckets: restore.py

Browse files
Files changed (1) hide show
  1. restore.py +141 -0
restore.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Restore the trusted SimLingo bucket snapshot for a new data location (Python >=3.8)."""
3
+ import argparse
4
+ import gzip
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import pickle
9
+ import shutil
10
+ import tarfile
11
+ import tempfile
12
+ from pathlib import Path
13
+
14
+ TOKEN = '__SIMLINGO_DATA_ROOT__'
15
+ CACHE = 'BUCKET2DATA_remove_missing_dream_jianing.pkl'
16
+ INDEX = 'bucketsv2_simlingo/buckets_paths.pkl'
17
+ FIELDS = ('images', 'boxes', 'measurements', 'alternative_trajectories')
18
+
19
+
20
+ def sha256(path):
21
+ h = hashlib.sha256()
22
+ with Path(path).open('rb') as f:
23
+ for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
24
+ h.update(block)
25
+ return h.hexdigest()
26
+
27
+
28
+ def rewrite_cache(cache, old, new):
29
+ """Rewrite path leaves only; keep scalar values, container types and aliasing."""
30
+ memo = {}
31
+ count = 0
32
+
33
+ def walk(value):
34
+ nonlocal count
35
+ ident = id(value)
36
+ if ident in memo:
37
+ return memo[ident][1]
38
+ if type(value) is str:
39
+ if not value.startswith(old + '/'):
40
+ raise ValueError('Unexpected cache path prefix; refusing a partial rewrite')
41
+ out = new + value[len(old):]
42
+ count += 1
43
+ elif type(value) is list:
44
+ out = []
45
+ memo[ident] = (value, out)
46
+ out.extend(walk(x) for x in value)
47
+ elif type(value) is tuple:
48
+ out = tuple(walk(x) for x in value)
49
+ else:
50
+ raise TypeError('Unexpected path container: ' + type(value).__name__)
51
+ memo[ident] = (value, out)
52
+ return out
53
+
54
+ for buckets in cache.values():
55
+ for bucket in buckets.values():
56
+ for field in FIELDS:
57
+ if field in bucket:
58
+ bucket[field] = walk(bucket[field])
59
+ return count
60
+
61
+
62
+ def check_data(root, probes):
63
+ from PIL import Image
64
+ for item in probes:
65
+ path = root / item['path']
66
+ if not path.is_file():
67
+ raise FileNotFoundError(str(path))
68
+ if item['kind'] == 'image':
69
+ with Image.open(str(path)) as im:
70
+ im.verify()
71
+ else:
72
+ with gzip.open(str(path), 'rt') as f:
73
+ data = json.load(f)
74
+ if item['kind'] == 'commentary':
75
+ assert 'commentary' in data
76
+ elif item['kind'] == 'vqa':
77
+ assert data.get('QA')
78
+ elif item['kind'] == 'dreamer':
79
+ assert any(v for k, v in data.items() if 'factor' not in k)
80
+ return len(probes)
81
+
82
+
83
+ def main():
84
+ parser = argparse.ArgumentParser(description=__doc__)
85
+ parser.add_argument('--database-root', type=Path, required=True,
86
+ help='Resource directory containing simlingo_v2_2025_01_10/')
87
+ parser.add_argument('--bundle-dir', type=Path, default=Path(__file__).resolve().parent)
88
+ parser.add_argument('--check-data', action='store_true', help='Decode representative real samples before writing')
89
+ args = parser.parse_args()
90
+ bundle = args.bundle_dir.resolve()
91
+ db = args.database_root.resolve()
92
+ data = (db / 'simlingo_v2_2025_01_10').resolve()
93
+ if args.check_data:
94
+ probes = json.loads((bundle / 'sample-probes.json').read_text())
95
+ print('Verified real data files:', check_data(data, probes), flush=True)
96
+ targets = (db / CACHE, db / INDEX)
97
+ for target in targets:
98
+ if target.exists() or target.is_symlink():
99
+ raise FileExistsError('Refusing to overwrite ' + str(target))
100
+ manifest = json.loads((bundle / 'manifest.json').read_text())
101
+ archive = bundle / manifest['archive']['path']
102
+ assert archive.stat().st_size == manifest['archive']['bytes']
103
+ assert sha256(archive) == manifest['archive']['sha256'], 'Archive checksum mismatch'
104
+ db.mkdir(parents=True, exist_ok=True)
105
+ with tempfile.TemporaryDirectory(prefix='.restore-buckets-', dir=str(db)) as temp:
106
+ temp = Path(temp)
107
+ expected = {x['path']: x for x in manifest['payload']}
108
+ with tarfile.open(str(archive), 'r:gz') as tar:
109
+ members = tar.getmembers()
110
+ assert len(members) == len(expected)
111
+ assert {x.name for x in members} == set(expected)
112
+ for member in members:
113
+ assert member.isfile() and member.size == expected[member.name]['bytes']
114
+ target = temp / member.name
115
+ target.parent.mkdir(parents=True, exist_ok=True)
116
+ with tar.extractfile(member) as src, target.open('wb') as dst:
117
+ shutil.copyfileobj(src, dst, 8 * 1024 * 1024)
118
+ assert sha256(target) == expected[member.name]['sha256']
119
+ print('Loading portable cache; this may take a few minutes.', flush=True)
120
+ with (temp / 'BUCKET2DATA.portable.pkl').open('rb') as f:
121
+ cache = pickle.load(f)
122
+ rewritten = rewrite_cache(cache, TOKEN, str(data))
123
+ staged_cache = temp / CACHE
124
+ with staged_cache.open('wb') as f:
125
+ pickle.dump(cache, f, protocol=4)
126
+ targets[1].parent.mkdir(parents=True, exist_ok=True)
127
+ # Hard links fail atomically if another process has created either target.
128
+ os.link(str(staged_cache), str(targets[0]))
129
+ try:
130
+ os.link(str(temp / INDEX), str(targets[1]))
131
+ except BaseException:
132
+ targets[0].unlink()
133
+ raise
134
+ report = {'ok': True, 'data_root': str(data), 'rewritten_unique_path_objects': rewritten,
135
+ 'cache': str(targets[0]), 'bucket_index': str(targets[1]),
136
+ 'sample_counts': manifest['sample_counts'], 'real_samples_checked': args.check_data}
137
+ print(json.dumps(report, indent=2))
138
+
139
+
140
+ if __name__ == '__main__':
141
+ main()