#!/usr/bin/env python3 """Convert ImageNet-1K parquet shards into layouts used by CDF experiments. Expected parquet columns: - image: bytes, PIL-compatible dict, or path-like object - label: integer class id in [0, 999] Outputs: - ImageFolder layout for DiT: /imagefolder/train/000/*.JPEG /imagefolder/validation/000/*.JPEG - LDM layout: /ldm/ILSVRC2012_train/data/000/*.JPEG /ldm/ILSVRC2012_train/filelist.txt /ldm/ILSVRC2012_validation/data/000/*.JPEG /ldm/ILSVRC2012_validation/filelist.txt The numeric folder names are zero-padded so torchvision ImageFolder maps them to the same integer labels after lexicographic sorting. """ from __future__ import annotations import argparse import gc import io import json import shutil from pathlib import Path from typing import Optional, Tuple from PIL import Image from tqdm import tqdm def find_parquet_files(input_dir: Path, split: str): return sorted(input_dir.glob(f"{split}-*.parquet")) def row_image_to_pil(value): if isinstance(value, Image.Image): return value.convert("RGB") if isinstance(value, bytes): return Image.open(io.BytesIO(value)).convert("RGB") if isinstance(value, dict): if value.get("bytes") is not None: return Image.open(io.BytesIO(value["bytes"])).convert("RGB") if value.get("path") is not None: return Image.open(value["path"]).convert("RGB") if hasattr(value, "as_py"): return row_image_to_pil(value.as_py()) return Image.open(value).convert("RGB") def detect_image_column(columns, image_column: Optional[str]) -> str: if image_column is None: for candidate in ("image", "jpg", "jpeg", "img", "bytes"): if candidate in columns: image_column = candidate break if image_column is None: raise ValueError( f"Could not detect image column from {columns}. " "Pass --image-column explicitly." ) return image_column def detect_label_column(columns, label_column: Optional[str]) -> str: if label_column is None: for candidate in ("label", "labels", "class_label", "cls", "target"): if candidate in columns: label_column = candidate break if label_column is None: raise ValueError( f"Could not detect label column from {columns}. " "Pass --label-column explicitly." ) return label_column def detect_columns(columns, image_column: Optional[str], label_column: Optional[str]) -> Tuple[str, str]: image_column = detect_image_column(columns, image_column) label_column = detect_label_column(columns, label_column) return image_column, label_column def mark_prepared(root: Path): root.mkdir(parents=True, exist_ok=True) for marker in (".ready", ".prepared"): (root / marker).write_text("prepared\n", encoding="utf-8") def iter_parquet_batches(shard: Path, columns, batch_size: int): """Yield row dictionaries from a parquet shard without loading it fully.""" try: import pyarrow.parquet as pq parquet_file = pq.ParquetFile(shard) for batch in parquet_file.iter_batches(batch_size=batch_size, columns=columns): yield batch.to_pydict() except ImportError: import pandas as pd frame = pd.read_parquet(shard, columns=columns) for start in range(0, len(frame), batch_size): yield frame.iloc[start : start + batch_size].to_dict(orient="list") def parquet_num_rows(shard: Path) -> Optional[int]: try: import pyarrow.parquet as pq return pq.ParquetFile(shard).metadata.num_rows except Exception: return None def parquet_columns(shard: Path): try: import pyarrow.parquet as pq return pq.ParquetFile(shard).schema_arrow.names except ImportError: import pandas as pd return pd.read_parquet(shard).columns def count_existing_shard_images(imagefolder_root: Path, shard_stem: str) -> int: return sum(1 for _ in imagefolder_root.glob(f"*/{shard_stem}-*.JPEG")) def ensure_ldm_copy_or_link(args, dit_path: Path, ldm_path: Path): ldm_path.parent.mkdir(parents=True, exist_ok=True) if args.copy_mode == "copy": if args.skip_existing and ldm_path.exists(): return shutil.copy2(dit_path, ldm_path) return if ldm_path.exists() or ldm_path.is_symlink(): return ldm_path.symlink_to(dit_path.resolve()) def rebuild_filelist(ldm_root: Path): manifest_root = ldm_root / ".manifests" filelist_path = ldm_root / "filelist.txt" with filelist_path.open("w", encoding="utf-8") as out: for manifest in sorted(manifest_root.glob("*.txt")): with manifest.open("r", encoding="utf-8") as src: shutil.copyfileobj(src, out) mark_prepared(ldm_root) print(f"Rebuilt LDM filelist: {filelist_path}") def write_manifest_from_existing(args, shard: Path, imagefolder_root: Path, ldm_data_root: Path, manifest_path: Path): columns = parquet_columns(shard) label_column = detect_label_column(columns, args.label_column) tmp_manifest = manifest_path.with_suffix(".txt.tmp") tmp_manifest.parent.mkdir(parents=True, exist_ok=True) row_offset = 0 with tmp_manifest.open("w", encoding="utf-8") as manifest: for batch in iter_parquet_batches(shard, [label_column], args.batch_size): labels = batch[label_column] for batch_idx, label_value in enumerate(labels): row_idx = row_offset + batch_idx label = int(label_value) class_dir = f"{label:03d}" filename = f"{shard.stem}-{row_idx:06d}.JPEG" relpath = f"{class_dir}/{filename}" dit_path = imagefolder_root / class_dir / filename ldm_path = ldm_data_root / class_dir / filename if not dit_path.exists(): tmp_manifest.unlink(missing_ok=True) return False ensure_ldm_copy_or_link(args, dit_path, ldm_path) manifest.write(relpath + "\n") row_offset += len(labels) tmp_manifest.replace(manifest_path) return True def convert_split(args, split: str, ldm_name: str): all_parquet_files = find_parquet_files(args.input_dir, split) if not all_parquet_files: print(f"No parquet shards found for split={split}; skipping.") return shard_end = args.shard_end if args.shard_end is not None else len(all_parquet_files) parquet_files = all_parquet_files[args.shard_start : shard_end] if args.max_shards is not None: parquet_files = parquet_files[: args.max_shards] if not parquet_files: print(f"No parquet shards selected for split={split}; skipping.") return imagefolder_root = args.output_dir / "imagefolder" / split ldm_root = args.output_dir / "ldm" / ldm_name ldm_data_root = ldm_root / "data" manifest_root = ldm_root / ".manifests" imagefolder_root.mkdir(parents=True, exist_ok=True) ldm_data_root.mkdir(parents=True, exist_ok=True) manifest_root.mkdir(parents=True, exist_ok=True) count = 0 selected_msg = ( f"split={split}, selected shards " f"[{args.shard_start}, {args.shard_start + len(parquet_files)}) of {len(all_parquet_files)}" ) print(selected_msg) for shard in tqdm(parquet_files, desc=f"split={split} shards"): manifest_path = manifest_root / f"{shard.stem}.txt" if args.resume and manifest_path.exists(): if args.limit_per_split is not None: count += sum(1 for _ in manifest_path.open("r", encoding="utf-8")) continue expected_rows = parquet_num_rows(shard) if ( args.resume and args.trust_existing and expected_rows is not None and count_existing_shard_images(imagefolder_root, shard.stem) >= expected_rows ): if write_manifest_from_existing(args, shard, imagefolder_root, ldm_data_root, manifest_path): count += expected_rows continue columns = parquet_columns(shard) image_column, label_column = detect_columns(columns, args.image_column, args.label_column) row_offset = 0 tmp_manifest = manifest_path.with_suffix(".txt.tmp") with tmp_manifest.open("w", encoding="utf-8") as manifest: for batch in iter_parquet_batches(shard, [image_column, label_column], args.batch_size): images = batch[image_column] labels = batch[label_column] iterable = zip(images, labels) progress = tqdm( iterable, total=len(labels), leave=False, desc=f"{shard.name}:{row_offset}", ) for batch_idx, (image_value, label_value) in enumerate(progress): row_idx = row_offset + batch_idx label = int(label_value) class_dir = f"{label:03d}" filename = f"{shard.stem}-{row_idx:06d}.JPEG" relpath = f"{class_dir}/{filename}" dit_path = imagefolder_root / class_dir / filename ldm_path = ldm_data_root / class_dir / filename dit_path.parent.mkdir(parents=True, exist_ok=True) if not (args.skip_existing and dit_path.exists()): image = row_image_to_pil(image_value) image.save(dit_path, format="JPEG", quality=args.jpeg_quality) ensure_ldm_copy_or_link(args, dit_path, ldm_path) manifest.write(relpath + "\n") count += 1 if args.limit_per_split is not None and count >= args.limit_per_split: break row_offset += len(labels) if args.limit_per_split is not None and count >= args.limit_per_split: break tmp_manifest.replace(manifest_path) gc.collect() if args.limit_per_split is not None and count >= args.limit_per_split: break rebuild_filelist(ldm_root) print(f"Wrote {count} images for split={split}") print(f"DiT ImageFolder: {imagefolder_root}") print(f"LDM data root: {ldm_root}") def main(): parser = argparse.ArgumentParser() parser.add_argument("--input-dir", type=Path, required=True) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--image-column", type=str, default=None) parser.add_argument("--label-column", type=str, default=None) parser.add_argument("--jpeg-quality", type=int, default=95) parser.add_argument("--copy-mode", choices=["symlink", "copy"], default="symlink") parser.add_argument("--limit-per-split", type=int, default=None) parser.add_argument("--splits", type=str, default="train,validation") parser.add_argument("--batch-size", type=int, default=512) parser.add_argument("--shard-start", type=int, default=0, help="Inclusive shard index within each selected split.") parser.add_argument("--shard-end", type=int, default=None, help="Exclusive shard index within each selected split.") parser.add_argument("--max-shards", type=int, default=None) parser.add_argument("--resume", dest="resume", action="store_true", default=True) parser.add_argument("--no-resume", dest="resume", action="store_false") parser.add_argument("--skip-existing", dest="skip_existing", action="store_true", default=True) parser.add_argument("--no-skip-existing", dest="skip_existing", action="store_false") parser.add_argument( "--trust-existing", dest="trust_existing", action="store_true", default=True, help="If all JPEGs for a shard already exist, rebuild only its manifest and skip image decoding.", ) parser.add_argument("--no-trust-existing", dest="trust_existing", action="store_false") parser.add_argument("--rebuild-filelist-only", action="store_true") args = parser.parse_args() split_map = { "train": "ILSVRC2012_train", "validation": "ILSVRC2012_validation", "val": "ILSVRC2012_validation", "test": "ILSVRC2012_validation", } args.output_dir.mkdir(parents=True, exist_ok=True) with (args.output_dir / "conversion_args.json").open("w", encoding="utf-8") as f: json.dump({key: str(value) for key, value in vars(args).items()}, f, indent=2) for split in [item.strip() for item in args.splits.split(",") if item.strip()]: ldm_name = split_map.get(split, split) if args.rebuild_filelist_only: rebuild_filelist(args.output_dir / "ldm" / ldm_name) else: convert_split(args, split, ldm_name) if __name__ == "__main__": main()