|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +"""Verify the synthetic layout benchmark without waiting for file inventory. |
| 3 | +
|
| 4 | +Regenerate each frame from its seed. This is deliberately specific to the fixture |
| 5 | +in ``arrayroute.benchmark``; it is not a verifier for arbitrary scientific data. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import argparse |
| 11 | +import hashlib |
| 12 | +import importlib.metadata |
| 13 | +import json |
| 14 | +import math |
| 15 | +import platform |
| 16 | +import time |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +import numpy as np |
| 20 | + |
| 21 | +from .backends import TensorStoreBackend, ZarrBackend, ZarristaBackend |
| 22 | +from .permutation import Permutation |
| 23 | +from .reader import ArrayReader, Backend |
| 24 | + |
| 25 | + |
| 26 | +def reference_frame(frame: int, edge: int) -> np.ndarray: |
| 27 | + rng = np.random.default_rng(83491 + frame) |
| 28 | + value = rng.standard_normal((edge, edge, edge, 3), dtype=np.float32) |
| 29 | + x = np.arange(edge, dtype=np.float32) / edge |
| 30 | + value *= np.float32(0.03) |
| 31 | + value += np.sin(x[:, None, None, None] * 12 + frame * 0.1) |
| 32 | + return value |
| 33 | + |
| 34 | + |
| 35 | +def digest(value: np.ndarray) -> str: |
| 36 | + return hashlib.sha256(memoryview(np.ascontiguousarray(value)).cast("B")).hexdigest() |
| 37 | + |
| 38 | + |
| 39 | +def open_backend(path: Path, engine: str) -> Backend: |
| 40 | + if engine == "zarr-python": |
| 41 | + import zarr |
| 42 | + |
| 43 | + return ZarrBackend(zarr.open_array(path, mode="r")) |
| 44 | + if engine == "zarrista": |
| 45 | + import zarrista |
| 46 | + |
| 47 | + return ZarristaBackend(zarrista.Array.open(zarrista.store.FilesystemStore(str(path)))) |
| 48 | + if engine == "tensorstore": |
| 49 | + import tensorstore as ts |
| 50 | + |
| 51 | + return TensorStoreBackend( |
| 52 | + ts.open( |
| 53 | + {"driver": "zarr3", "kvstore": {"driver": "file", "path": str(path) + "/"}}, |
| 54 | + read=True, |
| 55 | + context=ts.Context( |
| 56 | + { |
| 57 | + "cache_pool": {"total_bytes_limit": 0}, |
| 58 | + "data_copy_concurrency": {"limit": 8}, |
| 59 | + "file_io_concurrency": {"limit": 8}, |
| 60 | + } |
| 61 | + ), |
| 62 | + ).result() |
| 63 | + ) |
| 64 | + raise ValueError("Unknown engine") |
| 65 | + |
| 66 | + |
| 67 | +def scan( |
| 68 | + root: Path, |
| 69 | + output: Path, |
| 70 | + *, |
| 71 | + engine: str, |
| 72 | + layout: str = "sharded", |
| 73 | + deadline: float | None = None, |
| 74 | + limit: int | None = None, |
| 75 | +) -> dict: |
| 76 | + if layout not in {"frame", "brick", "sharded"}: |
| 77 | + raise ValueError("Unknown layout") |
| 78 | + if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or limit < 1): |
| 79 | + raise ValueError("limit must be a positive integer") |
| 80 | + if deadline is not None and not math.isfinite(deadline): |
| 81 | + raise ValueError("deadline must be finite") |
| 82 | + progress_bytes = (root / "progress.json").read_bytes() |
| 83 | + progress = json.loads(progress_bytes) |
| 84 | + backend = open_backend(root / f"{layout}.zarr", engine) |
| 85 | + shape = backend.spec.shape |
| 86 | + if ( |
| 87 | + len(shape) != 5 |
| 88 | + or shape[0] < 4 |
| 89 | + or shape[1] < 32 |
| 90 | + or shape[1] % 32 |
| 91 | + or shape[1:4] != (shape[1],) * 3 |
| 92 | + or shape[4] != 3 |
| 93 | + or backend.dtype != np.dtype("float32") |
| 94 | + or progress.get("frames_written") != shape[0] |
| 95 | + or progress.get("frames_total") != shape[0] |
| 96 | + or progress.get("logical_bytes_per_layout") != math.prod(shape) * 4 |
| 97 | + ): |
| 98 | + raise ValueError("Fixture is incomplete or does not match the synthetic generator") |
| 99 | + output.mkdir(parents=True, exist_ok=False) |
| 100 | + (output / "source-progress.json").write_bytes(progress_bytes) |
| 101 | + versions = {} |
| 102 | + for package in ("numpy", "zarr", "zarrista", "tensorstore", "arrayroute"): |
| 103 | + try: |
| 104 | + versions[package] = importlib.metadata.version(package) |
| 105 | + except importlib.metadata.PackageNotFoundError: |
| 106 | + pass |
| 107 | + report = { |
| 108 | + "engine": engine, |
| 109 | + "layout": layout, |
| 110 | + "shape": shape, |
| 111 | + "generator": "arrayroute-broadband-83491-v1", |
| 112 | + "order": {"algorithm": Permutation.algorithm, "seed": 991, "epoch": 0}, |
| 113 | + "state": "running", |
| 114 | + "complete": False, |
| 115 | + "frames_verified": 0, |
| 116 | + "verified_logical_bytes": 0, |
| 117 | + "read_seconds": 0.0, |
| 118 | + "reference_seconds": 0.0, |
| 119 | + "hash_seconds": 0.0, |
| 120 | + "started_at": time.time(), |
| 121 | + "deadline": deadline, |
| 122 | + "limit": limit, |
| 123 | + "versions": versions, |
| 124 | + "platform": platform.platform(), |
| 125 | + "cache_state": "OS uncontrolled; one traversal in seeded permuted order", |
| 126 | + "memory_policy": "One read frame and one regenerated reference; no dataset-sized index", |
| 127 | + "buffer_bytes": 256 << 20, |
| 128 | + } |
| 129 | + reader = ArrayReader(backend, buffer_bytes=256 << 20) |
| 130 | + started = time.perf_counter() |
| 131 | + |
| 132 | + def save() -> None: |
| 133 | + report["elapsed_seconds"] = time.perf_counter() - started |
| 134 | + temporary = output / "report.tmp" |
| 135 | + temporary.write_text(json.dumps(report, indent=2) + "\n") |
| 136 | + temporary.replace(output / "report.json") |
| 137 | + |
| 138 | + save() |
| 139 | + try: |
| 140 | + with (output / "frames.jsonl").open("x") as log: |
| 141 | + stop = min(shape[0], limit) if limit is not None else shape[0] |
| 142 | + for frame in Permutation(shape[0], seed=991).indices(stop=stop): |
| 143 | + if deadline is not None and time.time() >= deadline: |
| 144 | + report["state"] = "deadline" |
| 145 | + break |
| 146 | + start = time.perf_counter() |
| 147 | + value = reader.read((frame,) + (slice(None),) * 4) |
| 148 | + read_s = time.perf_counter() - start |
| 149 | + start = time.perf_counter() |
| 150 | + expected = reference_frame(frame, shape[1]) |
| 151 | + reference_s = time.perf_counter() - start |
| 152 | + start = time.perf_counter() |
| 153 | + expected_hash, actual_hash = digest(expected), digest(value) |
| 154 | + hash_s = time.perf_counter() - start |
| 155 | + valid = value.shape == expected.shape and value.dtype == expected.dtype |
| 156 | + valid = valid and actual_hash == expected_hash |
| 157 | + log.write(json.dumps({ |
| 158 | + "frame": frame, "bytes": value.nbytes, "read_s": read_s, |
| 159 | + "reference_s": reference_s, "hash_s": hash_s, |
| 160 | + "expected_sha256": expected_hash, "actual_sha256": actual_hash, |
| 161 | + "verified": valid, |
| 162 | + }) + "\n") |
| 163 | + log.flush() |
| 164 | + if not valid: |
| 165 | + raise ValueError(f"Frame {frame} differs from independently regenerated values") |
| 166 | + report["frames_verified"] += 1 |
| 167 | + report["verified_logical_bytes"] += value.nbytes |
| 168 | + report["read_seconds"] += read_s |
| 169 | + report["reference_seconds"] += reference_s |
| 170 | + report["hash_seconds"] += hash_s |
| 171 | + del value, expected |
| 172 | + if report["frames_verified"] % 32 == 0: |
| 173 | + save() |
| 174 | + else: |
| 175 | + report["complete"] = report["frames_verified"] == shape[0] |
| 176 | + report["state"] = "complete" if report["complete"] else "limited" |
| 177 | + except BaseException as exc: |
| 178 | + report["state"] = "failed" |
| 179 | + report["error"] = f"{type(exc).__name__}: {exc}" |
| 180 | + raise |
| 181 | + finally: |
| 182 | + report["finished_at"] = time.time() |
| 183 | + seconds = report["read_seconds"] |
| 184 | + report["read_GB_s"] = report["verified_logical_bytes"] / seconds / 1e9 if seconds else None |
| 185 | + save() |
| 186 | + return report |
| 187 | + |
| 188 | + |
| 189 | +def main() -> None: |
| 190 | + parser = argparse.ArgumentParser(description=__doc__) |
| 191 | + parser.add_argument("--root", type=Path, required=True) |
| 192 | + parser.add_argument("--output", type=Path, required=True) |
| 193 | + parser.add_argument( |
| 194 | + "--engine", choices=["zarr-python", "zarrista", "tensorstore"], required=True |
| 195 | + ) |
| 196 | + parser.add_argument("--layout", choices=["frame", "brick", "sharded"], default="sharded") |
| 197 | + parser.add_argument( |
| 198 | + "--deadline", type=float, help="Unix seconds; stop before starting a new frame" |
| 199 | + ) |
| 200 | + parser.add_argument( |
| 201 | + "--limit", type=int, help="Pilot only; never marks an incomplete scan complete" |
| 202 | + ) |
| 203 | + args = parser.parse_args() |
| 204 | + report = scan(**vars(args)) |
| 205 | + print(json.dumps(report, indent=2)) |
| 206 | + if report["state"] == "deadline": |
| 207 | + raise SystemExit(2) |
| 208 | + |
| 209 | + |
| 210 | +if __name__ == "__main__": |
| 211 | + main() |
0 commit comments