Download convert_assets.py from Passenger555/DatasetDistillationCollection: direct link, hf CLI and curl.
- Browser
- Download file 24.4 kB
-
https://huggingface.co/datasets/Passenger555/DatasetDistillationCollection/resolve/main/convert_assets.py
- Command line
-
hf download hf://datasets/Passenger555/DatasetDistillationCollection/convert_assets.py
-
curl -L -o convert_assets.py https://huggingface.co/datasets/Passenger555/DatasetDistillationCollection/resolve/main/convert_assets.py
24.4 kB
| #!/usr/bin/env python3 | |
| """Convert DataDistillBed image folders and selected ResNet teachers to Parquet. | |
| The conversion is byte-preserving: compressed image bytes and checkpoint bytes are | |
| stored directly in binary Parquet columns. The script validates the exact physical | |
| image counts found during the archive audit and records SHA-256 digests for every | |
| payload and output shard. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import collections | |
| import datetime as dt | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import tarfile | |
| from pathlib import Path, PurePosixPath | |
| from typing import Any, Iterable | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| DATASET_ALIASES = { | |
| "cifar10": "CIFAR-10", | |
| "cifar100": "CIFAR-100", | |
| "tiny": "TinyImageNet-200", | |
| "imagenette": "ImageNette", | |
| "imagenette128": "ImageNette", | |
| "imagenet": "ImageNet-1K", | |
| } | |
| NUM_CLASSES = { | |
| "CIFAR-10": 10, | |
| "CIFAR-100": 100, | |
| "TinyImageNet-200": 200, | |
| "ImageNette": 10, | |
| "ImageNet-1K": 1000, | |
| } | |
| STANDARD_GROUPS = { | |
| "DC": {"CIFAR-10": (1, 10, 50), "CIFAR-100": (1, 10, 50)}, | |
| "DM": {"CIFAR-10": (1, 10, 50), "CIFAR-100": (1, 10, 50)}, | |
| "DSA": {"CIFAR-10": (1, 10, 50), "CIFAR-100": (1, 10, 50)}, | |
| "ATT": { | |
| "CIFAR-10": (1, 10, 50), | |
| "CIFAR-100": (1, 10, 50), | |
| "TinyImageNet-200": (1, 10, 50), | |
| "ImageNette": (1, 10), | |
| }, | |
| "MTT": { | |
| "CIFAR-10": (1, 10, 50), | |
| "CIFAR-100": (1, 10, 50), | |
| "TinyImageNet-200": (1, 10, 50), | |
| "ImageNette": (1, 10), | |
| }, | |
| "TESLA": { | |
| "CIFAR-10": (1, 10, 50), | |
| "CIFAR-100": (1, 10, 50), | |
| "TinyImageNet-200": (1, 10, 50), | |
| "ImageNette": (1, 10), | |
| }, | |
| "CVDD": { | |
| "CIFAR-10": (1, 10, 50), | |
| "CIFAR-100": (1, 10, 50), | |
| "TinyImageNet-200": (1, 10, 50), | |
| "ImageNette": (1, 10, 50), | |
| "ImageNet-1K": (1, 10, 50), | |
| }, | |
| "GVBSM": { | |
| "CIFAR-10": (1, 10, 50), | |
| "CIFAR-100": (1, 10, 50), | |
| "TinyImageNet-200": (1, 10, 50), | |
| "ImageNet-1K": (1, 10, 50), | |
| }, | |
| "SCDD": {"CIFAR-10": (1, 10, 50), "CIFAR-100": (1, 10, 50)}, | |
| "SRe2L": { | |
| "TinyImageNet-200": (1, 10, 50), | |
| "ImageNet-1K": (1, 10, 50), | |
| }, | |
| "WMDD": { | |
| "TinyImageNet-200": (1, 10, 50), | |
| "ImageNette": (10, 50), | |
| "ImageNet-1K": (1, 10, 50), | |
| }, | |
| } | |
| FRED_COUNTS = { | |
| ("CIFAR-10", 1): 160, | |
| ("CIFAR-10", 10): 640, | |
| ("CIFAR-10", 50): 2000, | |
| ("CIFAR-100", 1): 800, | |
| ("CIFAR-100", 10): 1000, | |
| ("CIFAR-100", 50): 5000, | |
| ("TinyImageNet-200", 1): 1600, | |
| ("ImageNette", 1): 80, | |
| ("ImageNette", 10): 400, | |
| } | |
| NCFM_GROUPS = { | |
| "CIFAR-10": (1, 10, 50), | |
| "CIFAR-100": (1, 10, 50), | |
| "TinyImageNet-200": (1, 10, 50), | |
| "ImageNette": (1, 10, 50), | |
| } | |
| TEACHERS = { | |
| "other_pretrained_models/CVDD/cifar10/ResNet18.pth": { | |
| "provider": "CVDD", | |
| "dataset": "CIFAR-10", | |
| "architecture": "ResNet18", | |
| "used_by": ["CVDD"], | |
| }, | |
| "other_pretrained_models/CVDD/cifar100/ResNet18.pth": { | |
| "provider": "CVDD", | |
| "dataset": "CIFAR-100", | |
| "architecture": "ResNet18", | |
| "used_by": ["CVDD"], | |
| }, | |
| "other_pretrained_models/GVBSM/CIFAR-10/ResNet18/squeeze_ResNet18.pth": { | |
| "provider": "GVBSM", | |
| "dataset": "CIFAR-10", | |
| "architecture": "ResNet18", | |
| "used_by": ["GVBSM"], | |
| }, | |
| "other_pretrained_models/GVBSM/CIFAR-100/ResNet18/squeeze_ResNet18.pth": { | |
| "provider": "GVBSM", | |
| "dataset": "CIFAR-100", | |
| "architecture": "ResNet18", | |
| "used_by": ["GVBSM"], | |
| }, | |
| "other_pretrained_models/WMDD/tiny-imagenet_model_49.pth": { | |
| "provider": "WMDD", | |
| "dataset": "TinyImageNet-200", | |
| "architecture": "ResNet18", | |
| "used_by": ["WMDD"], | |
| }, | |
| "other_pretrained_models/WMDD/imagenette_model_49.pth": { | |
| "provider": "WMDD", | |
| "dataset": "ImageNette", | |
| "architecture": "ResNet18", | |
| "used_by": ["WMDD"], | |
| }, | |
| } | |
| MISSING_TEACHERS = [ | |
| "other_pretrained_models/GVBSM/tiny/ResNet18/squeeze_ResNet18.pth", | |
| "other_pretrained_models/SRe2L/cifar10/ckpt.pth", | |
| "other_pretrained_models/SRe2L/cifar100/ckpt.pth", | |
| "torchvision official ResNet-18 checkpoint (runtime dependency)", | |
| ] | |
| IMAGE_SCHEMA = pa.schema( | |
| [ | |
| pa.field("method", pa.string(), nullable=False), | |
| pa.field("dataset", pa.string(), nullable=False), | |
| pa.field("ipc", pa.int32(), nullable=False), | |
| pa.field("class_id", pa.int32(), nullable=False), | |
| pa.field("image_id", pa.int32(), nullable=False), | |
| pa.field("source_path", pa.string(), nullable=False), | |
| pa.field("extension", pa.string(), nullable=False), | |
| pa.field( | |
| "image", | |
| pa.struct( | |
| [ | |
| pa.field("bytes", pa.binary(), nullable=False), | |
| pa.field("path", pa.string(), nullable=False), | |
| ] | |
| ), | |
| nullable=False, | |
| ), | |
| pa.field("sample_weight", pa.float64()), | |
| pa.field("sha256", pa.string(), nullable=False), | |
| pa.field("byte_size", pa.int64(), nullable=False), | |
| pa.field("source_archive", pa.string(), nullable=False), | |
| ] | |
| ) | |
| TEACHER_SCHEMA = pa.schema( | |
| [ | |
| pa.field("provider", pa.string(), nullable=False), | |
| pa.field("dataset", pa.string(), nullable=False), | |
| pa.field("architecture", pa.string(), nullable=False), | |
| pa.field("used_by", pa.list_(pa.string()), nullable=False), | |
| pa.field("source_path", pa.string(), nullable=False), | |
| pa.field("checkpoint", pa.binary(), nullable=False), | |
| pa.field("sha256", pa.string(), nullable=False), | |
| pa.field("byte_size", pa.int64(), nullable=False), | |
| pa.field("source_archive", pa.string(), nullable=False), | |
| ] | |
| ) | |
| SHARD_SCHEMA = pa.schema( | |
| [ | |
| pa.field("asset_type", pa.string(), nullable=False), | |
| pa.field("relative_path", pa.string(), nullable=False), | |
| pa.field("method_or_provider", pa.string(), nullable=False), | |
| pa.field("row_count", pa.int64(), nullable=False), | |
| pa.field("payload_bytes", pa.int64(), nullable=False), | |
| pa.field("parquet_bytes", pa.int64(), nullable=False), | |
| pa.field("sha256", pa.string(), nullable=False), | |
| ] | |
| ) | |
| def sha256_file(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| while chunk := handle.read(chunk_size): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def normalized_tar_path(name: str) -> str: | |
| value = name.replace("\\", "/") | |
| while value.startswith("./"): | |
| value = value[2:] | |
| return value | |
| def parse_image_path(name: str) -> tuple[str, int, int, int, str]: | |
| normalized = normalized_tar_path(name) | |
| parts = PurePosixPath(normalized).parts | |
| dataset = next( | |
| (DATASET_ALIASES[p.lower()] for p in parts if p.lower() in DATASET_ALIASES), | |
| None, | |
| ) | |
| ipc_token = next((p for p in parts if re.fullmatch(r"ipc\d+", p.lower())), None) | |
| class_token = next((p for p in parts if re.fullmatch(r"new\d+", p.lower())), None) | |
| if dataset is None or ipc_token is None or class_token is None: | |
| raise ValueError(f"Cannot parse dataset/ipc/class from {normalized!r}") | |
| ipc = int(ipc_token[3:]) | |
| class_id = int(class_token[3:]) | |
| filename = parts[-1] | |
| explicit = re.search(r"class(\d+)_id(\d+)", filename, flags=re.IGNORECASE) | |
| generic = re.search(r"image_(\d+)", filename, flags=re.IGNORECASE) | |
| if explicit: | |
| filename_class = int(explicit.group(1)) | |
| if filename_class != class_id: | |
| raise ValueError( | |
| f"Directory class {class_id} disagrees with filename class " | |
| f"{filename_class}: {normalized}" | |
| ) | |
| image_id = int(explicit.group(2)) | |
| elif generic: | |
| image_id = int(generic.group(1)) | |
| else: | |
| raise ValueError(f"Cannot parse image id from {normalized!r}") | |
| extension = Path(filename).suffix.lower() | |
| if extension not in {".jpg", ".jpeg", ".png"}: | |
| raise ValueError(f"Unsupported image extension in {normalized!r}") | |
| return dataset, ipc, class_id, image_id, extension | |
| def expected_physical_counts() -> dict[tuple[str, str, int], int]: | |
| result: dict[tuple[str, str, int], int] = {} | |
| for method, datasets in STANDARD_GROUPS.items(): | |
| for dataset, ipcs in datasets.items(): | |
| for ipc in ipcs: | |
| result[(method, dataset, ipc)] = NUM_CLASSES[dataset] * ipc | |
| for (dataset, ipc), count in FRED_COUNTS.items(): | |
| result[("FreD", dataset, ipc)] = count | |
| for dataset, ipcs in NCFM_GROUPS.items(): | |
| for ipc in ipcs: | |
| result[("NCFM", dataset, ipc)] = NUM_CLASSES[dataset] * ipc * 4 | |
| return result | |
| def load_wmdd_weights(archive: Path) -> dict[tuple[str, int], list[list[float]]]: | |
| result: dict[tuple[str, int], list[list[float]]] = {} | |
| with tarfile.open(archive, "r:gz") as tf: | |
| for member in tf: | |
| if not member.isfile() or not member.name.endswith("sample_weights.txt"): | |
| continue | |
| dataset, ipc, _, _, _ = parse_weight_path(member.name) | |
| extracted = tf.extractfile(member) | |
| if extracted is None: | |
| raise RuntimeError(f"Cannot extract {member.name}") | |
| lines = extracted.read().decode("utf-8").splitlines() | |
| matrix = [[float(value) for value in line.split()] for line in lines] | |
| if len(matrix) != NUM_CLASSES[dataset]: | |
| raise ValueError(f"Wrong class count in {member.name}: {len(matrix)}") | |
| if any(len(row) != ipc for row in matrix): | |
| raise ValueError(f"Wrong IPC width in {member.name}") | |
| result[(dataset, ipc)] = matrix | |
| return result | |
| def parse_weight_path(name: str) -> tuple[str, int, int, int, str]: | |
| normalized = normalized_tar_path(name) | |
| parts = PurePosixPath(normalized).parts | |
| dataset = next( | |
| (DATASET_ALIASES[p.lower()] for p in parts if p.lower() in DATASET_ALIASES), | |
| None, | |
| ) | |
| ipc_token = next((p for p in parts if re.fullmatch(r"ipc\d+", p.lower())), None) | |
| if dataset is None or ipc_token is None: | |
| raise ValueError(f"Cannot parse WMDD weight path {normalized!r}") | |
| return dataset, int(ipc_token[3:]), 0, 0, ".txt" | |
| class ImageShardWriter: | |
| def __init__(self, root: Path, method: str, target_bytes: int, batch_size: int): | |
| self.root = root | |
| self.method = method | |
| self.target_bytes = target_bytes | |
| self.batch_size = batch_size | |
| self.shard_index = -1 | |
| self.writer: pq.ParquetWriter | None = None | |
| self.path: Path | None = None | |
| self.rows: list[dict[str, Any]] = [] | |
| self.rows_in_shard = 0 | |
| self.payload_in_shard = 0 | |
| self.records: list[dict[str, Any]] = [] | |
| def _open(self) -> None: | |
| self.shard_index += 1 | |
| directory = self.root / "data" / "images" / self.method | |
| directory.mkdir(parents=True, exist_ok=True) | |
| self.path = directory / f"train-{self.shard_index:05d}.parquet" | |
| if self.path.exists(): | |
| raise FileExistsError(f"Refusing to overwrite {self.path}") | |
| self.writer = pq.ParquetWriter( | |
| self.path, | |
| IMAGE_SCHEMA, | |
| compression="zstd", | |
| compression_level=3, | |
| use_dictionary=["method", "dataset", "extension", "source_archive"], | |
| write_statistics=[ | |
| "method", | |
| "dataset", | |
| "ipc", | |
| "class_id", | |
| "image_id", | |
| "sample_weight", | |
| "byte_size", | |
| ], | |
| data_page_size=1024 * 1024, | |
| ) | |
| def _flush_rows(self) -> None: | |
| if not self.rows: | |
| return | |
| assert self.writer is not None | |
| table = pa.Table.from_pylist(self.rows, schema=IMAGE_SCHEMA) | |
| self.writer.write_table(table, row_group_size=self.batch_size) | |
| self.rows.clear() | |
| def _close(self) -> None: | |
| if self.writer is None or self.path is None: | |
| return | |
| self._flush_rows() | |
| self.writer.close() | |
| parquet_file = pq.ParquetFile(self.path) | |
| if parquet_file.metadata.num_rows != self.rows_in_shard: | |
| raise RuntimeError(f"Row-count mismatch in {self.path}") | |
| self.records.append( | |
| { | |
| "asset_type": "image", | |
| "relative_path": self.path.relative_to(self.root).as_posix(), | |
| "method_or_provider": self.method, | |
| "row_count": self.rows_in_shard, | |
| "payload_bytes": self.payload_in_shard, | |
| "parquet_bytes": self.path.stat().st_size, | |
| "sha256": sha256_file(self.path), | |
| } | |
| ) | |
| self.writer = None | |
| self.path = None | |
| self.rows_in_shard = 0 | |
| self.payload_in_shard = 0 | |
| def append(self, row: dict[str, Any]) -> None: | |
| payload_size = int(row["byte_size"]) | |
| if self.writer is None: | |
| self._open() | |
| elif self.rows_in_shard and self.payload_in_shard + payload_size > self.target_bytes: | |
| self._close() | |
| self._open() | |
| self.rows.append(row) | |
| self.rows_in_shard += 1 | |
| self.payload_in_shard += payload_size | |
| if len(self.rows) >= self.batch_size: | |
| self._flush_rows() | |
| def close(self) -> list[dict[str, Any]]: | |
| self._close() | |
| return self.records | |
| def convert_images( | |
| inner_root: Path, output_root: Path, target_bytes: int, batch_size: int | |
| ) -> tuple[list[dict[str, Any]], dict[tuple[str, str, int], int], int, int]: | |
| expected = expected_physical_counts() | |
| observed: collections.Counter[tuple[str, str, int]] = collections.Counter() | |
| class_ids: dict[tuple[str, str, int], set[int]] = collections.defaultdict(set) | |
| shard_records: list[dict[str, Any]] = [] | |
| total_payload = 0 | |
| total_rows = 0 | |
| archives = sorted(inner_root.glob("*.tar.gz")) | |
| archive_methods = {path.name.removesuffix(".tar.gz") for path in archives} | |
| expected_methods = set(STANDARD_GROUPS) | {"FreD", "NCFM"} | |
| if archive_methods != expected_methods: | |
| raise ValueError( | |
| f"Method archives differ from checklist: found={sorted(archive_methods)}, " | |
| f"expected={sorted(expected_methods)}" | |
| ) | |
| for archive in archives: | |
| method = archive.name.removesuffix(".tar.gz") | |
| print(f"[images] {method}: reading {archive.name}", flush=True) | |
| weights = load_wmdd_weights(archive) if method == "WMDD" else {} | |
| writer = ImageShardWriter(output_root, method, target_bytes, batch_size) | |
| with tarfile.open(archive, "r:gz") as tf: | |
| for member in tf: | |
| if not member.isfile(): | |
| continue | |
| normalized = normalized_tar_path(member.name) | |
| suffix = Path(normalized).suffix.lower() | |
| if suffix == ".txt" and normalized.endswith("sample_weights.txt"): | |
| if method != "WMDD": | |
| raise ValueError(f"Unexpected sample weights outside WMDD: {normalized}") | |
| continue | |
| if suffix not in {".jpg", ".jpeg", ".png"}: | |
| raise ValueError(f"Unexpected non-image file in {archive.name}: {normalized}") | |
| dataset, ipc, class_id, image_id, extension = parse_image_path(normalized) | |
| key = (method, dataset, ipc) | |
| if key not in expected: | |
| raise ValueError(f"Image group is not in the checklist: {key}") | |
| if class_id < 0 or class_id >= NUM_CLASSES[dataset]: | |
| raise ValueError(f"Class id outside range in {normalized}") | |
| extracted = tf.extractfile(member) | |
| if extracted is None: | |
| raise RuntimeError(f"Cannot extract {normalized}") | |
| payload = extracted.read() | |
| if len(payload) != member.size: | |
| raise RuntimeError( | |
| f"Short read for {normalized}: {len(payload)} != {member.size}" | |
| ) | |
| sample_weight = None | |
| if method == "WMDD": | |
| matrix = weights.get((dataset, ipc)) | |
| if matrix is None: | |
| raise ValueError(f"Missing WMDD weights for {dataset} IPC {ipc}") | |
| if image_id < 0 or image_id >= ipc: | |
| raise ValueError(f"WMDD image id outside IPC range: {normalized}") | |
| sample_weight = matrix[class_id][image_id] | |
| writer.append( | |
| { | |
| "method": method, | |
| "dataset": dataset, | |
| "ipc": ipc, | |
| "class_id": class_id, | |
| "image_id": image_id, | |
| "source_path": normalized, | |
| "extension": extension, | |
| "image": {"bytes": payload, "path": normalized}, | |
| "sample_weight": sample_weight, | |
| "sha256": hashlib.sha256(payload).hexdigest(), | |
| "byte_size": len(payload), | |
| "source_archive": archive.name, | |
| } | |
| ) | |
| observed[key] += 1 | |
| class_ids[key].add(class_id) | |
| total_rows += 1 | |
| total_payload += len(payload) | |
| shard_records.extend(writer.close()) | |
| method_rows = sum(value for key, value in observed.items() if key[0] == method) | |
| print(f"[images] {method}: wrote {method_rows:,} rows", flush=True) | |
| if dict(observed) != expected: | |
| missing = {key: value for key, value in expected.items() if observed.get(key) != value} | |
| extra = {key: value for key, value in observed.items() if expected.get(key) != value} | |
| raise ValueError(f"Physical count validation failed; expected-diff={missing}, observed-diff={extra}") | |
| for key in sorted(expected): | |
| required = set(range(NUM_CLASSES[key[1]])) | |
| if class_ids[key] != required: | |
| raise ValueError(f"Class coverage validation failed for {key}") | |
| return shard_records, dict(observed), total_rows, total_payload | |
| def teacher_filename(spec: dict[str, Any]) -> str: | |
| values = [spec["provider"], spec["dataset"], spec["architecture"]] | |
| return "-".join(re.sub(r"[^A-Za-z0-9]+", "-", value).strip("-") for value in values).lower() | |
| def convert_teachers( | |
| archive: Path, output_root: Path | |
| ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], int]: | |
| output_dir = output_root / "data" / "teachers" | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| found: dict[str, dict[str, Any]] = {} | |
| shard_records: list[dict[str, Any]] = [] | |
| total_payload = 0 | |
| with tarfile.open(archive, "r:") as tf: | |
| for member in tf: | |
| if not member.isfile(): | |
| continue | |
| normalized = normalized_tar_path(member.name) | |
| spec = TEACHERS.get(normalized) | |
| if spec is None: | |
| continue | |
| extracted = tf.extractfile(member) | |
| if extracted is None: | |
| raise RuntimeError(f"Cannot extract {normalized}") | |
| payload = extracted.read() | |
| if len(payload) != member.size: | |
| raise RuntimeError(f"Short read for {normalized}") | |
| digest = hashlib.sha256(payload).hexdigest() | |
| output = output_dir / f"{teacher_filename(spec)}.parquet" | |
| if output.exists(): | |
| raise FileExistsError(f"Refusing to overwrite {output}") | |
| row = { | |
| **spec, | |
| "source_path": normalized, | |
| "checkpoint": payload, | |
| "sha256": digest, | |
| "byte_size": len(payload), | |
| "source_archive": archive.name, | |
| } | |
| table = pa.Table.from_pylist([row], schema=TEACHER_SCHEMA) | |
| pq.write_table( | |
| table, | |
| output, | |
| compression="zstd", | |
| compression_level=1, | |
| use_dictionary=["provider", "dataset", "architecture", "source_archive"], | |
| write_statistics=["provider", "dataset", "architecture", "byte_size"], | |
| data_page_size=1024 * 1024, | |
| ) | |
| check = pq.read_table(output, columns=["sha256", "byte_size"]).to_pylist()[0] | |
| if check["sha256"] != digest or check["byte_size"] != len(payload): | |
| raise RuntimeError(f"Teacher Parquet verification failed for {output}") | |
| found[normalized] = {key: value for key, value in row.items() if key != "checkpoint"} | |
| total_payload += len(payload) | |
| shard_records.append( | |
| { | |
| "asset_type": "teacher", | |
| "relative_path": output.relative_to(output_root).as_posix(), | |
| "method_or_provider": spec["provider"], | |
| "row_count": 1, | |
| "payload_bytes": len(payload), | |
| "parquet_bytes": output.stat().st_size, | |
| "sha256": sha256_file(output), | |
| } | |
| ) | |
| print(f"[teacher] {normalized}: {len(payload):,} bytes", flush=True) | |
| missing_present = sorted(set(TEACHERS) - set(found)) | |
| if missing_present: | |
| raise ValueError(f"Checklist says teacher exists but archive lookup failed: {missing_present}") | |
| return shard_records, [found[path] for path in TEACHERS], total_payload | |
| def write_manifest(output_root: Path, records: Iterable[dict[str, Any]]) -> None: | |
| manifest_dir = output_root / "data" / "manifest" | |
| manifest_dir.mkdir(parents=True, exist_ok=True) | |
| output = manifest_dir / "shards.parquet" | |
| if output.exists(): | |
| raise FileExistsError(f"Refusing to overwrite {output}") | |
| table = pa.Table.from_pylist(list(records), schema=SHARD_SCHEMA) | |
| pq.write_table(table, output, compression="zstd", compression_level=3) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--inner-root", required=True, type=Path) | |
| parser.add_argument("--teacher-archive", required=True, type=Path) | |
| parser.add_argument("--output-root", required=True, type=Path) | |
| parser.add_argument("--target-shard-mib", type=int, default=450) | |
| parser.add_argument("--batch-size", type=int, default=512) | |
| args = parser.parse_args() | |
| data_root = args.output_root / "data" | |
| if data_root.exists() and any(data_root.rglob("*.parquet")): | |
| raise FileExistsError( | |
| f"Parquet output already exists under {data_root}; refusing to overwrite" | |
| ) | |
| args.output_root.mkdir(parents=True, exist_ok=True) | |
| image_shards, counts, image_rows, image_payload = convert_images( | |
| args.inner_root, | |
| args.output_root, | |
| args.target_shard_mib * 1024 * 1024, | |
| args.batch_size, | |
| ) | |
| teacher_shards, teachers, teacher_payload = convert_teachers( | |
| args.teacher_archive, args.output_root | |
| ) | |
| all_shards = image_shards + teacher_shards | |
| write_manifest(args.output_root, all_shards) | |
| summary = { | |
| "created_at_utc": dt.datetime.now(dt.timezone.utc).isoformat(), | |
| "format": "byte-preserving Parquet", | |
| "image_schema": str(IMAGE_SCHEMA), | |
| "teacher_schema": str(TEACHER_SCHEMA), | |
| "image_rows": image_rows, | |
| "image_payload_bytes": image_payload, | |
| "teacher_rows": len(teachers), | |
| "teacher_payload_bytes": teacher_payload, | |
| "image_group_counts": [ | |
| {"method": key[0], "dataset": key[1], "ipc": key[2], "rows": value} | |
| for key, value in sorted(counts.items()) | |
| ], | |
| "teachers_present": teachers, | |
| "teachers_missing_from_source_archives": MISSING_TEACHERS, | |
| "shards": all_shards, | |
| } | |
| summary_path = args.output_root / "conversion_summary.json" | |
| summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") | |
| print( | |
| f"[done] images={image_rows:,} ({image_payload:,} bytes), " | |
| f"teachers={len(teachers)} ({teacher_payload:,} bytes), " | |
| f"shards={len(all_shards)}", | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |