ylsung commited on
Commit
60c51d5
·
verified ·
1 Parent(s): d983c92

Add round-trip test

Browse files
Files changed (1) hide show
  1. test_restore_roundtrip.py +229 -0
test_restore_roundtrip.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ End-to-end test of the publish/restore round trip, at a size you can actually run.
4
+
5
+ Builds a miniature mirror of the real dataset out of the original archive, pushes
6
+ it to a throwaway *private* Hub repo, restores it with the plain documented
7
+ command, and checks the result against the archive. Then deletes the temp repo.
8
+
9
+ python tools/test_restore_roundtrip.py --zip VLadapter.zip --namespace ylsung
10
+
11
+ Why a temp repo rather than testing against the published dataset: the
12
+ completeness check inside restore_datasets.py only runs when --datasets,
13
+ --limit-shards and --only are all absent, i.e. only for the bare command, and
14
+ running that against the real repo means restoring ~132 GB. A small mirror
15
+ exercises the same code path in a couple of minutes.
16
+
17
+ Checks, in order:
18
+ 1. bare `restore_datasets.py --out ./datasets` succeeds and its own
19
+ manifest verification passes
20
+ 2. every restored .h5 is bit-exact vs the archive, read with the same access
21
+ pattern as VL-T5/src/*_clip_data.py (f[f"{img_id}/features"][...])
22
+ 3. every restored annotation is byte-identical
23
+ 4. directory shape matches, including the empty dirs the archive carries
24
+ 5. a second run is idempotent (downloads and rewrites nothing)
25
+ 6. deleting files mid-tree and rerunning restores exactly those
26
+ 7. the download cache is left ~empty (shards deleted after expanding)
27
+
28
+ Exits non-zero on the first failure. Pass --keep-repo to leave the temp repo for
29
+ inspection.
30
+ """
31
+ import argparse
32
+ import io
33
+ import shutil
34
+ import subprocess
35
+ import sys
36
+ import tempfile
37
+ import zipfile
38
+ from pathlib import Path
39
+
40
+ import h5py
41
+ import numpy as np
42
+
43
+ ROOT = "vlt5_dataset/"
44
+ TOOLS = Path(__file__).resolve().parent
45
+ FAILURES = []
46
+
47
+
48
+ def check(label, ok, detail=""):
49
+ print(f" {'PASS' if ok else 'FAIL'} {label}" + (f" — {detail}" if detail else ""))
50
+ if not ok:
51
+ FAILURES.append(label)
52
+ return ok
53
+
54
+
55
+ def run(cmd, **kw):
56
+ return subprocess.run(cmd, capture_output=True, text=True, **kw)
57
+
58
+
59
+ def build_mini(src_zip, dest_zip, per_dataset, ann_max_bytes):
60
+ """A small archive shaped like the real one: features + annotations, no images."""
61
+ src = zipfile.ZipFile(src_zip)
62
+ feats, others, dirs = {}, [], []
63
+ for info in src.infolist():
64
+ name = info.filename
65
+ if name.endswith("/"):
66
+ dirs.append(info)
67
+ continue
68
+ rel = name[len(ROOT):]
69
+ if "/clip_features/" in rel and rel.endswith(".h5"):
70
+ feats.setdefault(rel.split("/")[0], []).append(info)
71
+ elif rel.startswith("nlvr/images/"):
72
+ continue # the published dataset ships no images; mirror that
73
+ elif info.file_size <= ann_max_bytes:
74
+ others.append(info)
75
+ picked = list(dirs) + others
76
+ for group in feats.values():
77
+ picked += group[:per_dataset]
78
+ with zipfile.ZipFile(dest_zip, "w", zipfile.ZIP_DEFLATED) as out:
79
+ for info in picked:
80
+ if info.filename.endswith("/"):
81
+ out.writestr(zipfile.ZipInfo(info.filename), b"")
82
+ else:
83
+ out.writestr(info, src.read(info))
84
+ return dest_zip
85
+
86
+
87
+ def compare_tree(mini_zip, tree):
88
+ """Bit-exactness of features, byte-exactness of everything else."""
89
+ z = zipfile.ZipFile(mini_zip)
90
+ n_h5 = n_other = bad = missing = 0
91
+ for info in z.infolist():
92
+ if info.filename.endswith("/"):
93
+ continue
94
+ rel = info.filename[len(ROOT):]
95
+ dest = tree / rel
96
+ if not dest.exists():
97
+ missing += 1
98
+ continue
99
+ orig = z.read(info)
100
+ if rel.endswith(".h5"):
101
+ stem = Path(rel).stem
102
+ with h5py.File(io.BytesIO(orig), "r") as fh:
103
+ ref = fh[f"{stem}/features"][...]
104
+ with h5py.File(dest, "r") as fh: # the loaders' access pattern
105
+ got = fh[f"{stem}/features"][...]
106
+ if not (got.shape == ref.shape == (49, 2048)
107
+ and got.dtype == ref.dtype == np.float16
108
+ and np.array_equal(got, ref)):
109
+ bad += 1
110
+ n_h5 += 1
111
+ else:
112
+ if dest.read_bytes() != orig:
113
+ bad += 1
114
+ n_other += 1
115
+ return n_h5, n_other, bad, missing
116
+
117
+
118
+ def main():
119
+ p = argparse.ArgumentParser(description=__doc__,
120
+ formatter_class=argparse.RawDescriptionHelpFormatter)
121
+ p.add_argument("--zip", required=True, help="the original VLadapter.zip")
122
+ p.add_argument("--namespace", required=True, help="Hub user or org for the temp repo")
123
+ p.add_argument("--repo-name", default="vladapter-restore-smoketest")
124
+ p.add_argument("--per-dataset", type=int, default=200, help="h5 files per dataset")
125
+ p.add_argument("--shard-rows", type=int, default=64)
126
+ p.add_argument("--ann-max-bytes", type=int, default=2_500_000,
127
+ help="skip annotations larger than this, to keep the test quick")
128
+ p.add_argument("--keep-repo", action="store_true")
129
+ p.add_argument("--workdir", default=None)
130
+ args = p.parse_args()
131
+
132
+ from huggingface_hub import HfApi
133
+
134
+ repo_id = f"{args.namespace}/{args.repo_name}"
135
+ work = Path(args.workdir or tempfile.mkdtemp(prefix="vladapter-test-"))
136
+ work.mkdir(parents=True, exist_ok=True)
137
+ api = HfApi()
138
+ py = sys.executable
139
+ print(f"workdir : {work}\ntemp repo: {repo_id} (private)\n")
140
+
141
+ try:
142
+ print("[1/7] building miniature archive")
143
+ mini = build_mini(args.zip, work / "mini.zip", args.per_dataset, args.ann_max_bytes)
144
+ print(f" {mini.stat().st_size/1e6:.1f} MB")
145
+
146
+ print("[2/7] converting to the Hub layout")
147
+ staging = work / "hf"
148
+ r = run([py, str(TOOLS / "convert_zip_to_hf.py"), "--zip", str(mini),
149
+ "--out", str(staging), "--shard-rows", str(args.shard_rows),
150
+ "--only", "annotations", "--only", "features"])
151
+ if r.returncode:
152
+ print(r.stdout[-2000:], r.stderr[-2000:])
153
+ return check("convert", False, "see output above") or 1
154
+ shards = list(staging.rglob("*.parquet"))
155
+ print(f" {len(shards)} shards")
156
+
157
+ print("[3/7] pushing the mirror to a private temp repo")
158
+ api.create_repo(repo_id, repo_type="dataset", private=True, exist_ok=True)
159
+ api.upload_folder(folder_path=str(staging), repo_id=repo_id, repo_type="dataset",
160
+ ignore_patterns=[".convert_state*", "*.tmp"],
161
+ commit_message="Miniature mirror for restore testing")
162
+
163
+ print("[4/7] bare restore: restore_datasets.py --out ./datasets")
164
+ tree = work / "datasets"
165
+ r = run([py, str(TOOLS / "restore_datasets.py"), "--out", str(tree),
166
+ "--repo-id", repo_id])
167
+ out = r.stdout + r.stderr
168
+ check("bare command exits 0", r.returncode == 0)
169
+ check("manifest verification ran and passed",
170
+ "missing=0, size-mismatch=0, crc-mismatch=0" in out,
171
+ next((l.strip() for l in out.splitlines() if "[verify]" in l), "no [verify] line"))
172
+
173
+ print("[5/7] comparing the restored tree against the archive")
174
+ n_h5, n_other, bad, missing = compare_tree(mini, tree)
175
+ check("every .h5 bit-exact", bad == 0 and missing == 0,
176
+ f"{n_h5} h5 + {n_other} annotations, {bad} mismatched, {missing} missing")
177
+
178
+ for rel in ["paragraphs", "COCO/clip_features/data_clip_RN101_fc", "nlvr/images"]:
179
+ check(f"empty dir preserved: {rel}", (tree / rel).is_dir())
180
+ for ds in ["COCO", "GQA", "VG", "nlvr"]:
181
+ d = tree / ds / "clip_features" / "data_clip_RN101_att"
182
+ check(f"loader path exists: {ds}", d.is_dir() and any(d.glob("*.h5")),
183
+ f"{len(list(d.glob('*.h5')))} .h5")
184
+
185
+ print("[6/7] second run must be idempotent")
186
+ r2 = run([py, str(TOOLS / "restore_datasets.py"), "--out", str(tree),
187
+ "--repo-id", repo_id])
188
+ o2 = r2.stdout + r2.stderr
189
+ check("nothing rewritten on rerun", "h5 written" not in o2,
190
+ f"{o2.count('already restored')} shards skipped")
191
+
192
+ print("[7/7] resume after a simulated interruption")
193
+ gqa = sorted((tree / "GQA/clip_features/data_clip_RN101_att").glob("*.h5"))
194
+ removed = gqa[: args.shard_rows]
195
+ for f in removed:
196
+ f.unlink()
197
+ (tree / "nlvr/test.json").unlink(missing_ok=True)
198
+ r3 = run([py, str(TOOLS / "restore_datasets.py"), "--out", str(tree),
199
+ "--repo-id", repo_id])
200
+ rewritten = sum(int(l.split(":")[-1].split("/")[0].strip())
201
+ for l in (r3.stdout + r3.stderr).splitlines() if "h5 written" in l)
202
+ check("resume rewrote exactly the deleted files", rewritten == len(removed),
203
+ f"deleted {len(removed)}, rewrote {rewritten}")
204
+ check("deleted annotation restored", (tree / "nlvr/test.json").exists())
205
+
206
+ cache = Path.home() / ".cache/huggingface/hub"
207
+ size = sum(f.stat().st_size for f in cache.rglob("*") if f.is_file()) if cache.exists() else 0
208
+ check("download cache left ~empty", size < 50e6, f"{size/1e6:.1f} MB")
209
+
210
+ finally:
211
+ if not args.keep_repo:
212
+ try:
213
+ api.delete_repo(repo_id, repo_type="dataset")
214
+ print(f"\ncleaned up {repo_id}")
215
+ except Exception as exc: # noqa: BLE001
216
+ print(f"\ncould not delete {repo_id}: {exc}")
217
+ if not args.workdir:
218
+ shutil.rmtree(work, ignore_errors=True)
219
+
220
+ print()
221
+ if FAILURES:
222
+ print(f"FAILED ({len(FAILURES)}): " + "; ".join(FAILURES))
223
+ return 1
224
+ print("ALL CHECKS PASSED")
225
+ return 0
226
+
227
+
228
+ if __name__ == "__main__":
229
+ sys.exit(main())