diff --git a/HF_DATASETS.md b/HF_DATASETS.md index 01d4e8f..b9d07d1 100644 --- a/HF_DATASETS.md +++ b/HF_DATASETS.md @@ -1,345 +1,118 @@ -# Hugging Face datasets +# Hugging Face reproduction data -This guide covers prepared dataset snapshots. -For trained weights, see [Hugging Face model checkpoints](HF_MODEL_CHECKPOINTS.md). -For source downloads and rendering, see the [dataset guide](datasets/README.md). - -The public [PartProbe3D preprocessed dataset](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed) -publishes saved observations, calibration, target grids, completion markers, and split policies. -The full extent bundles also contain posed geometry. -The FoundationPose bundle contains an export for training without meshes. -The dataset card lists archive availability and links RGB/mask/GLB previews. -The Hugging Face viewer exposes the per-view metadata indices. - -| Dataset | Training views | Test views | Local root after restoration | -| --- | ---: | ---: | --- | -| 3D-FRONT | 39,930 | 10,066 | `datasets/3dfront/extent/point_cloud` | -| YCB-V | 0 | 900 | `datasets/ycbv/extent/point_cloud` | -| SAGE-10k | 17,456 | 1,952 | `datasets/sage/extent/point_cloud` | -| FoundationPose | 42,256 | 4,692 | `datasets/foundationpose/extent/point_cloud` | - -YCB-V is evaluation only. SAGE's complete 64³ point-cloud extent contains 19,408 -views across 9,931 rooms. -Of the 20,000 calibrated captures, 592 did not have enough visible prompts for training targets. Its layout-level SHA-256 split keeps -all rooms/views of a layout together, with no validation split. The Hub card -records archive upload progress separately from source preparation completion. -FoundationPose retains 46,948 accepted captures from a budget of 50,000. -Target preparation excluded 3,052 captures and reported zero processing errors. -All 1,000 sampled views passed validation. This run skipped full validation by user request. -Diagnostic subsets, raw archives, model weights, and model-specific feature caches are not in this upload. - -Install the project's preprocessing dependencies, including `huggingface-hub` and `requests`. -From the repository root on another server, download and restore with: - -```bash -python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset 3dfront -python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset ycbv -python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset sage --cleanup -``` +The public [dataset repository](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed) separates training data, optional components, and deprecated uploads. +The default download supports SS, generative SLAT segmentation, and 32³ SLAT shape training. +Model weights remain separate artifacts. +See [model checkpoints](HF_MODEL_CHECKPOINTS.md) and [pretrained assets](ASSETS.md). -Use `--revision ` to pin a snapshot. Downloads resume after an interruption. -The downloader checks each archive against its SHA-256 checksum. -Restoration refuses to replace different existing data. -Each dataset transfers one file at a time through sequential HTTP requests. -Interrupted transfers retain their partial bytes. Different dataset commands can run concurrently. -The downloader records progress in `datasets//archives/huggingface///download-status.json`. -The downloader caches archives in `datasets//archives/huggingface/`. -Allow space for both archives and extracted files. Source manifests retain -historical absolute paths as provenance, but the loaders use manifest-relative -sample, camera and saved geometry paths, so raw sources are unnecessary. -Prepare model-specific feature caches on the destination server using the -existing SS or SLAT preparation commands. +## Repository structure -Use `download --cleanup` to restore one archive at a time and remove it only -after verification and successful extraction. This limits temporary archive -storage to one shard while keeping the extracted dataset and small indices. -The mixed training config `slat_segvigen/configs/one_hot_sum_flow_front3d_sage_32_nora_ray_pool.json` -consumes these SAGE and 3D-FRONT roots, computing image features and pooling the -saved 64³ grids to 32³ online. +| Location | Contents | Default download | +| --- | --- | --- | +| `training/observations//` | Original sample NPZ files, calibration, object mappings, and scene voxel targets | Yes | +| `training/shape/32//` | Complete object shape targets with explicit exclusions | Yes, when available | +| `training/index.json` | Dataset recipes, sizes, monitoring counts, and source identities | Yes | +| `optional/held_out//` | Remaining test observations | No | +| `optional/geometry//` | Mesh geometry for evaluation and target generation | No | +| `optional/occlusion//` | GT occlusion relations for applicable SS configurations | No | +| `optional/evaluation/ycbv/` | YCB-V observations and geometry for evaluation | No | +| `_deprecated/20261020/` | Previous bundles, inventories, and catalogs | No | +| `code/` | Restore changes relative to the recorded Git revision | Bootstrap only | -## Exports for training without meshes +Default datasets are 3D-FRONT and SAGE-10k. +FoundationPose requires an explicit dataset selection. +Its observation bundle supports SS and segmentation, but contains no shape targets or mesh geometry. -Training can use saved observations and targets without original datasets or mesh files. -The export preserves the source manifest, split definitions, sample bytes, and checksums. -Historical geometry paths remain provenance entries, but training does not open those paths. +## Restore on another server -Create a local export from a complete extent: +The dataset card records the required Git revision and restore patch. +Apply that patch to the recorded project checkout before using the new commands. +Install the project dependencies with its configured Python environment. ```bash -python -m preprocess.training_export \ - --dataset datasets/3dfront/extent/point_cloud \ - --output datasets/3dfront/training/point_cloud +python -m pip install -e '.[preprocess,ss-multiobj-depth,slat-segvigen,slat-multiobj-shape]' +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed ``` -The exporter uses hard links on the same filesystem and copies files when necessary. -The destination contains ordinary files and does not depend on source paths. -It includes complete GT occlusion relations when they exist. -It excludes mesh geometry and model-specific feature caches. -The separate `training_export.json` records completion without changing the source manifest. +The command downloads both default datasets and their 32³ object shape targets. +It excludes optional and deprecated folders. +It verifies each archive before extraction and removes temporary archives after restoration. +Use `--keep-archives` only when you need those temporary files. +Temporary transfer files use `datasets/_deprecated//huggingface/`. -Create transferable archives without an intermediate dataset copy: +Select one dataset with `--dataset`: ```bash -python -m preprocess.huggingface pack \ - --dataset 3dfront=datasets/3dfront/extent/point_cloud \ - --artifact-kind extent-training \ - --output outputs/huggingface/training_only +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset foundationpose ``` -The existing archive downloader also restores these archives. -Use a separate packaging directory to avoid mixing full and training exports. -The archive index records `artifact_kind=extent-training` and `geometry_included=false`. -The source dataset remains unchanged. - -SS with object attention also needs its matching GT occlusion cache. -SLAT shape training needs encoded targets and conditioning caches in addition to dataset metadata. -Mesh-based evaluation and new SLAT shape encoding require a full extent export. -Model weights remain separate artifacts. - -## FoundationPose on another server - -Use [code revision `92ca3ee`](https://github.com/cube-c/PartProbe3D/commit/92ca3eea1dbec6e162e246858eb7bdb7f7fd0701) or a compatible later revision on `slat-shape`. -The FoundationPose bundle preserves original RGB, depth, visible masks, cameras, object mapping, and complete per-object voxel occupancy at 64³. -Its source manifest has SHA-256 `2c4dcd1cd1e2e56a0eb08f2f92da320f299729c8ce7a2f52828c272cbc1fa0ad`. -The extracted files occupy 87.82 GB before filesystem overhead. -The [verified inventory](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/blob/073988c5b5e206570da67f57aada4a2f0ad94e95/bundles/foundationpose/index.json) contains 86 archives totaling 89.33 GB. -The export excludes raw archives, meshes, model weights, image features, SLAT latents, and GT occlusion relations. - -The loaders resolve input paths relative to the restored dataset. -Historical absolute paths remain provenance entries. -SS preparation creates the union of complete occupancy for objects with supplied masks and excludes other object voxels. - -### Restore the data - -Use Python 3.12 and a compatible PyTorch/CUDA installation. -Run these commands from the repository root. - -1. Install the project dependencies. - - ```bash - python -m pip install -e '.[preprocess,ss-multiobj-depth,tracking]' - ``` - -2. Restore the prepared observations and voxel targets. - - ```bash - python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --dataset foundationpose --cleanup \ - --revision 073988c5b5e206570da67f57aada4a2f0ad94e95 - ``` - -3. Initialize the pinned Pixal3D source. - - ```bash - git submodule update --init third_party/Pixal3D - ``` - -`--cleanup` retains extracted data and removes each verified temporary archive. -Allow at least 100 GB for data restoration, plus space for weights and model features. -Use `--revision ` to retain one dataset snapshot. - -### Acquire SS weights - -All required weights for the following SS configuration are available from Hugging Face. -The commands pin revisions with the same configuration and weight bytes as the verified local files. -DINOv3 requires approved access to its [gated model repository](https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m). - -1. Authenticate with an account that can download DINOv3. - - ```bash - hf auth login - ``` - -2. Download the native SS flow and decoder from [Pixal3D](https://huggingface.co/TencentARC/Pixal3D). - - ```bash - hf download TencentARC/Pixal3D \ - --revision b0cb2e1b794cab9aa0ac38a95d794a4d9337437f \ - --local-dir checkpoints/Pixal3D \ - --include 'ckpts/ss_flow_img_dit_1_3B_64_bf16.*' 'ckpts/ss_dec_conv3d_16l8_fp16.*' - ``` - -3. Download the SS encoder and paired decoder from [TRELLIS](https://huggingface.co/microsoft/TRELLIS-image-large). - - ```bash - hf download microsoft/TRELLIS-image-large \ - --revision 25e0d31ffbebe4b5a97464dd851910efc3002d96 \ - --local-dir checkpoints/TRELLIS \ - --include 'ckpts/ss_enc_conv3d_16l8_fp16.*' 'ckpts/ss_dec_conv3d_16l8_fp16.safetensors' - ``` - -4. Download DINOv3. - - ```bash - hf download facebook/dinov3-vitl16-pretrain-lvd1689m \ - --revision ea8dc2863c51be0a264bab82070e3e8836b02d51 \ - --local-dir checkpoints/DINOv3 --include config.json model.safetensors - ``` - -### Prepare features and train SS - -The [FoundationPose configuration](ss_multiobj_depth/configs/foundationpose.json) uses GT depth, `depth_embedding` voxel conditioning, global cross-attention, and rank-8 NoRA. -It creates features under `outputs/ss_multiobj_depth/foundationpose/features` and preserves the saved training/test splits. -It starts a new run with W&B online by default. -Online logging requires W&B authentication. -The setting `training.wandb_mode="disabled"` permits a local run without W&B. - -1. Prepare local features and encoded SS targets. - - ```bash - python -m ss_multiobj_depth.prepare --config ss_multiobj_depth/configs/foundationpose.json - ``` - -2. Start training. - - ```bash - python -m ss_multiobj_depth.train --config ss_multiobj_depth/configs/foundationpose.json - ``` - -This configuration needs no source archives, meshes, or additional dataset downloads. -The `occlusion_object` variant additionally requires a matching GT occlusion cache. -That cache requires mesh geometry during preparation and is absent from this FoundationPose bundle. -A matching GT occlusion overlay can transfer separately without another download of the observation archives. -New SLAT shape encoding and mesh-based evaluation also require geometry or separately transferred targets. -Exact resume of an existing run requires its matching checkpoint, feature manifests, source hashes, and settings. - -## GT occlusion relations - -Separate archives under `precomputed_occlusion/` preserve the completed GT occlusion caches. -The caches contain directed `[front, back]` relations from calibrated visible masks and posed GT mesh silhouettes. -Each archive preserves the original matrices, completion records, and manifest bytes. - -| Dataset | Training views | Test views | Archives | Size, MB | -| --- | ---: | ---: | ---: | ---: | -| 3D-FRONT | 39,930 | 10,066 | 3 | 240.01 | -| SAGE-10k | 17,456 | 1,952 | 3 | 103.45 | -| Total | 57,386 | 12,018 | 6 | 343.46 | - -MB means decimal megabytes. -The inventories at `precomputed_occlusion//index.json` record archive sizes and SHA-256 checksums. -They also preserve the source policy and checksum of the matching extent manifest. - -### Download GT occlusion caches +Add `--revision ` to retain one dataset snapshot. +Restoration refuses to replace different existing data. +Original extent manifests retain their bytes and SHA-256 identities. +The separate `compact_training.json` identifies available views without changing those manifests. -Restore the matching extent datasets before these overlays. -Run these commands from the repository root. +## Training inputs -```bash -python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_occlusion \ - --dataset 3dfront --revision 88cdf8f0e880a33e7cafa580ee9722776f16aa28 --cleanup -python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_occlusion \ - --dataset sage --revision 88cdf8f0e880a33e7cafa580ee9722776f16aa28 --cleanup -``` +The observations contain every training view and the first 16 test views per dataset. +These test views cover the existing eight-view and sixteen-view training monitors. +The remaining test observations require an optional download. +Training view order and source splits remain unchanged. -The commands restore `datasets//extent/point_cloud/occlusion/`. -The downloader verifies each archive and refuses to replace different existing files. -The dataset reader checks the extent manifest identity before reading GT relations. +Each sample NPZ already contains RGB, depth, visible labels, and complete per-object occupancy. +The compact export excludes separate RGB, mask, depth, overlay, and per-view voxel copies. +SS monitoring reads RGB and labels directly from the sample NPZ. +Scene voxel targets remain available because SS preparation reads them. -SS training with occlusion-aware object cross-attention reads these relations. -SLAT shape tokens already have instance identities and require no occlusion matrix. -Frozen image features and SLAT shape latents remain separate artifacts. +Shape targets preserve all object arrays, including coordinates, instance identities, and overlapping tokens. +The export excludes combined scene latents because the current shape objective uses object targets. +It records the three failed SAGE views as explicit exclusions. +These exclusions match the existing object-mean shape experiment. +SS and segmentation retain those views. +The download does not contain model features or trained weights. +SS preparation creates its local feature cache. +Segmentation extracts image features during training. +The `configure-shape` command creates an online configuration without a separate image-feature cache. +It preserves the selected preset's model and optimization settings. +The [SLAT preparation guide](preprocess/slat/HUGGING_FACE.md) describes both shape options. -### Publish GT occlusion caches +## Optional downloads -Package the verified caches from the prepared extent roots: +Restore observations before adding geometry, occlusion, or remaining test views. +The YCB-V evaluation bundle includes its own observations and geometry. +Select each optional component explicitly: ```bash -python -m preprocess.huggingface pack --artifact-kind gt-occlusion \ - --dataset 3dfront=datasets/3dfront/extent/point_cloud \ - --dataset sage=datasets/sage/extent/point_cloud \ - --output outputs/huggingface/gt_occlusion -python -m preprocess.huggingface upload \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_occlusion \ - --dataset 3dfront --dataset sage --output outputs/huggingface/gt_occlusion +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset sage --optional geometry +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset 3dfront --optional occlusion +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset sage --optional held-out +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset ycbv --optional evaluation ``` -Packaging checks every matrix checksum and its completion record. -The uploader publishes complete inventories after it verifies all remote archives. +Geometry supports mesh scoring and shape encoding at other resolutions. +GT occlusion relations support SS configurations with occlusion-aware object attention. +The current shape tokens already identify their objects and require no GT occlusion matrix. +The optional test overlay expands the available views without replacing training inputs. -## Additional SLAT targets +## Deprecated uploads -The same repository provides separate 32³ SLAT targets under `precomputed_slat/`. -The 3D-FRONT bundle covers 39,930 training views. The SAGE bundle covers 17,456 training views. -Together, their ten archives contain 6.37 GiB of latent targets and metadata. -The existing extent datasets supply the RGB images, masks, depth, and geometry. - -```bash -python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \ - --dataset 3dfront --cleanup -python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \ - --dataset sage --cleanup -``` - -These commands restore `datasets//slat/32/targets/`. -The snapshots retain partial scene encoding and three failed SAGE object targets. -Frozen image features require separate preparation. -See the [SLAT snapshot specification](preprocess/slat/HUGGING_FACE.md) for source revisions, coverage, and preparation steps. -The [local restoration report](reports/huggingface_additional_slat_targets_20261017.md) records downloaded snapshots and verification results. +The previous layout remains under `_deprecated/20261020/`. +The original [snapshot](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/tree/d13e577a7e71291ed94fa40e4297f54106577fbd) also remains accessible by revision. +Default downloads never select these paths. +An unfiltered Hugging Face snapshot download still includes every folder. +Use the project downloader to avoid optional and deprecated data. ## Publication -The reusable publication commands produce approximately 1 GiB archive shards -under `outputs/`, without modifying the source datasets: - -```bash -python -m preprocess.huggingface pack \ - --dataset ycbv=datasets/ycbv/extent/point_cloud \ - --dataset 3dfront=datasets/3dfront/extent/point_cloud \ - --output outputs/huggingface/preprocessed -python -m preprocess.huggingface catalog \ - --dataset 3dfront=datasets/3dfront/extent/point_cloud \ - --dataset ycbv=datasets/ycbv/extent/point_cloud \ - --repo cubec/PartProbe3D-preprocessed --output outputs/huggingface/preprocessed -python -m preprocess.huggingface upload \ - --dataset 3dfront --dataset ycbv --repo cubec/PartProbe3D-preprocessed \ - --output outputs/huggingface/preprocessed --follow -``` - -`--follow` uploads finished shards while packaging continues. Repeating the -commands reuses verified packages and skips matching remote archives. The publisher uploads the complete archive index after it uploads all archives. -Use `upload --workers 16` to request 16 concurrent archive transfers. -The default retains the Hugging Face client's transfer settings. -The initial run logs are `outputs/huggingface/preprocessed/pack.log`, -`upload-3dfront.log`, and `upload-ycbv.log`. - -For one job that packages, uploads, retries transient Hub failures and updates -the public dataset card, use: - -```bash -python -m preprocess.huggingface publish \ - --dataset ycbv=datasets/ycbv/extent/point_cloud \ - --dataset 3dfront=datasets/3dfront/extent/point_cloud \ - --repo cubec/PartProbe3D-preprocessed --output outputs/huggingface/preprocessed -``` - -The job records `running`, `complete`, or `failed` in -`outputs/huggingface/preprocessed/publish-status.json`. The detached server run -records its process ID in `publish.pid` and writes `publish.log` in that folder. - -For large datasets, `publish --cleanup` creates, uploads and verifies one shard -before removing it and creating the next. -The command preserves original datasets, archive inventories, previews, transfer logs, and remote archives. -Failures retain the current unverified shard. Repeating the command verifies -existing remote archives and resumes the upload. -The publisher can rebuild removed staging shards from the unchanged source. Existing dataset catalogs remain in the repo: +Run this command from the project root: ```bash -python -m preprocess.huggingface publish \ - --dataset sage=datasets/sage/extent/point_cloud \ +python -m preprocess.reproduction publish \ --repo cubec/PartProbe3D-preprocessed \ - --output outputs/huggingface/preprocessed --cleanup + --output outputs/huggingface/reproduction \ + --dataset 3dfront --dataset sage --dataset foundationpose ``` -## SS targets for masked objects - -The prepared dataset already contains complete per-object occupancy and the prompt mapping. -SS target generation uses the saved labels and prompt mapping. -It creates new local targets and encoded latents. -The published dataset retains its existing files. Existing local copies need no additional dataset download. - -See [SS target regeneration and transfer](ss_multiobj_depth/README.md#regenerate-targets-for-masked-objects) for target overlays and reuse of existing conditioning caches. +Publication preserves source datasets and limits temporary archive storage through verified upload batches. +Repetition reuses remote archives with matching SHA-256 identities. +The publisher retains unverified files after a failure. diff --git a/dataloader/dataset.py b/dataloader/dataset.py index 08f0d62..cdd79fd 100644 --- a/dataloader/dataset.py +++ b/dataloader/dataset.py @@ -110,6 +110,18 @@ class ViewDataset: if not self.manifest["complete"] and not allow_incomplete: raise ValueError("Conversion is incomplete; do not use partial data for training") self.views = [row for row in self.manifest["views"] if split is None or row["split"] == split] + selection_path = self.root / 'compact_training.json' + if selection_path.exists(): + from utils.hashing import sha256 + selection = json.loads(selection_path.read_text()) + ids = selection.get('view_ids', []) + if (selection.get('schema') != 'partprobe3d.compact-training.v1' + or selection.get('source_manifest_sha256') != sha256(self.root / 'manifest.json') + or len(ids) != len(set(ids)) + or set(ids) - {row['id'] for row in self.manifest['views']}): + raise ValueError('Compact training selection differs from the source manifest') + available = set(ids) + self.views = [row for row in self.views if row['id'] in available] def __len__(self): return len(self.views) diff --git a/dataloader/extent.py b/dataloader/extent.py index d13d628..245f83e 100644 --- a/dataloader/extent.py +++ b/dataloader/extent.py @@ -31,6 +31,10 @@ class ExtentLoader(BaseDataLoader): from PIL import Image index = self.dataset._index(index) row = self.rows[index] + if (self.root / 'compact_training.json').exists(): + # Load only these two NPZ members. Calibration and depth stay unread. + with np.load(self.root / row['sample'], allow_pickle=False) as arrays: + return arrays['rgb'], arrays['image_labels'].astype(np.int32) + 1 with Image.open(self.root / row["rgb"]) as image: rgb = np.array(image.convert("RGB")) objects = self.dataset.source.objects(self.dataset.indices[index])["prompts"] diff --git a/preprocess/huggingface.py b/preprocess/huggingface.py index 60aafa7..2fdce63 100644 --- a/preprocess/huggingface.py +++ b/preprocess/huggingface.py @@ -8,6 +8,7 @@ import os from pathlib import Path, PurePosixPath import re import shutil +import stat import tarfile import tempfile import time @@ -90,8 +91,13 @@ class _HashWriter: return self.stream.write(data) -def _archive(path, files, source, destination, previous=None): - records = [(str(p.relative_to(source)), p.stat().st_size, p.stat().st_mtime_ns) for p in files] +def _archive(path, files, source, destination, previous=None, *, checksums=None): + records = [] + for file in files: + original = file.stat(follow_symlinks=False) + if not stat.S_ISREG(original.st_mode): + raise ValueError(f'Archive sources must be regular files: {file}') + records.append((str(file.relative_to(source)), original.st_size, original.st_mtime_ns)) identity = hashlib.sha256(json.dumps(records).encode()).hexdigest() if previous and previous.get('identity') == identity and path.is_file(): if path.stat().st_size == previous['bytes'] and sha256(path) == previous['sha256']: @@ -101,18 +107,36 @@ def _archive(path, files, source, destination, previous=None): try: with temporary.open('wb') as stream: writer = _HashWriter(stream) - with tarfile.open(fileobj=writer, mode='w|', format=tarfile.USTAR_FORMAT) as archive: + with tarfile.open(fileobj=writer, mode='w|', format=tarfile.USTAR_FORMAT, + bufsize=256 * 1024, copybufsize=1024**2) as archive: for file, (name, size, mtime) in zip(files, records): - info = archive.gettarinfo(str(file), arcname=str(destination / name)) - if not info.isfile() or info.size != size or file.stat().st_mtime_ns != mtime: - raise ValueError(f'Source changed during packaging: {file}') + info = tarfile.TarInfo(str(destination / name)) + info.size = size info.uid = info.gid = info.mtime = 0 info.uname = info.gname = '' info.mode = 0o644 with file.open('rb') as data: - archive.addfile(info, data) - if file.stat().st_mtime_ns != mtime or file.stat().st_size != size: - raise ValueError(f'Source changed during packaging: {file}') + opened = os.fstat(data.fileno()) + if opened.st_size != size or opened.st_mtime_ns != mtime: + raise ValueError(f'Source changed during packaging: {file}') + if checksums and file in checksums: + class CheckedReader: + def __init__(self, stream): + self.stream, self.digest = stream, hashlib.sha256() + + def read(self, size=-1): + block = self.stream.read(size) + self.digest.update(block) + return block + checked = CheckedReader(data) + archive.addfile(info, checked) + if checked.digest.hexdigest() != checksums[file]: + raise ValueError(f'Source checksum changed during packaging: {file}') + else: + archive.addfile(info, data) + finished = os.fstat(data.fileno()) + if finished.st_mtime_ns != mtime or finished.st_size != size: + raise ValueError(f'Source changed during packaging: {file}') stream.flush() os.fsync(stream.fileno()) digest = writer.digest.hexdigest() @@ -378,7 +402,7 @@ def extract(index, folder, destination): path = folder / _relative(item['file']) if path.stat().st_size != item['bytes'] or sha256(path) != item['sha256']: raise ValueError(f'Archive checksum mismatch: {path}') - with tarfile.open(path, 'r|') as archive: + with tarfile.open(path, 'r|', bufsize=256 * 1024) as archive: for member in archive: relative = _relative(member.name) if not relative.is_relative_to(prefix) or not member.isfile(): @@ -401,6 +425,9 @@ def extract(index, folder, destination): finally: temporary.unlink(missing_ok=True) print(f"RESTORED {index['name']}/{item['file']}", flush=True) + if index.get('artifact_kind') in ('compact-training', 'held-out-observations'): + from preprocess.reproduction import refresh_selection + refresh_selection(destination / restored_prefix) return destination / restored_prefix @@ -523,14 +550,21 @@ def upload(output, repo, names, *, follow=False, packing=None, update_card=False print(f'UPLOADED {name}: https://huggingface.co/datasets/{repo}', flush=True) -def download(repo, name, destination, revision, *, cleanup=False, bundle_root='bundles'): +def download(repo, name, destination, revision, *, cleanup=None, bundle_root=None): + if bundle_root is None: + from preprocess.reproduction import download_training + return download_training(repo, name, destination, revision, cleanup=cleanup is not False) from huggingface_hub import HfApi, hf_hub_download from utils.huggingface_download import download_huggingface_file # Resolve main once so all archives and the index belong to one snapshot. revision = HfApi().dataset_info(repo, revision=revision).sha bundle_root = str(_relative(bundle_root)) destination = Path(destination).resolve() - cache = destination / 'datasets' / name / 'archives' / 'huggingface' + # Keep active training folders free of transfer archives. Retain the legacy + # cache path only when an explicit historical component needs resume. + cache = (destination / 'datasets' / '_deprecated' / name / 'huggingface' + if bundle_root.startswith(('training/', 'optional/')) + else destination / 'datasets' / name / 'archives' / 'huggingface') index_path = hf_hub_download(repo, f'{bundle_root}/{name}/index.json', repo_type='dataset', revision=revision, local_dir=cache) index = _json(index_path) @@ -820,12 +854,16 @@ def main(): help='Concurrent archive transfers. Default: Hugging Face client setting') restoring = commands.add_parser('download') restoring.add_argument('--repo', required=True) - restoring.add_argument('--dataset', required=True) + restoring.add_argument('--dataset', default='all', help='Dataset name. Default: 3D-FRONT and SAGE') restoring.add_argument('--destination', type=Path, default=Path('.')) restoring.add_argument('--revision', default='main') - restoring.add_argument('--bundle-root', default='bundles') + restoring.add_argument('--bundle-root', default=None, + help='Explicit component root. Default: compact training data and 32-cubed shape targets') restoring.add_argument('--cleanup', action='store_true', help='Restore one archive at a time and remove it after successful extraction') + restoring.add_argument('--keep-archives', action='store_true', help='Retain temporary archives after restoration') + restoring.add_argument('--optional', choices=('geometry', 'occlusion', 'held-out', 'evaluation'), + help='Download only this optional component for the selected dataset') describing = commands.add_parser('catalog') describing.add_argument('--dataset', action='append', required=True, metavar='NAME=EXTENT_ROOT') describing.add_argument('--output', type=Path, required=True) @@ -853,8 +891,14 @@ def main(): publish(args.output, dict(dataset.split('=', 1) for dataset in args.dataset), args.repo, cleanup=args.cleanup) else: - download(args.repo, args.dataset, args.destination, args.revision, cleanup=args.cleanup, - bundle_root=args.bundle_root) + if args.optional and args.bundle_root: + parser.error('--optional and --bundle-root cannot be combined') + bundle_root = f'optional/{args.optional.replace("-", "_")}' if args.optional else args.bundle_root + if args.optional and args.dataset == 'all': + parser.error('Select one dataset with --dataset for an optional download') + cleanup = not args.keep_archives if bundle_root is None or args.optional else args.cleanup + download(args.repo, args.dataset, args.destination, args.revision, cleanup=cleanup, + bundle_root=bundle_root) if __name__ == '__main__': diff --git a/preprocess/slat/HUGGING_FACE.md b/preprocess/slat/HUGGING_FACE.md index dee49f8..6252056 100644 --- a/preprocess/slat/HUGGING_FACE.md +++ b/preprocess/slat/HUGGING_FACE.md @@ -1,145 +1,99 @@ -## SLAT shape: upload and download specification - -The repository contains prepared extent datasets and separate SLAT-shape targets. -Combined 32³ SLAT finetuning requires both artifact types for both training datasets. -The 6.84 GB SLAT upload contains latent targets and metadata. -It excludes RGB observations, depth maps, masks, and frozen image features. - -The sizes and coverage below describe data snapshot `0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa`. -GB means decimal gigabytes. - -| Bundle | Contents | Training archives and metadata, GB | All archives, GB | -| --- | --- | ---: | ---: | -| `bundles/3dfront` | Calibrated observations, extent geometry, and occupancy targets | 234.67 | 293.70 | -| `bundles/sage` | Calibrated observations, extent geometry, and occupancy targets | 460.59 | 510.88 | -| `precomputed_slat/3dfront` | 32³ object latents and available scene latents | 5.57 | 5.57 | -| `precomputed_slat/sage` | 32³ object latents and recorded failures | 1.27 | 1.27 | -| Total | Both datasets and both artifact types | 702.10 | 811.42 | - -Training requires each extent bundle's `metadata.tar` and `train-*.tar` archives. -Evaluation also requires its `test-*.tar` archives. -The current download command restores every archive in a bundle, including available test archives. -It has no split filter. -The four commands below therefore download about 811.42 GB. - -### Download and restore - -Use the updated PartProbe3D checkout with latent generation in `preprocess/slat/`. -Install its preprocessing dependencies and `huggingface-hub`. -Authenticate with a Hugging Face account that can access this dataset repository. -Run these commands from the repository root. - -1. Restore the prepared 3D-FRONT extent dataset. - - ```bash - python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root bundles \ - --dataset 3dfront --revision 0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa --cleanup - ``` - -2. Restore the prepared SAGE-10k extent dataset. - - ```bash - python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root bundles \ - --dataset sage --revision 0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa --cleanup - ``` - -3. Restore the 3D-FRONT shape targets. - - ```bash - python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \ - --dataset 3dfront --revision 0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa --cleanup - ``` - -4. Restore the SAGE-10k shape targets. - - ```bash - python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \ - --dataset sage --revision 0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa --cleanup - ``` - -| Dataset | Prepared observations and extent targets | SLAT targets | -| --- | --- | --- | -| 3D-FRONT | `datasets/3dfront/extent/point_cloud/` | `datasets/3dfront/slat/32/targets/` | -| SAGE-10k | `datasets/sage/extent/point_cloud/` | `datasets/sage/slat/32/targets/` | - -The updated downloader maps historical SLAT archive paths under `outputs/` to these dataset locations. -It preserves target bytes and verifies every archive's size and SHA-256 checksum. -It refuses to replace different existing files. -`--cleanup` retains one temporary archive at a time and removes it after successful restoration. -Temporary archives reside under `datasets//archives/huggingface/`. -Extracted files and future feature caches need additional disk space. - -Preserve the original extent manifests without edits. -The SLAT manifests bind their source datasets through manifest checksums. -Raw dataset archives, rendering again, and SS feature caches are unnecessary for this workflow. - -### Complete preparation before training - -The published targets cover 39,930 3D-FRONT training views and 17,456 SAGE-10k training views. -Three SAGE-10k views retain one failed object target each. -These failures block strict combined training until object encoding succeeds. -The snapshot contains scene latents for 6,720 3D-FRONT views and no SAGE-10k scenes. -The current object loss does not require completed scene encoding. - -1. Obtain the configured Pixal3D, DINOv3, and NAF weights separately. -2. Resolve the three failed SAGE-10k object targets. -3. Prepare frozen conditioning features and immutable object targets. -4. Start finetuning after feature preparation succeeds. - -The TRELLIS.2 shape encoder and paired decoder are also required when regenerating shape targets. -Image features and immutable training snapshots are not included in the uploaded target bundles. -The commands below do not automatically schedule scene encoding or training during feature preparation. +# SLAT shape reproduction data + +The public dataset provides compact observations and separate 32³ object shape targets. +The [dataset guide](../../HF_DATASETS.md) describes restoration and optional components. +The default restore command includes both artifact types for 3D-FRONT and SAGE-10k. ```bash -python -m preprocess.slat.prepare \ - --config preprocess/slat/configs/front3d_sage_32.json \ - --stage features --devices cuda:1 cuda:2 -python -m slat_multiobj_shape.train \ - --config slat_multiobj_shape/configs/front3d_sage_32.json +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed ``` -Feature preparation writes `object_targets/` and `object_features/` under each dataset's `slat/32/` directory. -It retains clean GT depth for fresh augmentation during training. -Testing uses MoGe-3 depth and calibration. -Training results reside under `outputs/`, and model checkpoints reside under `checkpoints/`. +## Restored locations + +| Artifact | Location | +| --- | --- | +| Saved observations and occupancy | `datasets//extent/point_cloud/` | +| Object shape targets | `datasets//slat/32/targets/` | +| Optional geometry | `datasets//extent/point_cloud/scenes/` | + +The extent manifests retain their original bytes and source splits. +Each shape manifest binds those extent manifests by SHA-256. +Each successful object retains its original latent values, cell coordinates, object index, and transform. +The `object_sha256` identity checks those arrays independently of scene encoding. + +The current objective uses separate object latents. +It does not require combined scene latents or scene encoding. +The compact targets retain empty scene fields for the existing file schema. +Use configurations with `require_scene_targets=false`. + +## SAGE exclusions + +The original release contains three failed object targets. +The compact release records their views as explicit exclusions: + +- `sage10k/23adeb2d2638a873e5d9` +- `sage10k/7b2d68afd83bf89364ea` +- `sage10k/ff0a565cad070014b1b8` + +These exclusions match the existing object-mean shape experiment. +The exported shape manifest makes them available to every compatible shape preset. +Shape training therefore uses 39,930 3D-FRONT views and 17,453 SAGE views. +SS and segmentation still use all 17,456 SAGE training views. -### Upload contract +## Train without an image-feature cache -`bundles//index.json` describes prepared extent archives. -`precomputed_slat//index.json` describes SLAT target archives. -Each inventory records archive sizes, SHA-256 checksums, and the restore destination. -SLAT inventories also record source manifests, codec provenance, coverage, and encoding failures. +Obtain the configured Pixal3D, DINOv3, and NAF weights separately. +Create an online configuration from the project root: -An inventory's `complete=true` means packaging covers the snapshot files. -The uploader publishes a complete inventory after every archive is present with matching size. -It also compares remote SHA-256 checksums when Hub file metadata provides them. -`source_complete` separately records whether source preprocessing finished. -An upload can therefore finish while source object or scene encoding remains incomplete. -The upload preserves failure records and pending scene statuses. +```bash +python -m preprocess.reproduction configure-shape --output outputs/reproduction/shape_online.json +CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID \ + python -m slat_multiobj_shape.train \ + --config outputs/reproduction/shape_online.json +``` + +This configuration reads the uploaded object targets and computes image conditioning during training. +It avoids separate image-feature files and frozen target copies. +It preserves the selected preset's model, sampling, and optimizer settings. +It uses separate output and checkpoint directories. +Use the original cached preset when reproducing a cached-feature experiment. + +## Train with cached image features -Package shape targets with this command: +Prepare the existing assigned-object caches with: ```bash -python -m preprocess.huggingface pack \ - --artifact-kind slat-shape-targets \ - --dataset 3dfront=datasets/3dfront/slat/32/targets \ - --dataset sage=datasets/sage/slat/32/targets \ - --output outputs/huggingface/slat_targets_publish +CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID \ + python -m preprocess.slat.prepare \ + --config preprocess/slat/configs/front3d_sage_32_assigned_object.json \ + --stage features --devices cuda:0 cuda:1 +CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID \ + python -m slat_multiobj_shape.train \ + --config slat_multiobj_shape/configs/front3d_sage_32_assigned_object.json ``` -Publish those archives to an existing dataset repository with this command: +Feature preparation needs observations, object shape targets, and the configured image encoders. +It does not need source meshes or the shape encoder. +The generated feature files and frozen target snapshots consume additional local storage. + +## Optional geometry + +Geometry is necessary when generating new shape targets or scoring decoded meshes. +Download it explicitly before these operations: ```bash -python -m preprocess.huggingface upload \ - --repo cubec/PartProbe3D-preprocessed \ - --bundle-root precomputed_slat --dataset 3dfront --dataset sage \ - --output outputs/huggingface/slat_targets_publish +python -m preprocess.huggingface download \ + --repo cubec/PartProbe3D-preprocessed --dataset 3dfront --optional geometry +python -m preprocess.huggingface download \ + --repo cubec/PartProbe3D-preprocessed --dataset sage --optional geometry ``` -The target upload excludes worker jobs, raw assets, model weights, and frozen image feature caches. -Use a fresh packaging directory when source manifests change. -Publish matching extent and target snapshots before documenting a new reproducible data revision. +New encoding also needs the configured shape encoder and paired decoder. +The public compact shape targets use a 32³ grid. +Their encoder uses a 512³ geometry grid and produces 32 channels per latent cell. + +## Historical snapshots + +The original targets remain in the deprecated folder and the original pinned revisions. +The [original upload report](../../reports/slat_targets_huggingface_20261015.md) records their coverage and codec identities. +Exact checkpoint resume requires the checkpoint's original data and feature identities. diff --git a/preprocess/slat/README.md b/preprocess/slat/README.md index 46e4436..c5f93e5 100644 --- a/preprocess/slat/README.md +++ b/preprocess/slat/README.md @@ -1,7 +1,7 @@ # SLAT preparation This stage prepares reusable training inputs for multi-object SLAT shape finetuning. -It reads the saved 3D-FRONT and SAGE-10k extent datasets after capture and voxel export. +It reads saved extent datasets from 3D-FRONT, SAGE-10k, and FoundationPose after capture and voxel export. It preserves each saved cube, object identity, and room or layout split. The generation implementation and its configurations reside in this package. @@ -11,6 +11,95 @@ The generation implementation and its configurations reside in this package. | `targets.py` | Select posed meshes, preserve the saved cube, and write object and scene targets | | `encode.py` | Convert meshes to dual grids and apply the frozen pretrained shape encoder | | `prepare.py` | Coordinate dataset phases and extract frozen conditioning features | +| `scene_targets.py` | Export one scene token per reference voxel with an explicit latent validity flag | + +## Aligned scene targets at 32³ + +The scene export combines complete meshes for all prompted objects before one frozen shape encoder processes them. +It preserves each training view's saved cube, calibration, object order, and dataset split. +Different views of one room can use different cubes. +The export therefore retains each view ID. + +Reference voxels are the union of complete occupancy for prompted objects. +The shared `prompt_object_cells` function selects these voxels from saved 64³ targets and pools them to 32³. +Unprompted objects do not add reference voxels. +Older feature caches can contain extra scene voxels from unprompted objects. +Those extra rows do not define the reference occupancy for this export. + +Each reference voxel has exactly one scene token, including voxels that contain multiple objects. +The native scene encoder can omit a small number of reference voxels because its rasterization method differs. +The export retains those coordinates with zero feature storage and `latent_valid=false`. +Training must exclude invalid rows from the latent loss. +The export does not average object latents or interpolate missing values. + +| Array | Shape | Meaning | +| --- | --- | --- | +| `coords` | `[N, 3]` | Unique reference coordinates in sorted order, stored as `uint8` | +| `feats` | `[N, 32]` | Physical scene latents stored as `float16`, with zeros at invalid rows | +| `latent_valid` | `[N]` | Boolean flag for an exact coordinate match with native scene encoding | +| `memberships` | `[N, K]` | Independent per-object voxel occupancy for the same reference rows | +| `object_ids` | `[K]` | Prompt identities in the saved order | +| `model_to_world` | `[4, 4]` | Original transform from the normalized cube to world coordinates | + +Multiple columns of `memberships` can be positive at one voxel. +They do not create additional scene tokens. + +Run the combined export from the repository root: + +```bash +python -m preprocess.slat.scene_targets \ + --config preprocess/slat/configs/scenes_32.json +``` + +The configuration selects training views only and uses GPUs 0, 1, and 2. +Sixteen CPU processes prepare meshes for six persistent GPU workers. +Each GPU hosts two encoder processes. +Each GPU worker uses four CPU threads to prepare native dual grids while the GPU encodes earlier grids. +The `mesh_workers` and `raster_workers` settings control these CPU counts. +The latter count applies separately to each GPU worker. +The `mesh_executor` setting selects CPU processes or threads. +CPU processes avoid Python thread contention during mesh preparation. +They transfer geometry and reference metadata without RGB or depth tensors. +Prefetch retains a bounded number of grids in memory. + +Mesh clipping omits plane cuts when all vertices lie strictly inside the plane. +Vertices near a clipping plane retain the original Trimesh procedure. +These changes preserve the cube, rasterization settings, encoder weights, and reference voxels. + +Its `encoder_config` selects the existing codec weights, dual-grid settings, and native Python environment. +Each dataset saves its targets under `datasets//slat/32/scene_targets/`. +The format identifier is `slat-scene-targets-v1`. +Logs and combined progress reside under `outputs/slat_scene/32/preparation/`. + +The export reuses completed native scene encodings after it checks their dataset, cube, prompts, codec, and file checksums. +Existing object caches retain their original files. +Per-view completion records support resume after an interruption. +Resume retries failed encodings and replaces corrupt output files. + +Add `--limit-per-dataset 2` for a short GPU check. +Repeat the command without that argument to complete every training view. +The command finishes active jobs before it honors SIGINT or SIGTERM. +The default storage reserve stops preparation if free space falls below 20 GiB. + +`dataloader.slat_scene.SceneTargetDataset` reads one or more exported caches without loading meshes. +It checks exact reference coordinates, occupancy labels, object identities, and cube transforms against the saved extent views. +It normalizes valid latents with the pretrained flow statistics and keeps invalid rows zero. + +### Test native latent equivalence + +Run the regression with the actual pretrained encoder: + +```bash +PARTPROBE3D_NATIVE_SLAT_TEST=1 python -m pytest \ + preprocess/tests/test_slat_native_equivalence.py -q +``` + +This test requires the native CUDA environment and existing codec checkpoints. +Set `PARTPROBE3D_NATIVE_SLAT_DEVICE` to select a GPU other than `cuda:0`. +The test compares original serial preparation with optimized clipping and four CPU threads for rasterization. +It covers inside meshes, clipped meshes, and overlapping objects encoded together. +It requires identical coordinates and identical stored `float16` latents with zero tolerance. +The normal test suite skips this GPU test unless the environment flag enables it. ## Prepared data @@ -84,8 +173,8 @@ Scene encoding preserves object failures and includes their selected meshes in t Failed objects still require successful encoding before feature extraction or finetuning. Resume preserves completed object and scene latents. -The cached training configurations supervise objects and do not require scene targets. -Configurations with `require_scene_targets=true` retain scene supervision in their feature caches. +All shape training configurations supervise object latents only. +Feature caches exclude scene supervision, while target exports retain scene latents for diagnostics. 1. Prepare targets and features for both training datasets. @@ -181,42 +270,31 @@ Training resume also checks cache provenance and latent target checksums. ## Hugging Face snapshots -The [upload and download specification](HUGGING_FACE.md) lists training dependencies, archive sizes, restoration commands, and publication requirements. - -The [preprocessed dataset repository](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/tree/main/precomputed_slat) contains separate snapshots of the available 32³ shape targets. -The snapshots preserve the original manifests, per-view checksums, object identities, and completion states. -They cover training views only. -Frozen DINOv3 and NAF feature caches still require preparation. - -| Dataset | Training views | Encoded objects | Failed objects | Completed scene views | Pending scene views | -| --- | ---: | ---: | ---: | ---: | ---: | -| 3D-FRONT | 39,930 | 240,952 | 0 | 6,720 | 33,210 | -| SAGE-10k | 17,456 | 397,203 | 3 | 0 | 17,456 | - -These counts describe the published snapshot. -Three SAGE-10k views retain one failed object each. -Pending scene records remain pending after restoration. -An archive's completion flag describes packaging and transfer, not completion of source preprocessing. - -Restore both caches from the repository root: +The [reproduction guide](HUGGING_FACE.md) describes the active compact observations and 32³ object shape targets. +The default download restores both artifact types for 3D-FRONT and SAGE-10k. +It excludes optional components and deprecated uploads. ```bash -python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \ - --dataset 3dfront --cleanup -python -m preprocess.huggingface download \ - --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \ - --dataset sage --cleanup +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed ``` -The first command restores `datasets/3dfront/slat/32/targets/`. -The second command restores `datasets/sage/slat/32/targets/`. -The downloader maps historical archive paths to these dataset locations. -Restoration verifies archive checksums and rejects replacement of different existing files. -Add `--revision ` to select a fixed Hub snapshot. +The observations restore under `datasets//extent/point_cloud/`. +The object targets restore under `datasets//slat/32/targets/`. +The extent manifests retain their original bytes and SHA-256 identities. +Object arrays retain their latent values, coordinates, instance identities, and transforms. + +Shape training uses 39,930 3D-FRONT views and 17,453 SAGE views. +The shape manifest explicitly excludes the three failed SAGE views from the existing experiment. +The compact shape export omits combined scene latents because the current object loss does not use them. +Original snapshots remain under `_deprecated/20261020/` and their pinned revisions. + +Add `--revision ` to select a fixed release. +Restoration checks archive hashes and refuses to replace different existing data. +The downloader removes temporary archives after successful extraction. -The corresponding extent datasets remain in the repository's `bundles/` directory. -Shape target loaders require those source datasets and matching manifests. +Image features require local preparation or online extraction during training. +Mesh geometry requires an explicit `--optional geometry` download for target regeneration or mesh scoring. +See the reproduction guide for the online shape configuration and cached feature commands. ## Training and testing diff --git a/preprocess/validate_dataset.py b/preprocess/validate_dataset.py index d9131c6..7eac2ea 100644 --- a/preprocess/validate_dataset.py +++ b/preprocess/validate_dataset.py @@ -28,11 +28,16 @@ def _validate_view(root, row): sample = vd.canonical_sample(vd.load_npz(root / row['sample']), gt) folder = root / row['view_directory'] stamp = json.loads((folder / 'complete.json').read_text()) + compact = (root / 'compact_training.json').exists() + required = {Path(row['sample']).name, Path(row['camera']).name, 'objects.json'} for filename, checksum in stamp['sha256'].items(): + if compact and filename not in required: + continue if sha256(folder / filename) != checksum: raise ValueError(f'Checksum mismatch: {folder / filename}') - with Image.open(folder / 'rgb.png') as im: - np.testing.assert_array_equal(np.asarray(im), sample['rgb']) + if not compact: + with Image.open(folder / 'rgb.png') as im: + np.testing.assert_array_equal(np.asarray(im), sample['rgb']) for name, key in (('instance_labels.png', 'image_labels'), ('support_instance_labels.png', 'all_image_labels')): if (folder / name).exists(): @@ -50,8 +55,11 @@ def _validate_view(root, row): table = json.loads((folder / 'objects.json').read_text())['prompts'] for prompt in table: k = prompt['prompt_index'] - with Image.open(folder / prompt['mask']) as im: - mask = np.asarray(im) + if compact: + mask = (sample['image_labels'] == k).astype(np.uint8) * 255 + else: + with Image.open(folder / prompt['mask']) as im: + mask = np.asarray(im) np.testing.assert_array_equal(mask != 0, sample['image_labels'] == k) if set(np.unique(mask)) - {0, 255}: raise ValueError('Mask PNG is not lossless binary') @@ -146,9 +154,11 @@ def validate(root, *, write_card=True, workers=DEFAULT_WORKERS): """Check all views with isolated CPU workers and publish one complete report.""" if not isinstance(workers, int) or isinstance(workers, bool) or workers < 1: raise ValueError('Validation workers must be a positive integer') + selection_path = Path(root) / 'compact_training.json' + selection_sha256 = sha256(selection_path) if selection_path.exists() else None dataset = ViewDataset(root) rows = dataset.views - if len(rows) != dataset.manifest["expected_views"]: + if len(dataset.manifest['views']) != dataset.manifest["expected_views"]: raise ValueError("Completed manifest has the wrong capture count") if len({Path(r["file"]).name for r in rows}) != len(rows): raise ValueError("Sample filenames collide in a feature cache") @@ -185,9 +195,38 @@ def validate(root, *, write_card=True, workers=DEFAULT_WORKERS): "checks": ["artifact hashes", "RGB/depth/label alignment", "binary mask/object identity", "sparse/dense occupancy equality", "shared scene GT and prompt columns", "scene split separation", "unique cache filenames"]} + current_selection_sha256 = sha256(selection_path) if selection_path.exists() else None + if current_selection_sha256 != selection_sha256: + raise ValueError('Restored view selection changed during validation') + if selection_sha256 is not None: + restored_counts = {split: { + 'scenes': len({row['scene'] for row in rows if row['split'] == split}), + 'views': sum(row['split'] == split for row in rows)} + for split in sorted({row['split'] for row in rows})} + report.update(scope='restored_compact_views', full_validation=len(rows) == dataset.manifest['expected_views'], + source_views=dataset.manifest['expected_views'], source_counts=report['counts'], + counts=restored_counts, selection_sha256=selection_sha256) vd.write_json(dataset.root / "validation.json", report) if not write_card: return report + if report.get('scope') == 'restored_compact_views': + card = [f"# {dataset.manifest['dataset']} compact observations", '', + f'The validator checked {images} views, {len(scenes)} scenes, and {mask_count} prompt masks.', + 'The table describes restored views.', + f"The original source manifest lists {report['source_views']} views.", '', + '| Split | Scenes | Views |', '| --- | ---: | ---: |'] + for split, counts in report['counts'].items(): + card.append(f"| {split} | {counts['scenes']} | {counts['views']} |") + card.extend(['', 'Sample NPZ files contain RGB, depth, visible labels, and per-object occupancy.', + 'Saved calibration and object mappings remain available.', + 'The samples retain hidden object surfaces and overlapping labels.', + 'NPZ labels use zero-based object indices and -1 for context.', + 'The default training download omits separate PNG, depth, and mesh exports.', + 'The export preserves the original manifest bytes.', '', + '[Source inventory](manifest.json).', + '[Validation report](validation.json).', '']) + (dataset.root / 'DATASET_CARD.md').write_text('\n'.join(card)) + return report card = [f"# {dataset.manifest['dataset']} — converted per-view dataset", "", f"Schema: `{vd.SCHEMA}`. Validated **{images} captures**, **{len(scenes)} scenes**, " f"and **{mask_count} binary object masks**.", "", diff --git a/preprocess/reproduction.py b/preprocess/reproduction.py new file mode 100644 index 0000000..fd0ccd7 --- /dev/null +++ b/preprocess/reproduction.py @@ -0,0 +1,671 @@ +"""Publish compact training data and explicit optional components on Hugging Face.""" +import argparse +from collections import Counter, defaultdict +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy +import hashlib +import json +import os +from pathlib import Path +import subprocess + +from preprocess.huggingface import SCHEMA, _archive, _json, _relative, _retry +from preprocess.storage import atomic_json +from utils.hashing import sha256 + + +RECIPE_SCHEMA = 'partprobe3d.reproduction.v1' +COMPACT_SCHEMA = 'partprobe3d.compact-training.v1' +DEFAULT_REPO = 'cubec/PartProbe3D-preprocessed' +DEFAULT_DATASETS = ('3dfront', 'sage') +LEGACY_PREFIX = '_deprecated/20261020' +LEGACY_REVISION = 'd13e577a7e71291ed94fa40e4297f54106577fbd' + + +def refresh_selection(root): + """Identify restored views without changing the original manifest bytes.""" + root = Path(root) + path = root / 'manifest.json' + if not path.exists(): + return + manifest = _json(path) + rows = [row for row in manifest['views'] + if all((root / row[key]).is_file() for key in ('sample', 'camera', 'scene_gt', 'object_table'))] + atomic_json(root / 'compact_training.json', { + 'schema': COMPACT_SCHEMA, 'source_manifest_sha256': sha256(path), + 'view_ids': [row['id'] for row in rows], + 'counts': dict(Counter(row['split'] for row in rows)), + 'geometry_included': False, 'observations': 'RGB, depth and labels in sample NPZ files'}) + + +def stage_observations(source, staged, *, monitor_views=16): + """Index original training files for direct streaming without another dataset copy.""" + source, staged = Path(source).resolve(), Path(staged).resolve() + manifest = _json(source / 'manifest.json') + if (not manifest.get('complete') or len(manifest['views']) != manifest['expected_views'] + or monitor_views < 1): + raise ValueError('A complete source and a positive monitoring count are required') + original_hash = sha256(source / 'manifest.json') + + def scene_groups(groups): + # Follow the original scene archive order to avoid random HDD seeks. + scenes = {source / row['sample']: row['scene'] for row in manifest['views']} + paths_by_scene, counts = defaultdict(set), Counter() + for label, paths, count in groups: + scene = next(scenes[path] for path in paths if path in scenes) + paths_by_scene[label, scene].update(paths) + counts[label, scene] += count + return [(label, sorted(paths), counts[label, scene]) + for (label, scene), paths in sorted(paths_by_scene.items())] + staged.mkdir(parents=True, exist_ok=True) + inventory_path = staged / 'stream_inventory.json' + if inventory_path.exists(): + saved = _json(inventory_path) + if (saved.get('source_manifest_sha256') == original_hash and saved.get('monitor_views') == monitor_views + and saved.get('source_root') == str(source)): + decode = lambda groups: [(label, [source / _relative(path) for path in paths], count) + for label, paths, count in groups] + return (manifest, [source / _relative(path) for path in saved['metadata']], + scene_groups(decode(saved['core'])), scene_groups(decode(saved['held_out'])), + {source / _relative(path): digest for path, digest in saved['checksums'].items()}) + metadata = [source / name for name in ('manifest.json', 'conversion_policy.json') if (source / name).exists()] + core, held_out, checksums = [], [], {} + monitor_ids = {row['id'] for row in [row for row in manifest['views'] if row['split'] != 'train'][:monitor_views]} + + def inspect_view(row): + selected = row['split'] == 'train' or row['id'] in monitor_ids + label = 'train' if row['split'] == 'train' else 'monitor' if selected else 'held-out' + folder = source / _relative(row['view_directory']) + marker = folder / 'complete.json' + stamp = _json(marker) + if stamp['row']['id'] != row['id']: + raise ValueError(f'Completion record differs from the source view: {row["id"]}') + paths = {source / _relative(row[key]) for key in ('sample', 'camera', 'scene_gt', 'object_table')} + paths.update((folder / 'objects.json', marker)) + expected = {source / row[key]: stamp['sha256'][str(Path(row[key]).relative_to(row['view_directory']))] + for key in ('sample', 'camera')} + expected[folder / 'objects.json'] = stamp['sha256']['objects.json'] + target_marker = (source / row['scene_gt']).with_name('complete.json') + if target_marker.exists(): + paths.add(target_marker) + target_digest = _json(target_marker).get('sha256') + if isinstance(target_digest, str): + expected[source / row['scene_gt']] = target_digest + return selected, (label, sorted(paths), 1), expected + + with ThreadPoolExecutor(max_workers=16) as pool: + for number, (selected, group, expected) in enumerate(pool.map(inspect_view, manifest['views']), 1): + (core if selected else held_out).append(group) + checksums.update(expected) + if number % 5000 == 0: + print(f'INDEXED {manifest["dataset"]}: {number}/{len(manifest["views"])} views', flush=True) + core, held_out = scene_groups(core), scene_groups(held_out) + if sha256(source / 'manifest.json') != original_hash: + raise ValueError('Source manifest changed during observation indexing') + encode = lambda groups: [(label, [str(path.relative_to(source)) for path in paths], count) + for label, paths, count in groups] + atomic_json(inventory_path, {'source_manifest_sha256': original_hash, 'source_root': str(source), + 'monitor_views': monitor_views, 'metadata': [str(path.relative_to(source)) for path in metadata], + 'core': encode(core), 'held_out': encode(held_out), + 'checksums': {str(path.relative_to(source)): digest for path, digest in checksums.items()}}) + return manifest, metadata, core, held_out, checksums + + +def stage_shape(source, staged): + """Preserve object arrays and record existing failures as explicit exclusions.""" + import numpy as np + from slat_multiobj_shape.storage import object_sha256, read_view_targets + + source, staged = Path(source).resolve(), Path(staged).resolve() + original = _json(source / 'manifest.json') + source_hash = sha256(source / 'manifest.json') + receipt = staged / 'export.json' + if receipt.exists() and _json(receipt).get('source_manifest_sha256') == source_hash: + manifest = _json(staged / 'manifest.json') + else: + manifest = deepcopy(original) + manifest.update(entries={}, target_scope='objects', phase='objects', phase_complete=True, + complete=False, excluded_views=sorted(set(original.get('excluded_views', [])) | { + key for key, row in original['entries'].items() if row.get('failed_objects')})) + manifest['export'] = {'source_manifest_sha256': source_hash, 'scene_latents_included': False, + 'object_arrays_unchanged': True} + def export_view(item): + key, row = item + path = source / _relative(row['file']) + if sha256(path) != row['sha256']: + raise ValueError(f'Original shape target checksum changed: {key}') + arrays = read_view_targets(path) + identity = object_sha256(arrays) + arrays.update(scene_coords=np.empty((0, 3), np.uint8), scene_feats=np.empty((0, 32), np.float16), + scene_status=np.array('pending'), scene_seconds=np.array(0.), + scene_dual_voxels=np.array(0), scene_error=np.array('')) + output = staged / _relative(row['file']) + output.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(output, **arrays) + if object_sha256(read_view_targets(output)) != identity: + raise ValueError(f'Object shape arrays changed during export: {key}') + entry = {**row, 'sha256': sha256(output), 'object_sha256': identity, + 'scene_status': 'pending', 'scene_latent_cells': 0, 'scene_seconds': 0.} + atomic_json(output.with_suffix('.complete.json'), entry) + return key, entry + selected = sorted(((key, row) for key, row in original['entries'].items() + if key not in manifest['excluded_views']), key=lambda item: (item[1]['scene'], item[0])) + with ThreadPoolExecutor(max_workers=8) as pool: + for number, (key, entry) in enumerate(pool.map(export_view, selected), 1): + manifest['entries'][key] = entry + if number % 5000 == 0: + print(f'SHAPE {source.parent.parent.parent.name}: {number}/{len(selected)}', flush=True) + if sha256(source / 'manifest.json') != source_hash: + raise ValueError('Source manifest changed during shape export') + atomic_json(staged / 'manifest.json', manifest) + atomic_json(receipt, manifest['export']) + groups, checksums = [], {} + for key, row in manifest['entries'].items(): + path = staged / _relative(row['file']) + groups.append(('train', [path, path.with_suffix('.complete.json')], 1)) + checksums[path] = row['sha256'] + return manifest, [staged / 'manifest.json', receipt], groups, checksums + + +def package(root, output, component, name, *, destination, kind, metadata, groups, + details=None, checksums=None, shard_bytes=1024**3, publisher=None): + """Write deterministic shards and publish them with bounded temporary storage.""" + root, output = Path(root).resolve(), Path(output).resolve() + folder = output / _relative(component) / name + folder.mkdir(parents=True, exist_ok=True) + path = folder / 'index.json' + old = _json(path) if path.exists() else {} + identity = {'destination': str(destination), 'artifact_kind': kind, **(details or {})} + if old and any(old.get(key) != value for key, value in identity.items()): + raise ValueError(f'Package source changed. Select another output: {component}/{name}') + previous = {row['file']: row for row in old.get('archives', [])} + index = {'schema': SCHEMA, 'name': name, 'complete': False, **identity, 'archives': []} + atomic_json(path, index) + + def save(label, files, views): + filename = label + '.tar' + files = sorted(set(files)) + old_record = previous.get(filename) + remote_path = f'{component}/{name}/{filename}' + reusable = False + if old_record and publisher and publisher.matches(remote_path, old_record): + records = [] + for file in files: + saved = file.stat() + records.append((str(file.relative_to(root)), saved.st_size, saved.st_mtime_ns)) + reusable = old_record.get('identity') == hashlib.sha256(json.dumps(records).encode()).hexdigest() + if reusable: + record = old_record + else: + record = _archive(folder / filename, files, root, Path(destination), old_record, checksums=checksums) + record['views'] = views + index['archives'].append(record) + atomic_json(path, index) + print(f'PACKED {remote_path}: {record["bytes"]/1e9:.3f} GB, {views} views', flush=True) + if publisher: + publisher.ready(remote_path, folder / filename, record) + + if metadata: + save('metadata', metadata, 0) + emitted, paths, size, views, label, number = set(), [], 0, 0, None, 0 + for group_label, group_files, group_views in groups: + fresh = [path for path in group_files if path not in emitted] + required = sum(path.stat().st_size + 1024 for path in fresh) + if paths and (label != group_label or size + required > shard_bytes): + save(f'{label}-{number:05d}', paths, views) + paths, size, views, number = [], 0, 0, number + 1 + emitted.update(fresh) + label = group_label + paths.extend(fresh) + size += required + views += group_views + if paths: + save(f'{label}-{number:05d}', paths, views) + if publisher: + publisher.flush() + index.update(complete=True, bytes=sum(row['bytes'] for row in index['archives'])) + atomic_json(path, index) + if publisher: + publisher.small(f'{component}/{name}/index.json', path) + return index + + +class Publisher: + """Verify remote SHA-256 identities before deleting local transfer shards.""" + def __init__(self, repo, *, cleanup=True, workers=4): + from huggingface_hub import HfApi + self.repo, self.api, self.cleanup, self.workers = repo, HfApi(), cleanup, workers + self.remote = {item.rfilename: item for item in self.api.dataset_info(repo, files_metadata=True).siblings} + self.pending = [] + + def matches(self, path, record): + existing = self.remote.get(path) + return bool(existing and existing.size == record['bytes'] and existing.lfs + and existing.lfs.sha256 == record['sha256']) + + def ready(self, remote_path, local_path, record): + if self.matches(remote_path, record): + if self.cleanup: + local_path.unlink(missing_ok=True) + return + self.pending.append((remote_path, local_path, record)) + if len(self.pending) >= 8: + self.flush() + + def flush(self): + from huggingface_hub import CommitOperationAdd + if not self.pending: + return + batch = self.pending + print(f'UPLOADING {len(batch)} archives, {sum(row[2]["bytes"] for row in batch)/1e9:.3f} GB', flush=True) + _retry(lambda: self.api.create_commit(repo_id=self.repo, repo_type='dataset', + operations=[CommitOperationAdd(path_in_repo=remote, path_or_fileobj=local) + for remote, local, record in batch], num_threads=self.workers, + commit_message='Upload compact reproduction archives')) + entries = _retry(lambda: self.api.get_paths_info(self.repo, [row[0] for row in batch], repo_type='dataset')) + self.remote.update({entry.path: entry for entry in entries}) + # RepoFile uses path, while RepoSibling uses rfilename. Both expose size and lfs. + for remote, local, record in batch: + if not self.matches(remote, record): + raise ValueError(f'Remote archive verification failed: {remote}') + if self.cleanup: + local.unlink() + self.pending = [] + + def small(self, remote_path, local_path): + _retry(lambda: self.api.upload_file(repo_id=self.repo, repo_type='dataset', + path_in_repo=remote_path, path_or_fileobj=local_path, + commit_message=f'Publish {remote_path}')) + + +def download_training(repo, name, destination, revision='main', *, cleanup=True): + """Restore only active training components. Optional and deprecated paths stay untouched.""" + from huggingface_hub import HfApi, hf_hub_download + from preprocess.huggingface import download + revision = HfApi().dataset_info(repo, revision=revision).sha + cache = Path(destination).resolve() / 'outputs/huggingface/reproduction' + path = hf_hub_download(repo, 'training/index.json', repo_type='dataset', revision=revision, local_dir=cache) + recipe = _json(path) + if recipe.get('schema') != RECIPE_SCHEMA or not recipe.get('complete'): + raise ValueError('The active training inventory is incomplete') + names = recipe['default_datasets'] if name == 'all' else [name] + restored = [] + for dataset in names: + if dataset not in recipe['datasets']: + raise ValueError(f'Unknown training dataset: {dataset}') + for component in recipe['datasets'][dataset]['required']: + relative = _relative(component) + if relative.parts[0] != 'training' or relative.name != dataset: + raise ValueError('Default downloads must remain in the active training folder') + restored.append(download(repo, dataset, destination, revision, cleanup=cleanup, + bundle_root=str(relative.parent))) + return restored + + +def publish(repo, output, names, *, monitor_views=16, optional=True, shard_bytes=1024**3, workers=4): + """Publish compact observations, object targets and separate optional components.""" + output = Path(output).resolve() + output.mkdir(parents=True, exist_ok=True) + publisher = Publisher(repo, workers=workers) + recipe = {'schema': RECIPE_SCHEMA, 'complete': False, 'default_datasets': list(DEFAULT_DATASETS), + 'monitor_views_per_dataset': monitor_views, 'datasets': {}, 'optional': {}, + 'base_git_revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()} + status = output / 'status.json' + atomic_json(status, {'phase': 'running', 'repo': repo, 'pid': os.getpid()}) + for name in names: + source = Path('datasets') / name / 'extent/point_cloud' + staged = output / 'staging' / name / 'extent/point_cloud' + manifest, metadata, core, held_out, checksums = stage_observations(source, staged, monitor_views=monitor_views) + digest = sha256(source / 'manifest.json') + destination = Path('datasets') / name / 'extent/point_cloud' + details = {'source_manifest_sha256': digest, 'resolution': manifest['resolution'], + 'source_views': len(manifest['views']), 'views': sum(row[2] for row in core), + 'monitor_views': sum(row[2] for row in core if row[0] == 'monitor'), + 'training_views': sum(row[2] for row in core if row[0] == 'train')} + index = package(source, output, 'training/observations', name, destination=destination, + kind='compact-training', metadata=metadata, groups=core, details=details, + checksums=checksums, shard_bytes=shard_bytes, publisher=publisher) + record = {'required': [f'training/observations/{name}'], 'bytes': index['bytes'], **details} + shape = Path('datasets') / name / 'slat/32/targets' + if (shape / 'manifest.json').exists(): + shape_stage = output / 'staging' / name / 'slat/32/targets' + targets, shape_metadata, groups, target_checksums = stage_shape(shape, shape_stage) + shape_index = package(shape_stage, output, 'training/shape/32', name, + destination=Path('datasets') / name / 'slat/32/targets', kind='object-shape-targets', + metadata=shape_metadata, groups=groups, checksums=target_checksums, + details={'source_manifest_sha256': sha256(shape / 'manifest.json'), 'resolution': 32, + 'views': len(targets['entries']), 'excluded_views': targets['excluded_views'], + 'dataset_manifest_sha256': digest, 'scene_latents_included': False}, + shard_bytes=shard_bytes, publisher=publisher) + record['required'].append(f'training/shape/32/{name}') + record['bytes'] += shape_index['bytes'] + record['shape_excluded_views'] = targets['excluded_views'] + recipe['datasets'][name] = record + if optional: + if held_out: + held_index = package(source, output, 'optional/held_out', name, destination=destination, + kind='held-out-observations', metadata=[], groups=held_out, checksums=checksums, + details={'source_manifest_sha256': digest, 'views': sum(row[2] for row in held_out)}, + shard_bytes=shard_bytes, publisher=publisher) + recipe['optional'][f'held_out/{name}'] = {'component': f'optional/held_out/{name}', + 'bytes': held_index['bytes']} + geometry = sorted({source.resolve() / row['geometry'] for row in manifest['views']}) + if geometry and all(path.exists() for path in geometry): + from dataloader.geometry import geometry_artifacts + groups = [('geometry', geometry_artifacts(source, str(path.relative_to(source.resolve()))), 0) + for path in geometry] + geometry_index = package(source, output, 'optional/geometry', name, destination=destination, + kind='mesh-geometry', metadata=[], groups=groups, + details={'source_manifest_sha256': digest}, shard_bytes=shard_bytes, publisher=publisher) + recipe['optional'][f'geometry/{name}'] = {'component': f'optional/geometry/{name}', + 'bytes': geometry_index['bytes']} + atomic_json(output / 'training/index.json', recipe) + atomic_json(status, {'phase': 'running', 'repo': repo, 'pid': os.getpid(), 'finished_dataset': name, + 'datasets': list(recipe['datasets'])}) + recipe['complete'] = True + atomic_json(output / 'training/index.json', recipe) + publisher.small('training/index.json', output / 'training/index.json') + atomic_json(status, {'phase': 'data_uploaded', 'repo': repo, 'pid': os.getpid(), + 'revision': publisher.api.dataset_info(repo).sha, 'datasets': recipe['datasets']}) + return recipe + + +def publish_evaluation(repo, output): + """Publish YCB-V scoring inputs without duplicate image and depth files.""" + from dataloader.geometry import geometry_artifacts + output = Path(output).resolve() + source = Path('datasets/ycbv/extent/point_cloud') + ready = output / 'optional/evaluation/ycbv/index.json' + if ready.exists(): + previous = _json(ready) + if previous.get('complete') and previous.get('source_manifest_sha256') == sha256(source / 'manifest.json'): + remote = Publisher(repo) + if all(remote.matches(f'optional/evaluation/ycbv/{row["file"]}', row) for row in previous['archives']): + return {'component': 'optional/evaluation/ycbv', 'bytes': previous['bytes']} + staged = output / 'staging/ycbv/extent/point_cloud' + manifest, metadata, groups, _, checksums = stage_observations(source, staged, monitor_views=1000000) + for relative in sorted({row['geometry'] for row in manifest['views']}): + files = geometry_artifacts(source, relative) + groups.append(('geometry', files, 0)) + index = package(source, output, 'optional/evaluation', 'ycbv', + destination=Path('datasets/ycbv/extent/point_cloud'), kind='compact-training', metadata=metadata, + groups=groups, checksums=checksums, details={'source_manifest_sha256': sha256(source / 'manifest.json'), + 'evaluation_only': True, 'views': len(manifest['views']), 'geometry_included': True}, + publisher=Publisher(repo)) + return {'component': 'optional/evaluation/ycbv', 'bytes': index['bytes']} + + +def _copy_files(api, repo, output, mapping, *, revision=LEGACY_REVISION, remove_sources=False): + """Copy LFS objects on the server and transfer only small Git files.""" + from huggingface_hub import CommitOperationAdd, CommitOperationCopy, CommitOperationDelete, hf_hub_download + source_info = api.dataset_info(repo, revision=revision, files_metadata=True) + sources = {row.rfilename: row for row in source_info.siblings} + current = {row.rfilename: row for row in api.dataset_info(repo, files_metadata=True).siblings} + operations = [] + commits = [] + + def flush(): + if operations: + result = _retry(lambda: api.create_commit(repo_id=repo, repo_type='dataset', operations=list(operations), + commit_message='Move superseded dataset uploads to the deprecated folder' if remove_sources + else 'Separate optional GT occlusion archives')) + commits.append(result.oid) + operations.clear() + + for source, target in mapping.items(): + original = sources[source] + existing = current.get(target) + matches = bool(existing and existing.size == original.size and ( + existing.lfs.sha256 == original.lfs.sha256 if original.lfs and existing.lfs + else existing.blob_id == original.blob_id)) + if existing and not matches: + raise ValueError(f'Existing destination differs from the historical file: {target}') + if not matches: + if original.lfs: + operations.append(CommitOperationCopy(src_path_in_repo=source, path_in_repo=target, + src_revision=revision)) + else: + local = hf_hub_download(repo, source, repo_type='dataset', revision=revision, + local_dir=Path(output) / 'historical_metadata') + operations.append(CommitOperationAdd(path_in_repo=target, path_or_fileobj=local)) + if remove_sources and source in current: + old = current[source] + same = old.lfs.sha256 == original.lfs.sha256 if old.lfs and original.lfs else old.blob_id == original.blob_id + if not same: + raise ValueError(f'The legacy source changed during migration: {source}') + operations.append(CommitOperationDelete(path_in_repo=source)) + if len(operations) >= 100: + flush() + flush() + return commits + + +def export_code(output, base_revision): + """Export only this migration's source changes, preserving unrelated workspace edits.""" + output = Path(output) + folder = output / 'code' + folder.mkdir(parents=True, exist_ok=True) + tracked = ['HF_DATASETS.md', 'preprocess/slat/HUGGING_FACE.md', 'preprocess/slat/README.md', 'dataloader/dataset.py', + 'dataloader/extent.py', 'preprocess/huggingface.py', 'preprocess/validate_dataset.py'] + added = ['preprocess/reproduction.py', 'preprocess/tests/test_reproduction.py'] + content = subprocess.check_output(['git', 'diff', '--binary', base_revision, '--', *tracked, *added]) + for path in added: + present = subprocess.run(['git', 'cat-file', '-e', f'{base_revision}:{path}'], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 + indexed = subprocess.run(['git', 'ls-files', '--error-unmatch', path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 + if present or indexed: + continue + result = subprocess.run(['git', 'diff', '--binary', '--no-index', '--', '/dev/null', path], + stdout=subprocess.PIPE, check=False) + if result.returncode not in (0, 1): + raise RuntimeError(f'Cannot export restore source: {path}') + content += result.stdout + patch = folder / 'reproduction.patch' + patch.write_bytes(content) + manifest = {'base_git_revision': base_revision, 'patch_sha256': sha256(patch), + 'files': {path: sha256(path) for path in [*tracked, *added]}} + atomic_json(folder / 'manifest.json', manifest) + return manifest + + +def write_card(output, recipe, repo): + """Write the active download instructions with measured archive sizes.""" + output = Path(output) + total = sum(recipe['datasets'][name]['bytes'] for name in recipe['default_datasets']) + lines = ['---', 'language:', '- en', 'tags:', '- 3d', '- depth', '- segmentation', + '- voxel-occupancy', 'pretty_name: PartProbe3D compact reproduction data', '---', '', + '# PartProbe3D reproduction data', '', + 'This release supports SS, generative SLAT segmentation, and 32³ SLAT shape training.', + f'The default transfer is **{total/1e9:.2f} GB**, including both training datasets and object shape targets.', + 'Default downloads exclude optional and deprecated folders.', '', + '## Restore tools', '', + f'Use the project checkout at Git revision `{recipe["base_git_revision"]}`.', + 'Apply the supplied restore patch before using the compact data.', + 'The patch preserves unrelated files and adds the compact readers and download commands.', '', + '```bash', f'hf download {repo} code/reproduction.patch --repo-type dataset --local-dir outputs/huggingface/bootstrap', + 'git apply --check outputs/huggingface/bootstrap/code/reproduction.patch', + 'git apply outputs/huggingface/bootstrap/code/reproduction.patch', + "python -m pip install -e '.[preprocess,ss-multiobj-depth,slat-segvigen,slat-multiobj-shape]'", '```', '', + 'The [source manifest](code/manifest.json) records the patch checksum and required Git revision.', '', + '## Default download', '', 'Run this command from the patched project root:', '', '```bash', + f'python -m preprocess.huggingface download --repo {repo}', '```', '', + 'The command restores 3D-FRONT, SAGE-10k, and their 32³ object shape targets.', + 'It verifies each archive and removes temporary archives after restoration.', + 'The downloader pins one Hub revision before reading any archive.', + 'Add `--revision ` to select a fixed release.', + 'Add `--keep-archives` only when you need temporary transfer files.', '', + '| Dataset | SS/segmentation training views | Shape training views | Monitoring views | Transfer, GB |', + '| --- | ---: | ---: | ---: | ---: |'] + for name, row in recipe['datasets'].items(): + shape_views = row['training_views'] - len(row.get('shape_excluded_views', [])) if len(row['required']) > 1 else 'Unavailable' + lines.append(f'| {name} | {row["training_views"]:,} | {shape_views if isinstance(shape_views, str) else format(shape_views, ",")} | {row["monitor_views"]} | {row["bytes"]/1e9:.2f} |') + lines += ['', 'FoundationPose requires explicit selection and supports SS and segmentation.', '', '```bash', + f'python -m preprocess.huggingface download --repo {repo} --dataset foundationpose', '```', '', + '## Contents', '', + 'Sample NPZ files retain RGB, metric depth, visible labels, complete object occupancy, and the original transforms.', + 'Calibration, scene voxel targets, object mappings, and original extent manifests remain available.', + 'The compact export omits separate RGB, masks, depth copies, overlays, and duplicate voxel exports.', + 'Every training view remains available to SS and segmentation.', + 'The first 16 test views per dataset support existing eight-view and sixteen-view training monitors.', + 'All other test observations require an optional download.', '', + 'Object shape arrays retain their original values and identities.', + 'Shape manifests explicitly exclude the three failed SAGE views used by the existing experiment.', + 'SS and segmentation retain those views.', + 'The export omits combined scene latents because the current shape objective uses object targets.', + 'Model weights and image-feature caches remain separate dependencies.', '', + '## Optional components', '', + '| Component | Purpose | Transfer, GB |', '| --- | --- | ---: |'] + descriptions = {'geometry': 'Mesh scoring and new target encoding', 'held_out': 'Remaining test observations', + 'occlusion': 'GT relations for SS object attention', 'evaluation': 'YCB-V mesh evaluation'} + for name, row in sorted(recipe['optional'].items()): + lines.append(f'| `{name}` | {descriptions[name.split("/")[0]]} | {row["bytes"]/1e9:.3f} |') + lines += ['', 'Restore observations before geometry, occlusion, or test overlays.', + 'YCB-V evaluation includes its own observations and geometry.', 'Select each optional component explicitly:', '', + '```bash', f'python -m preprocess.huggingface download --repo {repo} --dataset sage --optional geometry', + f'python -m preprocess.huggingface download --repo {repo} --dataset 3dfront --optional occlusion', + f'python -m preprocess.huggingface download --repo {repo} --dataset sage --optional held-out', + f'python -m preprocess.huggingface download --repo {repo} --dataset ycbv --optional evaluation', '```', '', + '## Train all three stages', '', + 'Obtain the configured model weights separately.', 'Run SS preparation before SS training.', '', + '```bash', 'export CUDA_VISIBLE_DEVICES=4,6', 'export CUDA_DEVICE_ORDER=PCI_BUS_ID', + 'python -m ss_multiobj_depth.prepare --config ss_multiobj_depth/configs/front3d_sage.json', + 'python -m ss_multiobj_depth.train --config ss_multiobj_depth/configs/front3d_sage.json', + 'python -m slat_segvigen.train --config slat_segvigen/configs/object_mean_image_nora_coverage_gate.json', + 'python -m preprocess.slat.prepare --config preprocess/slat/configs/front3d_sage_32_assigned_object.json --stage features --devices cuda:0 cuda:1', + 'python -m slat_multiobj_shape.train --config slat_multiobj_shape/configs/front3d_sage_32_assigned_object.json', '```', '', + 'Use the saved configuration and pretrained assets for a specific experiment.', + 'Feature preparation creates local caches without meshes or another dataset download.', + 'For lower local storage, generate an online shape configuration:', '', '```bash', + 'python -m preprocess.reproduction configure-shape --output outputs/reproduction/shape_online.json', + 'python -m slat_multiobj_shape.train --config outputs/reproduction/shape_online.json', '```', '', + 'The generated configuration computes image conditioning during training and avoids separate image-feature caches.', + 'It preserves the selected preset\'s model and optimization settings.', + 'Use the original cached preset when reproducing a cached-feature experiment.', + 'Data and decoder provenance remain in the restored manifests.', + 'Exact checkpoint resume requires the original matching feature and data identities.', '', + '## Deprecated uploads', '', + f'`{LEGACY_PREFIX}/` contains superseded bundles and catalogs.', + 'The project downloader never selects these paths.', + 'An unfiltered Hugging Face snapshot download includes every folder.', + 'Use the project downloader for minimal transfer.', + f'The [original release](https://huggingface.co/datasets/{repo}/tree/{LEGACY_REVISION}) remains available by revision.', '', + '## Source terms and previews', '', + 'Source dataset terms continue to apply to these derived observations.', + 'The prepared data does not replace access agreements for original source assets.', '', + '![3D-FRONT RGB](previews/3dfront/train-rgb.png)', '', + '![3D-FRONT visible masks](previews/3dfront/train-overlay.png)', '', + '[Posed object geometry](previews/3dfront/train-geometry.glb)', ''] + (output / 'README.md').write_text('\n'.join(lines)) + + +def finalize(repo, output, *, deprecate=False): + """Verify active artifacts before moving any legacy file.""" + from huggingface_hub import HfApi, hf_hub_download + output = Path(output).resolve() + recipe = _json(output / 'training/index.json') + if not recipe.get('complete'): + raise ValueError('Complete training publication before finalizing the repository') + api = HfApi() + legacy = api.dataset_info(repo, revision=LEGACY_REVISION, files_metadata=True) + copies = {row.rfilename: row.rfilename.replace('precomputed_occlusion/', 'optional/occlusion/', 1) + for row in legacy.siblings if row.rfilename.startswith('precomputed_occlusion/') + and (row.rfilename.endswith('.tar') or row.rfilename.endswith('/index.json'))} + _copy_files(api, repo, output, copies) + for name in DEFAULT_DATASETS: + path = hf_hub_download(repo, f'precomputed_occlusion/{name}/index.json', repo_type='dataset', + revision=LEGACY_REVISION, local_dir=output / 'historical_metadata') + recipe['optional'][f'occlusion/{name}'] = {'component': f'optional/occlusion/{name}', 'bytes': _json(path)['bytes']} + recipe['optional']['evaluation/ycbv'] = publish_evaluation(repo, output) + publisher = Publisher(repo) + components = [part for row in recipe['datasets'].values() for part in row['required']] + components += [row['component'] for row in recipe['optional'].values()] + verified = [] + for component in components: + path = hf_hub_download(repo, f'{component}/index.json', repo_type='dataset', local_dir=output / 'verification') + index = _json(path) + if not index.get('complete'): + raise ValueError(f'Incomplete component: {component}') + for row in index['archives']: + if not publisher.matches(f'{component}/{row["file"]}', row): + raise ValueError(f'Remote archive mismatch: {component}/{row["file"]}') + verified.append({'component': component, 'archives': len(index['archives']), 'bytes': index['bytes']}) + code = export_code(output, recipe['base_git_revision']) + publisher.small('code/reproduction.patch', output / 'code/reproduction.patch') + publisher.small('code/manifest.json', output / 'code/manifest.json') + atomic_json(output / 'training/index.json', recipe) + publisher.small('training/index.json', output / 'training/index.json') + write_card(output, recipe, repo) + publisher.small('README.md', output / 'README.md') + commits = [] + if deprecate: + prefixes = ('bundles/', 'precomputed_slat/', 'precomputed_occlusion/', 'metadata/', 'catalog/') + mapping = {row.rfilename: f'{LEGACY_PREFIX}/{row.rfilename}' for row in legacy.siblings + if row.rfilename.startswith(prefixes) or row.rfilename == 'catalog.json'} + commits = _copy_files(api, repo, output, mapping, remove_sources=True) + folder = output / LEGACY_PREFIX + folder.mkdir(parents=True, exist_ok=True) + (folder / 'README.md').write_text('# Deprecated dataset uploads\n\n' + 'These files preserve the previous dataset layout.\n' + 'Default reproduction downloads exclude this folder.\n' + 'Use the active `training/` components and explicit `optional/` downloads.\n\n' + f'[Original release](https://huggingface.co/datasets/{repo}/tree/{LEGACY_REVISION}).\n') + publisher.small(f'{LEGACY_PREFIX}/README.md', folder / 'README.md') + result = {'complete': True, 'repo': repo, 'revision': api.dataset_info(repo).sha, + 'components': verified, 'code': code, 'deprecation_commits': commits, + 'default_bytes': sum(recipe['datasets'][name]['bytes'] for name in recipe['default_datasets'])} + atomic_json(output / 'completion.json', result) + atomic_json(output / 'status.json', {'phase': 'complete', **result}) + return result + + +def configure_shape(source, output): + """Select online image conditioning without changing model or optimization settings.""" + config = _json(source) + for entry in config.get('prepared_datasets', []): + entry.pop('features', None) + entry.pop('training_targets', None) + config.pop('features', None) + config.pop('training_targets', None) + config['output'] = 'outputs/slat_multiobj_shape/reproduction_online/train' + config['checkpoints'] = 'checkpoints/training/slat_multiobj_shape/reproduction_online' + config['checkpoint'] = config['checkpoints'] + '/last.pt' + output = Path(output) + output.parent.mkdir(parents=True, exist_ok=True) + if output.exists() and _json(output) != config: + raise FileExistsError(f'Configuration already contains different settings: {output}') + atomic_json(output, config) + return config + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='command', required=True) + publishing = commands.add_parser('publish') + publishing.add_argument('--repo', default=DEFAULT_REPO) + publishing.add_argument('--output', type=Path, required=True) + publishing.add_argument('--dataset', action='append', required=True) + publishing.add_argument('--monitor-views', type=int, default=16) + publishing.add_argument('--workers', type=int, default=4) + publishing.add_argument('--shard-gib', type=float, default=1) + publishing.add_argument('--without-optional', action='store_true') + finishing = commands.add_parser('finalize') + finishing.add_argument('--repo', default=DEFAULT_REPO) + finishing.add_argument('--output', type=Path, required=True) + finishing.add_argument('--deprecate', action='store_true') + configuring = commands.add_parser('configure-shape') + configuring.add_argument('--source', type=Path, + default=Path('slat_multiobj_shape/configs/front3d_sage_32_assigned_object.json')) + configuring.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + if args.command == 'finalize': + finalize(args.repo, args.output, deprecate=args.deprecate) + elif args.command == 'configure-shape': + configure_shape(args.source, args.output) + else: + publish(args.repo, args.output, args.dataset, monitor_views=args.monitor_views, + optional=not args.without_optional, shard_bytes=int(args.shard_gib * 1024**3), workers=args.workers) + + +if __name__ == '__main__': + main() diff --git a/preprocess/tests/test_reproduction.py b/preprocess/tests/test_reproduction.py new file mode 100644 index 0000000..f9989d3 --- /dev/null +++ b/preprocess/tests/test_reproduction.py @@ -0,0 +1,222 @@ +"""Compact exports retain training tensors and never select deprecated downloads.""" +import json +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest + +from dataloader.dataset import ViewDataset +from dataloader.extent import ExtentLoader +from dataloader.prepared import ExtentDataset +from preprocess.huggingface import extract +from preprocess.reproduction import (COMPACT_SCHEMA, RECIPE_SCHEMA, download_training, package, + refresh_selection, stage_observations, stage_shape) +from preprocess.storage import atomic_json +from preprocess.tests.test_validate_dataset import dataset +from utils.hashing import sha256 + + +def test_compact_restore_preserves_tensors_and_adds_optional_test_views(dataset, tmp_path): + source, original = dataset + staged = tmp_path / 'staged' + manifest, metadata, core, held_out, checksums = stage_observations(source, staged, monitor_views=1) + output = tmp_path / 'archives' + destination = Path('datasets/fixture/extent/point_cloud') + index = package(source, output, 'training/observations', 'fixture', destination=destination, + kind='compact-training', metadata=metadata, groups=core, checksums=checksums) + restored = extract(index, output / 'training/observations/fixture', tmp_path / 'server') + assert sha256(restored / 'manifest.json') == sha256(source / 'manifest.json') + assert len(ViewDataset(restored)) == 3 + assert not list(restored.rglob('*.png')) + assert not list(restored.rglob('depth.npy')) + assert not list(restored.rglob('geometry.npz')) + expected = ExtentDataset(source, split='train') + actual = ExtentDataset(restored, split='train') + assert len(expected) == len(actual) == 2 + import torch + for a, b in zip(expected, actual): + for key in ('rgb', 'masks', 'depth', 'memberships', 'coords', 'intrinsics', 'model_to_world'): + torch.testing.assert_close(a[key], b[key], rtol=0, atol=0) + loader = ExtentLoader(restored) + rgb, masks = loader.load_observation(0) + arrays = ViewDataset(restored)[0] + np.testing.assert_array_equal(rgb, arrays['rgb']) + np.testing.assert_array_equal(masks, arrays['image_labels'] + 1) + from preprocess.validate_dataset import validate + report = validate(restored, workers=1) + assert report['validated_views'] == 3 + assert report['counts']['train']['views'] == 2 and report['counts']['test']['views'] == 1 + assert report['source_counts'] == original['counts'] + assert report['selection_sha256'] == sha256(restored / 'compact_training.json') + assert '| test | 1 | 1 |' in (restored / 'DATASET_CARD.md').read_text() + optional = package(source, output, 'optional/held_out', 'fixture', destination=destination, + kind='held-out-observations', metadata=[], groups=held_out, checksums=checksums) + extract(optional, output / 'optional/held_out/fixture', tmp_path / 'server') + assert len(ViewDataset(restored)) == 4 + # Repeating the compact restore must preserve separately restored test views. + extract(index, output / 'training/observations/fixture', tmp_path / 'server') + assert len(ViewDataset(restored)) == 4 + + +def test_compact_pack_rejects_corrupt_original_sample(dataset, tmp_path): + source, _ = dataset + _, metadata, groups, _, checksums = stage_observations(source, tmp_path / 'staged', monitor_views=1) + row = json.loads((source / 'manifest.json').read_text())['views'][0] + (source / row['sample']).write_bytes(b'corrupt source') + with pytest.raises(ValueError, match='Source checksum changed'): + package(source, tmp_path / 'archives', 'training/observations', 'fixture', + destination=Path('datasets/fixture/extent/point_cloud'), kind='compact-training', + metadata=metadata, groups=groups, checksums=checksums) + + +def test_compact_validation_rejects_changed_view_selection(dataset, monkeypatch): + from preprocess import validate_dataset + root, _ = dataset + refresh_selection(root) + path = root / 'compact_training.json' + selection = json.loads(path.read_text()) + selection['view_ids'] = selection['view_ids'][:-1] + selection['counts'] = {'train': 2, 'test': 1} + atomic_json(path, selection) + original = validate_dataset._validate_view + def changed(root, row): + result = original(root, row) + refresh_selection(root) + return result + monkeypatch.setattr(validate_dataset, '_validate_view', changed) + with pytest.raises(ValueError, match='selection changed during validation'): + validate_dataset.validate(root, workers=1) + assert not (root / 'validation.json').exists() + + +def test_object_shape_export_retains_object_identity_and_explicit_exclusions(tmp_path): + from slat_multiobj_shape.storage import SCHEMA, object_sha256, read_view_targets + root = tmp_path / 'source' + file = root / 'views/fixture/good.npz' + file.parent.mkdir(parents=True) + arrays = dict(schema=np.array(SCHEMA), coords=np.array([[1, 2, 3]], np.uint8), + feats=np.ones((1, 32), np.float16), object_index=np.zeros(1, np.int16), + object_ids=np.array(['object']), object_status=np.array(['complete']), + resolution=np.array(32), model_to_world=np.eye(4), grid_size=np.array(512), + scene_coords=np.array([[1, 2, 3]], np.uint8), scene_feats=np.ones((1, 32), np.float16), + scene_status=np.array('complete'), scene_scope=np.array('selected_prompt_objects'), + scene_seconds=np.array(1.), scene_dual_voxels=np.array(1), scene_error=np.array('')) + np.savez_compressed(file, **arrays) + row = {'file': 'views/fixture/good.npz', 'split': 'train', 'scene': 'room', + 'failed_objects': 0, 'sha256': sha256(file)} + atomic_json(root / 'manifest.json', {'schema': SCHEMA, 'resolution': 32, + 'entries': {'fixture/good': row, 'fixture/bad': {**row, 'failed_objects': 1}}, + 'datasets': [], 'models': {}, 'complete': False}) + manifest, _, groups, _ = stage_shape(root, tmp_path / 'staged') + assert manifest['excluded_views'] == ['fixture/bad'] + assert len(groups) == 1 + exported = read_view_targets(tmp_path / 'staged' / row['file']) + assert object_sha256(exported) == object_sha256(arrays) + assert not len(exported['scene_feats']) and str(exported['scene_status']) == 'pending' + assert len(read_view_targets(file)['scene_feats']) == 1 + + +def test_default_download_pins_recipe_and_excludes_optional_and_deprecated(tmp_path, monkeypatch): + import huggingface_hub + import preprocess.huggingface + revision = 'a' * 40 + recipe = tmp_path / 'index.json' + atomic_json(recipe, {'schema': RECIPE_SCHEMA, 'complete': True, 'default_datasets': ['fixture'], + 'datasets': {'fixture': {'required': ['training/observations/fixture', 'training/shape/32/fixture']}}, + 'optional': {'geometry': '_deprecated/old'}}) + monkeypatch.setattr(huggingface_hub, 'HfApi', lambda: SimpleNamespace( + dataset_info=lambda *a, **k: SimpleNamespace(sha=revision))) + monkeypatch.setattr(huggingface_hub, 'hf_hub_download', lambda *a, **k: str(recipe)) + calls = [] + monkeypatch.setattr(preprocess.huggingface, 'download', lambda *a, **k: calls.append((a, k))) + download_training('owner/repo', 'all', tmp_path / 'server') + assert [call[1]['bundle_root'] for call in calls] == ['training/observations', 'training/shape/32'] + assert all(call[0][3] == revision and call[1]['cleanup'] for call in calls) + data = json.loads(recipe.read_text()) + data['datasets']['fixture']['required'].append('_deprecated/fixture') + atomic_json(recipe, data) + with pytest.raises(ValueError, match='active training folder'): + download_training('owner/repo', 'all', tmp_path / 'server') + + +def test_compact_selection_rejects_another_manifest(dataset): + root, _ = dataset + atomic_json(root / 'compact_training.json', {'schema': COMPACT_SCHEMA, + 'source_manifest_sha256': 'wrong', 'view_ids': []}) + with pytest.raises(ValueError, match='source manifest'): + ViewDataset(root) + + +@pytest.mark.parametrize('corrupt', [False, True]) +def test_upload_cleanup_requires_verified_remote_digest(tmp_path, monkeypatch, corrupt): + import huggingface_hub + from preprocess.reproduction import Publisher + path = tmp_path / 'archive.tar' + path.write_bytes(b'verified data') + digest = sha256(path) + entry = SimpleNamespace(path='training/observations/fixture/train.tar', size=path.stat().st_size, + lfs=SimpleNamespace(sha256='wrong' if corrupt else digest)) + api = SimpleNamespace(dataset_info=lambda *a, **k: SimpleNamespace(siblings=[]), + create_commit=lambda **k: SimpleNamespace(oid='commit'), + get_paths_info=lambda *a, **k: [entry]) + monkeypatch.setattr(huggingface_hub, 'HfApi', lambda: api) + publisher = Publisher('owner/repo') + publisher.ready(entry.path, path, {'bytes': path.stat().st_size, 'sha256': digest}) + if corrupt: + with pytest.raises(ValueError, match='verification failed'): + publisher.flush() + assert path.read_bytes() == b'verified data' + else: + publisher.flush() + assert not path.exists() + + +def test_deprecation_rejects_concurrently_changed_legacy_file(tmp_path): + from preprocess.reproduction import _copy_files, LEGACY_REVISION + old = SimpleNamespace(rfilename='bundles/fixture/train.tar', size=10, blob_id='blob', + lfs=SimpleNamespace(sha256='original')) + changed = SimpleNamespace(rfilename=old.rfilename, size=10, blob_id='changed', + lfs=SimpleNamespace(sha256='changed')) + def info(*args, **kwargs): + return SimpleNamespace(siblings=[old if kwargs.get('revision') == LEGACY_REVISION else changed]) + api = SimpleNamespace(dataset_info=info, create_commit=lambda **k: pytest.fail('Changed data must remain untouched')) + with pytest.raises(ValueError, match='source changed'): + _copy_files(api, 'owner/repo', tmp_path, + {old.rfilename: '_deprecated/old/' + old.rfilename}, remove_sources=True) + + +@pytest.mark.parametrize('optional,keep', [(False, False), (True, False), (False, True)]) +def test_download_command_defaults_to_active_data_and_removes_archives(monkeypatch, optional, keep): + import sys + from preprocess import huggingface + arguments = ['download', '--repo', 'owner/repo'] + if optional: + arguments += ['--dataset', 'fixture', '--optional', 'geometry'] + if keep: + arguments += ['--keep-archives'] + monkeypatch.setattr(sys, 'argv', ['huggingface', *arguments]) + calls = [] + monkeypatch.setattr(huggingface, 'download', lambda *a, **k: calls.append((a, k))) + huggingface.main() + assert calls[0][1]['cleanup'] is not keep + assert calls[0][1]['bundle_root'] == ('optional/geometry' if optional else None) + assert calls[0][0][1] == ('fixture' if optional else 'all') + + +def test_online_shape_configuration_preserves_model_and_optimizer_settings(tmp_path): + from preprocess.reproduction import configure_shape + original = {'model': {'rank': 8, 'local_condition_mode': 'assigned_object'}, + 'training': {'learning_rate': .0001, 'optimizer': {'betas': [.9, .95]}}, + 'prepared_datasets': [{'targets': 'datasets/fixture/slat/32/targets', + 'features': 'old', 'training_targets': 'old'}], + 'require_scene_targets': False, 'features': 'old', 'training_targets': 'old'} + source = tmp_path / 'source.json' + atomic_json(source, original) + output = tmp_path / 'generated/online.json' + actual = configure_shape(source, output) + assert actual['model'] == original['model'] and actual['training'] == original['training'] + assert actual['prepared_datasets'] == [{'targets': 'datasets/fixture/slat/32/targets'}] + assert not {'features', 'training_targets'} & actual.keys() + assert json.loads(source.read_text()) == original + assert configure_shape(source, output) == actual