diff --git a/HF_DATASETS.md b/HF_DATASETS.md index 01d4e8f..d29c68d 100644 --- a/HF_DATASETS.md +++ b/HF_DATASETS.md @@ -1,345 +1,239 @@ -# Hugging Face datasets - -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: +# Hugging Face reproduction data -```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 -``` - -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. - -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. - -## Exports for training without meshes - -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. - -Create a local export from a complete extent: - -```bash -python -m preprocess.training_export \ - --dataset datasets/3dfront/extent/point_cloud \ - --output datasets/3dfront/training/point_cloud -``` - -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. - -Create transferable archives without an intermediate dataset copy: - -```bash -python -m preprocess.huggingface pack \ - --dataset 3dfront=datasets/3dfront/extent/point_cloud \ - --artifact-kind extent-training \ - --output outputs/huggingface/training_only -``` - -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. +The public [dataset repository](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed) separates training data, required evaluation 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). -## 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 - ``` +## Select data by task -2. Download the native SS flow and decoder from [Pixal3D](https://huggingface.co/TencentARC/Pixal3D). +Use `--task` to download only the data required by a server. +The [HF task catalog](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/blob/main/tasks/index.json) records components and sizes. +The [HF task guide](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/blob/main/tasks/README.md) also lists sizes for individual datasets. - ```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.*' - ``` +| Task | Required data | Default datasets | Transfer, GB | +| --- | --- | --- | ---: | +| `eval` | RGB, masks, GT meshes | PICASSO, MessyKitchen, selected 3D-FRONT test views | 23.404 | +| `ss` | Observations and encoded SS targets | 3D-FRONT, SAGE, FoundationPose | 265.667 | +| `slat-seg` | Observations only | 3D-FRONT, SAGE, FoundationPose | 221.950 | +| `slat-shape` | Observations and 32³ object shape targets | 3D-FRONT, SAGE | 166.318 | +| `all-training` | All training components | 3D-FRONT, SAGE, FoundationPose | 271.793 | -3. Download the SS encoder and paired decoder from [TRELLIS](https://huggingface.co/microsoft/TRELLIS-image-large). +Sizes use decimal GB and exclude model weights. +Archive extraction needs additional local space. +The task commands verify archives and remove them after extraction. +They retain existing files and resume partial transfers. - ```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' - ``` +Preview the selected components before downloading: -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 | +```bash +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task ss --dry-run +``` -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. +The preview reads small indices without transferring data archives. +Select one task for the server: -### Download GT occlusion caches +```bash +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task eval +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task ss +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task slat-seg +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task slat-shape +``` -Restore the matching extent datasets before these overlays. -Run these commands from the repository root. +Select individual datasets with `--dataset`: ```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 +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task eval --dataset picasso +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task eval --dataset picasso,messykitchen +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task slat-seg --dataset foundationpose ``` -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. - -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. +PICASSO alone requires about 0.165 GB, including shared metadata. +Evaluation metadata describes the full cohort. Data files cover only the selected datasets. +The evaluation bundle contains no depth predictions. Depth-dependent models need their configured depth estimator. + +SS uses published native targets without another target encoding pass. +Segmentation generates instance codes and image features during training. +Use `preprocess.reproduction configure-shape` for online shape conditioning without a separate feature cache. +FoundationPose shape targets remain unavailable. +Explicit FoundationPose shape requests fail before any archive transfer. +Custom configurations can require optional occlusion data or additional test observations. + +Commands without `--task` preserve the previous behavior and restore all training components. +Task selection does not download model weights. +Select exact checkpoint paths using the include patterns in the [checkpoint guide](HF_MODEL_CHECKPOINTS.md#download-checkpoints). + +## Mandatory files + +These paths refer to the Hugging Face repository root. +Files are mandatory for the task specified in each row. +The default command restores training files. +The benchmark also requires the separate download with `--dataset evaluation`. + +| File or directory | Required task | Contents | +| --- | --- | --- | +| `training/index.json` | Training restoration | Component paths, sizes, monitoring counts, and source identities | +| `training/observations//` | Training on the selected dataset | Archive index, sample NPZ files, calibration, object mappings, and scene voxel targets | +| `training/ss//` | Direct SS training after target publication | Archive index, native SS latents, and codec provenance | +| `training/shape/32//` | SLAT shape training where targets are available | Archive index and object shape targets with explicit exclusions | +| `evaluation/index.json` | Benchmark restoration | Archive list and SHA-256 checksums | +| `evaluation/metadata.tar` | Benchmark evaluation | Portable manifests, source selections, and dataset documentation | +| `evaluation/picasso-*.tar` | Benchmark evaluation | All 100 PICASSO images, masks, previews, and GT meshes | +| `evaluation/messykitchen-*.tar` | Benchmark evaluation | All 1,503 MessyKitchens images, masks, previews, and 100 shared GT meshes | +| `evaluation/3dfront-*.tar` | Benchmark evaluation | The selected 1,000 3D-FRONT test images, masks, previews, and GT meshes | + +Restore every archive listed in the selected component's `index.json`. +The complete evaluation bundle has 26 archives and requires about 23.4 GB. +Task downloads can select only the archives required by individual evaluation datasets. +Older checkouts also require the corresponding restore patch under `code/`. + +## Optional files + +These components support additional datasets, test views, and target generation. +The mandatory evaluation bundle already includes its RGB images, masks, and GT meshes. +Some SS configurations require the matching optional occlusion component. + +| File or directory | Purpose | +| --- | --- | +| `optional/held_out//` | Remaining test observations beyond the training monitors | +| `optional/geometry//` | Source geometry for new targets or other evaluation sets | +| `optional/occlusion//` | GT occlusion relations for applicable SS configurations | +| `optional/evaluation/ycbv/` | Additional YCB-V observations and GT geometry | + +Optional components are separate downloads with `--optional`. +Historical files under `_deprecated/20261020/` are obsolete and unnecessary for the current release. + +The default SS and segmentation datasets include 3D-FRONT, SAGE-10k, and FoundationPose. +Its observation bundle supports SS and segmentation, but contains no shape targets or mesh geometry. + +## Restore on another server + +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 pip install -e '.[preprocess,ss-multiobj-depth,slat-segvigen,slat-multiobj-shape]' +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed +``` -### Publish GT occlusion caches +The command downloads the default datasets and their available SS and 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/`. -Package the verified caches from the prepared extent roots: +Select one dataset with `--dataset`: ```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 foundationpose ``` -Packaging checks every matrix checksum and its completion record. -The uploader publishes complete inventories after it verifies all remote archives. - -## Additional SLAT targets - -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. +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. + +## Training inputs + +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. + +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. + +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. + +Published SS components contain exact native latents with shape `8×16×16×16`. +The standard download restores them to the cache paths used by online SS training. +The [portable SS guide](preprocess/SS_TARGETS.md) describes direct training after restoration. +Each component preserves its original cache files and manifest identity. +The observation bundles provide the first 16 test views for training monitors. +The HF card lists the components that completed publication. +The download excludes trained weights. +SS archives retain historical feature fields when their original cache manifests require them. +Online SS training reads only the latent target from these tensor files. +Run SS preparation only when compatible encoded targets are unavailable. +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. + +## Optional downloads + +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 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 --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 ``` -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. +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. -## Publication +## Frozen evaluation + +The local dataset resides under `datasets/evaluation/`. +It contains 100 PICASSO images, 1,503 MessyKitchens images, and 1,000 3D-FRONT test views. +The 3D-FRONT selection uses seed 42 and samples views without replacement. +Each MessyKitchens scene has one shared GT mesh export. +Every view references its mesh through a relative manifest path. +Archive members contain regular files, so restoration requires no symbolic links. -The reusable publication commands produce approximately 1 GiB archive shards -under `outputs/`, without modifying the source datasets: +The benchmark requires this evaluation dataset. +Download the evaluation bundle: ```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 +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset evaluation ``` -`--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`. +The dataset card includes the loader patch for checkouts that lack `dataloader/frozen.py`. +Use `--dataset frozen` with the corresponding `evaluation/configs/*_frozen.json` file. +Original selections remain in `source_selection.json` for provenance. +The loader reads the exported GLB geometry with its stored float32 vertices. +RGB pixels and mask labels retain their original selection checksums. +These bundles contain no depth maps, model weights, or image features. -For one job that packages, uploads, retries transient Hub failures and updates -the public dataset card, use: +Create the local dataset and publish its archives with these commands: ```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 +python -m preprocess.evaluation store --source outputs/evaluation/full_dataset_20261021 +python -m preprocess.evaluation publish --repo cubec/PartProbe3D-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. +## Deprecated uploads -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: +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 + +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/models/voxel_condition.py b/models/voxel_condition.py index 71c0708..d0192fd 100644 --- a/models/voxel_condition.py +++ b/models/voxel_condition.py @@ -14,6 +14,26 @@ LORA_IMAGE_PROJECTION_FORMAT = 'lora-image-projection-v1' FROZEN_IMAGE_PROJECTION_FORMAT = 'frozen-image-projection-v1' +def voxel_adapter_settings(settings, adapters=None): + """Resolve new LoRA defaults and retain historical checkpoint semantics.""" + settings = dict(settings) + recorded_method = adapters.get('backbone_adapter_method', 'nora') if adapters is not None else 'lora' + settings.setdefault('adapter_method', recorded_method) + if adapters is not None and settings['adapter_method'] != recorded_method: + raise ValueError('Checkpoint backbone adapter method differs from model settings') + if settings['adapter_method'] not in ('lora', 'nora'): + raise ValueError('adapter_method must be lora or nora') + recorded_image = ({NORA_IMAGE_PROJECTION_FORMAT: 'nora', LORA_IMAGE_PROJECTION_FORMAT: 'lora', + FROZEN_IMAGE_PROJECTION_FORMAT: 'frozen'}.get(adapters.get('image_projection_format'), 'full') + if adapters is not None else None) + settings.setdefault('image_projection_adaptation', recorded_image or + (settings['adapter_method'] if settings.get('rank', 0) else 'full')) + if recorded_image is not None and settings['image_projection_adaptation'] != recorded_image: + raise ValueError('Checkpoint image projection adaptation differs from model settings') + image_projection_adaptation(settings) + return settings + + def image_projection_adaptation(settings): """Validate the shared image projection policy for SS and SLAT models.""" mode = settings.get('image_projection_adaptation', 'full') @@ -405,13 +425,16 @@ def install_voxel_adapters(flow, *, depth_channels=128, rank=8, alpha=8., voxel_condition_mode='additive', voxel_condition_hidden_channels=None, mask_channels=None, object_context=False, object_aggregation=False, region_image_channels=2048, coverage_conditioned=False, - image_projection_adaptation='full'): + image_projection_adaptation='full', adapter_method='lora'): """Train full image projections and new conditions; adapt the remaining frozen backbone.""" voxel_condition_width(voxel_condition_mode, voxel_condition_hidden_channels) + if adapter_method not in ('lora', 'nora'): + raise ValueError('adapter_method must be lora or nora') if (getattr(flow, 'image_attn_mode', None) != 'proj' or not flow.blocks or any(not hasattr(block.cross_attn, 'proj_linear') for block in flow.blocks)): raise ValueError('Expected unwrapped native Pixal3D proj blocks') flow.requires_grad_(False) + flow.voxel_adapter_method = adapter_method if object_aggregation: resize_image_projection(flow, region_image_channels) for block in flow.blocks: @@ -421,7 +444,7 @@ def install_voxel_adapters(flow, *, depth_channels=128, rank=8, alpha=8., coverage_conditioned=coverage_conditioned) block.use_checkpoint = True if rank: - install_lora(flow, rank=rank, alpha=alpha, method='nora') + install_lora(flow, rank=rank, alpha=alpha, method=adapter_method) configure_image_projections(flow, {'image_projection_adaptation': image_projection_adaptation, 'rank': rank, 'alpha': alpha}) return flow @@ -431,10 +454,14 @@ def adapter_state(flow, conditioner): return {'flow': {name: parameter.detach().cpu() for name, parameter in flow.named_parameters() if parameter.requires_grad}, 'image_projection_format': image_projection_format(flow), + 'backbone_adapter_method': getattr(flow, 'voxel_adapter_method', 'nora'), 'conditioner': {name: value.detach().cpu() for name, value in conditioner.state_dict().items()}} def load_adapter_state(flow, conditioner, state, *, allow_legacy=True): + if (any(isinstance(layer, LoRALinear) for layer in flow.modules()) + and getattr(flow, 'voxel_adapter_method', 'nora') != state.get('backbone_adapter_method', 'nora')): + raise ValueError('Checkpoint backbone adapter method differs from this model') parameters = dict(flow.named_parameters()) weights = {} for name, value in state['flow'].items(): diff --git a/preprocess/SS_TARGETS.md b/preprocess/SS_TARGETS.md new file mode 100644 index 0000000..b75a878 --- /dev/null +++ b/preprocess/SS_TARGETS.md @@ -0,0 +1,79 @@ +# Portable SS targets + +The SS task download includes observations and native SS latents for 3D-FRONT, SAGE-10k, and FoundationPose. +The publisher adds each dataset after all its target archives pass remote checksum checks. +The [dataset card](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed) lists the available SS components. + +| Data | Purpose | Offline work after restoration | +| --- | --- | --- | +| Observations and voxel labels | Calibrated inputs and occupancy supervision | None | +| SS latents | Native SS flow targets, shape `8×16×16×16` | None | + +Image encoders compute features during online training. +This avoids separate image caches while preserving current conditioning. +Model weights and software dependencies remain separate requirements. + +## Restore and train + +Use the project revision recorded in the HF card. +Download only the SS training components: + +```bash +python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task ss +``` + +This command selects all three datasets, including FoundationPose. +It excludes shape targets and evaluation data. +Add `--dataset foundationpose` to select one dataset. +Add `--dry-run` to preview components and transfer sizes. +The restore command checks archive hashes and preserves original observation manifests. +It writes SS caches to the paths used by the default training configuration. + +Start SS training with the desired device configuration: + +```bash +envs/sam3d/bin/python -m ss_multiobj_depth.train \ + --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json +``` + +The encoded targets remove the SS preparation command from this procedure. +The default uses online conditioning, a real batch of 16, and one accumulation step. +Use a fresh cache destination when existing files differ from the selected HF release. + +## Publish completed targets + +Run this command after native SS target preparation: + +```bash +python -m preprocess.ss_targets \ + --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json \ + --output outputs/huggingface/ss_targets +``` + +Add `--follow` to wait for each source cache to become complete. +Publication streams the completed cache through the archive writer. +The writer checks source file hashes during that pass. +Publication uses CPU operations and leaves training processes active. +It preserves every view in the original cache. +The export preserves the original files and manifest bytes. +It also retains historical cached features when the original manifest requires them. +Online training computes its image features from the current configuration. +It reads only the saved SS latent from each target tensor file. + +Each dataset uses `training/ss//` on HF. +The publisher registers its component in `training/index.json` after archive verification. +The task downloader reads this inventory and selects observations plus SS targets. +Later observation publications retain SS components when their dataset identities still match. + +## Compatibility checks + +The export retains the target scope, observation hashes, and frozen codec identities. +The export retains the original model hashes and dataset provenance. +The training loader checks the dataset manifest and model weights against its configuration. +The cache also retains any additional test targets from the original preparation. +The observation download provides the monitoring views used by training. +Original manifest identities support exact checkpoint resume with matching code, configuration, and model weights. + +The relocation test restores real archive files into a separate directory. +It removes the original observations and cache before reading the restored training data. +It checks latent equality and rejects changed targets, incomplete caches, and mismatched datasets. diff --git a/preprocess/huggingface.py b/preprocess/huggingface.py index 60aafa7..6afd3ce 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() @@ -370,15 +394,15 @@ def extract(index, folder, destination): if index.get('schema') != SCHEMA or not index.get('complete'): raise ValueError('A complete archive index is required') folder, destination = Path(folder), Path(destination).resolve() - prefix = _relative(index['destination']) + prefix = _relative(index.get('archive_prefix', index['destination'])) restored_prefix = (_slat_destination(index['name'], index['resolution']) - if index.get('artifact_kind') == 'slat-shape-targets' else prefix) + if index.get('artifact_kind') == 'slat-shape-targets' else _relative(index['destination'])) # Publish the original complete manifest only after restoring its artifacts. for item in sorted(index['archives'], key=lambda item: item['file'] == 'metadata.tar'): 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,25 +550,43 @@ 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, archive_files=None): + if name == 'evaluation' and bundle_root is None: + bundle_root = '' + 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)) + bundle_root = str(_relative(bundle_root)) if bundle_root else '' + component = str(PurePosixPath(bundle_root) / _relative(name)) destination = Path(destination).resolve() - cache = destination / 'datasets' / name / 'archives' / 'huggingface' - index_path = hf_hub_download(repo, f'{bundle_root}/{name}/index.json', repo_type='dataset', + # Keep active dataset 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 component.split('/')[0] in ('training', 'optional', 'evaluation') + else destination / 'datasets' / name / 'archives' / 'huggingface') + index_path = hf_hub_download(repo, f'{component}/index.json', repo_type='dataset', revision=revision, local_dir=cache) index = _json(index_path) if index.get('name') != name or not index.get('complete'): raise ValueError('Requested dataset has no complete archive index') - folder = cache / bundle_root / name + archives = index['archives'] + if archive_files is not None: + selected = set(archive_files) + available = {item['file'] for item in archives} + if not selected or not selected.issubset(available) or 'metadata.tar' not in selected: + raise ValueError('Select existing archives and include metadata.tar') + archives = [item for item in archives if item['file'] in selected] + folder = cache / component status_path = folder / 'download-status.json' status = {'state': 'running', 'pid': os.getpid(), 'repo': repo, 'revision': revision, 'dataset': name, 'bundle_root': bundle_root, 'started_unix': time.time(), - 'archives_total': len(index['archives']), 'archives_restored': 0, - 'archive_bytes_total': sum(item['bytes'] for item in index['archives']), + 'archives_total': len(archives), 'archives_restored': 0, + 'selected_archives': [item['file'] for item in archives], + 'archive_bytes_total': sum(item['bytes'] for item in archives), 'archive_bytes_restored': 0, 'file_workers': 1, 'parallel_ranges': False} def save(): @@ -554,11 +599,11 @@ def download(repo, name, destination, revision, *, cleanup=False, bundle_root='b save() try: - for item in sorted(index['archives'], key=lambda item: item['file'] == 'metadata.tar'): + for item in sorted(archives, key=lambda item: item['file'] == 'metadata.tar'): status.update(state='downloading', current_archive=item['file'], active_transfer=None) save() archive = download_huggingface_file( - repo, f'{bundle_root}/{name}/{item["file"]}', repo_type='dataset', + repo, f'{component}/{item["file"]}', repo_type='dataset', revision=revision, local_dir=cache, expected_size=item['bytes'], expected_sha256=item['sha256'], progress=progress) status['state'] = 'restoring' @@ -820,12 +865,19 @@ 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='Training dataset name, or evaluation for the required benchmark') restoring.add_argument('--destination', type=Path, default=Path('.')) restoring.add_argument('--revision', default='main') - restoring.add_argument('--bundle-root', default='bundles') + restoring.add_argument('--task', choices=('eval', 'ss', 'slat-seg', 'slat-shape', 'all-training'), + help='Restore only the data required by this task') + restoring.add_argument('--dry-run', action='store_true', help='Print the task plan without downloading archives') + 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 +905,23 @@ 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.task: + if args.optional or args.bundle_root is not None: + parser.error('--task cannot be combined with --optional or --bundle-root') + from preprocess.tasks import download_task + download_task(args.repo, args.task, args.dataset, args.destination, args.revision, + cleanup=not args.keep_archives, dry_run=args.dry_run) + return + if args.dry_run: + parser.error('--dry-run requires --task') + 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/reproduction.py b/preprocess/reproduction.py new file mode 100644 index 0000000..34eaed4 --- /dev/null +++ b/preprocess/reproduction.py @@ -0,0 +1,690 @@ +"""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) if component else Path()) / name + folder.mkdir(parents=True, exist_ok=True) + remote_root = str(folder.relative_to(output)) + 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': []} + if 'archive_prefix' in old: + index['archive_prefix'] = old['archive_prefix'] + atomic_json(path, index) + + def save(label, files, views): + filename = label + '.tar' + files = sorted(set(files)) + old_record = previous.get(filename) + remote_path = f'{remote_root}/{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(index.get('archive_prefix', 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'{remote_root}/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 + from preprocess.ss_targets import retain_registered + retain_registered(recipe, repo, output) + 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, *, tracked=None, added=None, name='reproduction'): + """Export selected source changes and preserve unrelated workspace edits.""" + output = Path(output) + folder = output / 'code' + folder.mkdir(parents=True, exist_ok=True) + if tracked is None: + runtime = subprocess.check_output(['git', 'ls-files', '--', 'ss_multiobj_depth', + 'utils/training', 'models/voxel_condition.py'], text=True).splitlines() + 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', *runtime] + added = (['preprocess/reproduction.py', 'preprocess/tests/test_reproduction.py', + 'preprocess/ss_targets.py', 'preprocess/tests/test_ss_targets.py', 'preprocess/SS_TARGETS.md', + 'preprocess/tasks.py'] + if added is None else added) + 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 / f'{name}.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' if name == 'reproduction' else f'{name}_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', + '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)', ''] + card = '\n'.join(lines) + if any(row.get('ss_targets') for row in recipe['datasets'].values()): + from preprocess.ss_targets import update_card + card = update_card(card, recipe, repo) + from preprocess.tasks import update_card + card = update_card(card, None, repo) + (output / 'README.md').write_text(card) + + +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/slat/HUGGING_FACE.md b/preprocess/slat/HUGGING_FACE.md index dee49f8..0865e0d 100644 --- a/preprocess/slat/HUGGING_FACE.md +++ b/preprocess/slat/HUGGING_FACE.md @@ -1,145 +1,98 @@ -## 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 shape task downloads both artifact types for 3D-FRONT and SAGE-10k. +It excludes SS targets and evaluation data. +FoundationPose shape targets remain unavailable. ```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 --task slat-shape ``` -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`. -### Upload contract +## SAGE exclusions -`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. +The original release contains three failed object targets. +The compact release records their views as explicit exclusions: -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. +- `sage10k/23adeb2d2638a873e5d9` +- `sage10k/7b2d68afd83bf89364ea` +- `sage10k/ff0a565cad070014b1b8` -Package shape targets with this command: +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. + +## Train without an image-feature cache + +Obtain the configured Pixal3D, DINOv3, and NAF weights separately. +Create an online configuration from the project root: ```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 +python -m preprocess.reproduction configure-shape --output outputs/reproduction/shape_online.json +python -m slat_multiobj_shape.train \ + --config outputs/reproduction/shape_online.json ``` -Publish those archives to an existing dataset repository with this command: +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 + +Prepare the existing assigned-object caches with: ```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.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 +``` + +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 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..c7e7fde 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,106 @@ 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. + +## FoundationPose object targets + +The [FoundationPose target preset](configs/targets_foundationpose_32.json) uses the same native shape encoder and dual-grid settings as 3D-FRONT and SAGE. +It reads saved FoundationPose extents and writes `datasets/foundationpose/slat/32/targets/`. +Its device `cuda:1` selects the second visible GPU. + +FoundationPose observation bundles contain RGB, masks, depth, calibration, and voxel labels. +They do not contain object shape latents or complete mesh geometry. +Restore the geometry or existing shape targets before starting FoundationPose-inclusive shape training. +The training default requires complete target coverage and does not omit FoundationPose when its targets are unavailable. ## Prepared data @@ -84,25 +184,25 @@ 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. ```bash - CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m preprocess.slat.prepare + python -m preprocess.slat.prepare ``` 2. Train with equal sampling probability per dataset. ```bash - CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m slat_multiobj_shape.train + python -m slat_multiobj_shape.train ``` 3. Resume training with the same prepared data. ```bash - CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m slat_multiobj_shape.train --resume + python -m slat_multiobj_shape.train --resume ``` Use the corresponding `front3d_sage_64.json` files for a 64³ token grid. @@ -126,10 +226,10 @@ That option overrides the device list for feature extraction. Rerun the same command to reuse matching entries and regenerate corrupt or failed entries. `--stage targets` runs the object phase and scene phase without feature extraction. -Generate latents on physical GPUs 4 and 6 with: +Generate latents on two visible GPUs with: ```bash -CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m preprocess.slat.prepare \ +python -m preprocess.slat.prepare \ --stage targets --devices cuda:0 cuda:1 --parallel 2 ``` @@ -181,42 +281,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 @@ -241,7 +330,7 @@ See the [shape guide](../../slat_multiobj_shape/README.md) for finetuning and in Start the combined workflow with: ```bash -CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m preprocess.slat.finetune \ +python -m preprocess.slat.finetune \ --devices cuda:0 cuda:1 --training-device cuda:0 ``` @@ -251,9 +340,9 @@ Select the original training configuration to resume an existing additive run. The command completes these steps: -1. Prepare all per-object latents on physical GPUs 4 and 6. +1. Prepare all per-object latents on the configured devices. 2. Freeze object targets and prepare conditioning features on those GPUs. -3. Start finetuning on physical GPU 4 and scene encoding on physical GPU 6. +3. Start finetuning and scene encoding on separate configured devices. The command reuses verified object targets. It requires full training coverage unless an explicit `--limit` selects a pilot. diff --git a/preprocess/ss_targets.py b/preprocess/ss_targets.py new file mode 100644 index 0000000..aa5ae6a --- /dev/null +++ b/preprocess/ss_targets.py @@ -0,0 +1,265 @@ +"""Publish native SS latents so restored training needs no target encoding.""" +import argparse +from copy import deepcopy +import json +from pathlib import Path +import re +import subprocess +import time + +import torch + +from dataloader.dataset import ViewDataset +from preprocess.huggingface import _json, _relative, _retry +from preprocess.reproduction import DEFAULT_REPO, RECIPE_SCHEMA, Publisher, package +from preprocess.storage import atomic_json +from ss_multiobj_depth.config import TARGET_SCOPE, load_config, source_configs +from ss_multiobj_depth.dataloader import FeatureDataset, dataset_name +from utils.hashing import sha256 +from utils.paths import REPO_ROOT + + +COMPONENT = 'training/ss' +CARD_START = '' +CARD_END = '' + + +def hub_name(dataset): + name = dataset_name(dataset) + return 'sage' if name == 'sage10k' else name + + +def index_targets(source, observations, *, monitor_views=16): + """Index exact cache files for streaming through the checked archive writer.""" + source, observations = Path(source).resolve(), Path(observations).resolve() + if monitor_views < 1: + raise ValueError('Use a positive monitoring count') + cache = FeatureDataset(source) + if cache.target_scope != TARGET_SCOPE or not cache.compact or not len(cache): + raise ValueError('Export requires native masked-object SS targets') + views = ViewDataset(observations) + if cache.policy['dataset']['manifest_sha256'] != sha256(observations / 'manifest.json'): + raise ValueError('SS targets and observations have different dataset manifests') + if cache.dataset != dataset_name(views.manifest['dataset']): + raise ValueError('SS target dataset identity differs from observations') + original = {row['id']: row for row in views.manifest['views']} + required = {row['id'] for row in views.manifest['views'] if row['split'] == 'train'} + required.update([row['id'] for row in views.manifest['views'] if row['split'] == 'test'][:monitor_views]) + if not required.issubset({row['id'] for row in cache.rows}): + raise ValueError('The SS cache omits required training or monitoring views') + clean = cache.read_features(0)['clean'] + if clean.shape != (8, 16, 16, 16) or not clean.is_floating_point() or not torch.isfinite(clean).all(): + raise ValueError('Invalid native SS latent') + groups, checksums = [], {} + for row in sorted(cache.rows, key=lambda row: (row['split'], row['scene'], row['id'])): + if (row['id'] not in original + or any(row[key] != original[row['id']][key] for key in ('scene', 'split'))): + raise ValueError(f'SS target identity or split changed: {row["id"]}') + if not {'features.pt', 'targets.npz', 'geometry.json'}.issubset(row['files']): + raise ValueError(f'Incomplete SS target record: {row["id"]}') + folder = source / _relative(row['directory']) + paths = [folder / _relative(name) for name in (*row['files'], 'complete.json')] + groups.append((row['split'], paths, 1)) + checksums.update({folder / _relative(key): value for key, value in row['files'].items()}) + metadata = [source / 'manifest.json', source / 'policy.json'] + checksums.update({path: sha256(path) for path in metadata}) + return cache.manifest, metadata, groups, checksums + + +def target_section(recipe, repo=DEFAULT_REPO): + lines = [CARD_START, '## Encoded SS targets', '', + 'The SS task download includes encoded targets for the datasets listed below.', + 'These targets remove GPU encoding from the restore procedure.', + 'They retain the original cache manifests, latent tensors, and monitoring targets.', + 'Their native latent shape is `8×16×16×16`.', + 'Model weights remain separate dependencies.', '', + '| Dataset | Target views | Transfer, GB |', '| --- | ---: | ---: |'] + for name, row in recipe['datasets'].items(): + if row.get('ss_targets'): + targets = row['ss_targets'] + lines.append(f'| {name} | {targets["views"]:,} | {targets["bytes"]/1e9:.3f} |') + ready = all(recipe['datasets'].get(key, {}).get('ss_targets') for key in ('3dfront', 'sage', 'foundationpose')) + lines += ['', 'Use the current project checkout and download the selected datasets:', '', '```bash', + f'python -m preprocess.huggingface download --repo {repo} --task ss', '```', '', + ('SS training can then use the default online configuration without a preparation command.' if ready + else 'Publication continues for the remaining datasets. The listed datasets already include SS targets.'), + 'The downloader checks archive hashes before extraction.', + 'The training loader checks dataset and frozen codec identities.', + 'The image encoders compute features during training.', CARD_END] + return '\n'.join(lines) + + +def update_card(card, recipe, repo): + """Update restore instructions while preserving unrelated published sections.""" + total = sum(recipe['datasets'][key]['bytes'] for key in recipe['default_datasets']) + card = re.sub(r'The default transfer is \*\*[\d.,]+ GB\*\*[^\n]*', + f'The default transfer is **{total/1e9:.2f} GB**, including observations, SS targets, and available shape targets.', card) + ready = all(recipe['datasets'].get(key, {}).get('ss_targets') for key in ('3dfront', 'sage', 'foundationpose')) + if ready and '## Restore tools' in card and '## Default download' in card: + start, end = card.index('## Restore tools'), card.index('## Default download') + card = (card[:start] + '## Restore tools\n\n' + f'Use project Git revision `{recipe["restore_git_revision"]}` or later.\n' + 'This revision includes the restore tools and the online SS defaults.\n\n' + '```bash\n' + "python -m pip install -e '.[preprocess,ss-multiobj-depth,slat-segvigen,slat-multiobj-shape]'\n" + '```\n\n' + card[end:]) + for name, row in recipe['datasets'].items(): + card = re.sub(rf'(^\| {name} \|[^\n]*\| )[^|]+( \|$)', + lambda match: match[1] + f'{row["bytes"]/1e9:.2f}' + match[2], card, flags=re.MULTILINE) + if 'foundationpose' in recipe['default_datasets']: + card = card.replace('The command restores 3D-FRONT, SAGE-10k, and their 32³ object shape targets.', + 'The command restores observations and SS targets for 3D-FRONT, SAGE-10k, and FoundationPose.\n' + 'It also restores available 32³ object shape targets.') + card = card.replace('FoundationPose requires explicit selection and supports SS and segmentation.', + 'The default includes FoundationPose for SS and segmentation.\n' + 'FoundationPose shape targets remain unavailable.\n' + 'Use this command to restore FoundationPose alone:') + if ready: + card = card.replace('Run SS preparation before SS training.', + 'The restored SS targets support online SS training directly.') + card = card.replace('python -m ss_multiobj_depth.prepare --config ss_multiobj_depth/configs/front3d_sage.json\n', '') + card = card.replace('python -m ss_multiobj_depth.train --config ss_multiobj_depth/configs/front3d_sage.json', + 'python -m ss_multiobj_depth.train') + section = target_section(recipe, repo) + if CARD_START in card: + start, end = card.index(CARD_START), card.index(CARD_END) + len(CARD_END) + return card[:start] + section + card[end:] + return card.rstrip() + '\n\n' + section + '\n' + + +def retain_registered(recipe, repo, output): + """Keep compatible SS components when observations or shape targets are republished.""" + from huggingface_hub import HfApi, hf_hub_download + from huggingface_hub.errors import EntryNotFoundError + revision = HfApi().dataset_info(repo).sha + try: + previous = _json(hf_hub_download(repo, 'training/index.json', repo_type='dataset', revision=revision, + local_dir=Path(output) / 'registered')) + except EntryNotFoundError: + return + for name, row in recipe['datasets'].items(): + old = previous.get('datasets', {}).get(name, {}) + targets = old.get('ss_targets') + if not targets or old.get('source_manifest_sha256') != row['source_manifest_sha256']: + continue + if targets['component'] != f'{COMPONENT}/{name}': + raise ValueError('Registered SS targets reference an unexpected component') + if targets['component'] not in row['required']: + row['required'].append(targets['component']) + row['bytes'] += targets['bytes'] + row['ss_targets'] = deepcopy(targets) + if any(row.get('ss_targets') for row in recipe['datasets'].values()): + recipe['restore_git_revision'] = previous['restore_git_revision'] + if all(recipe['datasets'].get(key, {}).get('ss_targets') for key in ('3dfront', 'sage', 'foundationpose')): + recipe['default_datasets'] = ['3dfront', 'sage', 'foundationpose'] + + +def register(repo, output, name, index): + """Add verified SS archives without replacing concurrent dataset publications.""" + from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download + from huggingface_hub.errors import HfHubHTTPError + api, output = HfApi(), Path(output) + for attempt in range(5): + revision = api.dataset_info(repo).sha + recipe = _json(hf_hub_download(repo, 'training/index.json', repo_type='dataset', revision=revision, + local_dir=output / 'remote')) + if recipe.get('schema') != RECIPE_SCHEMA or not recipe.get('complete'): + raise ValueError('A complete active training recipe is required') + row = recipe['datasets'][name] + if row['source_manifest_sha256'] != index['dataset_manifest_sha256']: + raise ValueError('Published observations differ from the encoded SS dataset') + if row['training_views'] != index['training_views']: + raise ValueError('The SS export omits published training views') + previous = row.get('ss_targets', {}) + row['bytes'] += index['bytes'] - previous.get('bytes', 0) + component = f'{COMPONENT}/{name}' + if component not in row['required']: + row['required'].append(component) + row['ss_targets'] = {'component': component, 'bytes': index['bytes'], 'views': index['views'], + 'latent_shape': [8, 16, 16, 16], 'target_scope': TARGET_SCOPE} + recipe['restore_git_revision'] = subprocess.check_output( + ['git', 'rev-parse', 'HEAD'], cwd=REPO_ROOT, text=True).strip() + # The default SS and segmentation runs include all three datasets. + if all(recipe['datasets'].get(key, {}).get('ss_targets') for key in ('3dfront', 'sage', 'foundationpose')): + recipe['default_datasets'] = ['3dfront', 'sage', 'foundationpose'] + card = Path(hf_hub_download(repo, 'README.md', repo_type='dataset', revision=revision, + local_dir=output / 'remote')).read_text() + card = update_card(card, recipe, repo) + (output / 'training').mkdir(parents=True, exist_ok=True) + atomic_json(output / 'training/index.json', recipe) + (output / 'README.md').write_text(card) + try: + result = _retry(lambda: api.create_commit(repo_id=repo, repo_type='dataset', parent_commit=revision, + operations=[CommitOperationAdd(path_in_repo='training/index.json', path_or_fileobj=output / 'training/index.json'), + CommitOperationAdd(path_in_repo='README.md', path_or_fileobj=output / 'README.md')], + commit_message=f'Include encoded SS targets for {name} in standard restoration')) + return result.oid + except HfHubHTTPError as error: + if error.response.status_code not in (409, 412) or attempt == 4: + raise + raise RuntimeError('The training recipe changed during every registration attempt') + + +def publish(config, output, repo=DEFAULT_REPO, *, monitor_views=16, workers=4, + shard_bytes=1024**3, follow=False): + output = Path(output).resolve() + output.mkdir(parents=True, exist_ok=True) + status = {'state': 'running', 'repo': repo, 'datasets': {}} + for source in source_configs(config): + cache, observations = REPO_ROOT / source['cache'], REPO_ROOT / source['dataset'] + name = hub_name(_json(observations / 'manifest.json')['dataset']) + while not (cache / 'manifest.json').exists() or not _json(cache / 'manifest.json').get('complete'): + if not follow: + raise ValueError(f'Complete SS target preparation first: {cache}') + status.update(state='waiting_for_targets', waiting_dataset=name) + atomic_json(output / 'status.json', status) + time.sleep(30) + status.update(state='exporting', waiting_dataset=None) + atomic_json(output / 'status.json', status) + manifest, metadata, groups, checksums = index_targets(cache, observations, monitor_views=monitor_views) + status['state'] = 'publishing' + atomic_json(output / 'status.json', status) + cache_name = 'front3d' if name == '3dfront' else name + index = package(cache, output, COMPONENT, name, + destination=Path('outputs/ss_multiobj_depth') / cache_name / 'masked_objects/targets', + kind='ss-latent-targets', metadata=metadata, groups=groups, checksums=checksums, + details={'source_manifest_sha256': sha256(cache / 'manifest.json'), + 'dataset_manifest_sha256': sha256(observations / 'manifest.json'), + 'views': len(manifest['entries']), 'target_scope': TARGET_SCOPE, + 'training_views': sum(row['split'] == 'train' for row in manifest['entries']), + 'latent_shape': [8, 16, 16, 16]}, + shard_bytes=shard_bytes, publisher=Publisher(repo, workers=workers)) + revision = register(repo, output, name, index) + status['datasets'][name] = {'views': index['views'], 'bytes': index['bytes'], 'revision': revision} + atomic_json(output / 'status.json', status) + status.update(state='complete', waiting_dataset=None) + atomic_json(output / 'status.json', status) + return status + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--config', type=Path, required=True) + parser.add_argument('--output', type=Path, default=Path('outputs/huggingface/ss_targets')) + parser.add_argument('--repo', default=DEFAULT_REPO) + parser.add_argument('--monitor-views', type=int, default=16) + parser.add_argument('--workers', type=int, default=4) + parser.add_argument('--shard-gib', type=float, default=1.) + parser.add_argument('--follow', action='store_true', help='Wait for target preparation before each dataset export') + args = parser.parse_args() + if args.workers < 1 or args.monitor_views < 1 or args.shard_gib <= 0: + parser.error('Worker count, monitoring count and shard size must be positive') + torch.set_num_threads(1) + try: + publish(load_config(args.config), args.output, args.repo, monitor_views=args.monitor_views, + workers=args.workers, shard_bytes=int(args.shard_gib*1024**3), follow=args.follow) + except Exception as error: + args.output.mkdir(parents=True, exist_ok=True) + path = args.output / 'status.json' + status = _json(path) if path.exists() else {} + atomic_json(path, {**status, 'state': 'failed', 'error': f'{type(error).__name__}: {error}'}) + raise + + +if __name__ == '__main__': + main() diff --git a/preprocess/tasks.py b/preprocess/tasks.py new file mode 100644 index 0000000..f96f60d --- /dev/null +++ b/preprocess/tasks.py @@ -0,0 +1,265 @@ +"""Plan task-specific data transfers and publish their Hugging Face catalog.""" +import argparse +import json +from pathlib import Path +import re +import subprocess + +from preprocess.huggingface import SCHEMA, _json, _relative, _retry +from preprocess.storage import atomic_json +from utils.hashing import sha256 + + +TASKS = ('eval', 'ss', 'slat-seg', 'slat-shape', 'all-training') +ROLES = {'ss': ('observations', 'ss'), 'slat-seg': ('observations',), + 'slat-shape': ('observations', 'shape/32')} +KINDS = {'observations': 'compact-training', 'ss': 'ss-latent-targets', + 'shape/32': 'object-shape-targets'} +CARD_START = '' +CARD_END = '' +DEFAULT_REPO = 'cubec/PartProbe3D-preprocessed' + + +class Snapshot: + """Resolve the Hub revision once and cache only small inventory files.""" + def __init__(self, repo, revision, cache): + from huggingface_hub import HfApi + self.repo = repo + self.revision = HfApi().dataset_info(repo, revision=revision).sha + self.cache = Path(cache) + self.indices = {} + self.hashes = {} + + def read(self, path): + from huggingface_hub import hf_hub_download + if path not in self.indices: + file = hf_hub_download(self.repo, path, repo_type='dataset', revision=self.revision, + local_dir=self.cache) + self.indices[path] = _json(file) + self.hashes[path] = sha256(file) + return self.indices[path] + + +def _names(value, available): + names = list(available) if value == 'all' else value.split(',') + if not names or len(names) != len(set(names)) or any(name not in available for name in names): + raise ValueError(f'Choose unique datasets from: {", ".join(available)}') + return names + + +def _component(snapshot, path, *, kind, archive_files=None): + relative = _relative(path) + index = snapshot.read(f'{relative}/index.json') + if (index.get('schema') != SCHEMA or not index.get('complete') + or index.get('name') != relative.name or index.get('artifact_kind') != kind): + raise ValueError(f'Incomplete or incompatible component: {path}') + archives = index['archives'] + if index.get('bytes') != sum(row['bytes'] for row in archives): + raise ValueError(f'Archive sizes differ from the component total: {path}') + if archive_files is not None: + archives = [row for row in archives if row['file'] in archive_files] + result = {'path': path, 'destination': index['destination'], + 'index_sha256': snapshot.hashes[f'{relative}/index.json'], + 'bytes': sum(row['bytes'] for row in archives), 'archives': len(archives)} + if archive_files is not None: + result['archive_files'] = [row['file'] for row in archives] + return result + + +def plan(snapshot, task, datasets='all'): + """Validate every requested dependency before transferring any data archive.""" + if task not in TASKS: + raise ValueError(f'Unknown task: {task}') + notes = ['Model weights are separate. Download only the configured model assets.'] + if task == 'eval': + index = snapshot.read('evaluation/index.json') + names = _names('all' if datasets == 'evaluation' else datasets, index['datasets']) + files = {'metadata.tar'} + for name in names: + shards = {row['file'] for row in index['archives'] if row['file'].startswith(f'{name}-')} + if not shards: + raise ValueError(f'No evaluation archives for {name}') + files.update(shards) + if not any(row['file'] == 'metadata.tar' for row in index['archives']): + raise ValueError('The evaluation metadata archive is missing') + components = [_component(snapshot, 'evaluation', kind='frozen-evaluation', archive_files=files)] + notes += ['Metadata describes the full cohort. Data files cover only the selected datasets.', + 'This bundle has RGB, masks and GT meshes. Depth-dependent models need their configured depth estimator.'] + else: + recipe = snapshot.read('training/index.json') + if recipe.get('schema') != 'partprobe3d.reproduction.v1' or not recipe.get('complete'): + raise ValueError('The active training inventory is incomplete') + defaults = recipe['default_datasets'] + if task != 'all-training': + supported = [name for name in defaults if all( + f'training/{role}/{name}' in recipe['datasets'][name]['required'] for role in ROLES[task])] + omitted = [name for name in defaults if name not in supported] + if datasets == 'all' and omitted: + notes.append(f'Targets unavailable for {", ".join(omitted)}. These datasets are excluded from this task default.') + defaults = supported + names = _names(datasets, defaults if datasets == 'all' else recipe['datasets']) + if not names: + raise ValueError(f'No published datasets support {task}') + selected = [] + for name in names: + required = recipe['datasets'][name]['required'] + paths = required if task == 'all-training' else [f'training/{role}/{name}' for role in ROLES[task]] + for path in paths: + relative = _relative(path) + if relative.parts[0] != 'training' or relative.name != name: + raise ValueError('Task downloads must remain in the active training folder') + if path not in required: + raise ValueError(f'{task} targets are unavailable for {name}: {path}') + role = '/'.join(relative.parts[1:-1]) + if role not in KINDS: + raise ValueError(f'Unknown training component: {path}') + selected.append((path, KINDS[role])) + components = [_component(snapshot, path, kind=kind) for path, kind in selected] + if task == 'ss': + notes.append('Native SS targets are ready. Online SS training requires no target encoding.') + if task == 'slat-seg': + notes.append('Segmentation generates instance codes and image features during training. No latent target download is required.') + if task == 'slat-shape': + notes.append('Use an online shape configuration to avoid a separate feature cache.') + notes.append('Custom configs can require optional occlusion data or additional test observations.') + return {'schema': 'partprobe3d.task-download.v1', 'repo': snapshot.repo, + 'revision': snapshot.revision, 'task': task, 'datasets': names, 'components': components, + 'archive_bytes': sum(row['bytes'] for row in components), 'notes': notes} + + +def download_task(repo, task, datasets, destination, revision='main', *, cleanup=True, dry_run=False): + from preprocess.huggingface import download + snapshot = Snapshot(repo, revision, Path(destination).resolve() / 'outputs/huggingface/tasks') + selected = plan(snapshot, task, datasets) + print(json.dumps(selected, indent=2), flush=True) + if not dry_run: + for row in selected['components']: + path = _relative(row['path']) + kwargs = {'archive_files': row['archive_files']} if 'archive_files' in row else {} + download(repo, path.name, destination, snapshot.revision, cleanup=cleanup, + bundle_root='' if len(path.parts) == 1 else str(path.parent), **kwargs) + return selected + + +def catalog(snapshot): + profiles = {} + for task in TASKS: + default = plan(snapshot, task) + profiles[task] = {**default, 'by_dataset': { + name: plan(snapshot, task, name) for name in default['datasets']}} + return {'schema': 'partprobe3d.task-catalog.v1', 'repo': snapshot.repo, + 'data_revision': snapshot.revision, 'profiles': profiles, + 'inventory_sha256': dict(snapshot.hashes), + 'restore_git_revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()} + + +def card_section(inventory=None, repo=DEFAULT_REPO): + descriptions = {'eval': 'RGB, masks and GT meshes', 'ss': 'Observations and native SS targets', + 'slat-seg': 'Observations only', 'slat-shape': 'Observations and 32³ object shape targets', + 'all-training': 'All published training components'} + lines = [CARD_START, '## Download by task', '', + 'Select a task to avoid unnecessary data transfers.', + 'The [task catalog](tasks/index.json) records component paths, sizes, and the data revision.', + 'The [task guide](tasks/README.md) lists downloads for individual datasets.', '', + '| Task | Required data | Default transfer, GB |', '| --- | --- | ---: |'] + for task in TASKS: + size = f'{inventory["profiles"][task]["archive_bytes"]/1e9:.3f}' if inventory else 'See catalog' + lines.append(f'| [`{task}`](tasks/{task}/index.json) | {descriptions[task]} | {size} |') + lines += ['', 'Use the current project checkout for these commands.', 'Preview the transfer before downloading:', '', + '```bash', f'python -m preprocess.huggingface download --repo {repo} --task ss --dry-run', '```', '', + 'Select the task required by this server:', '', '```bash'] + for task in TASKS[:-1]: + lines.append(f'python -m preprocess.huggingface download --repo {repo} --task {task}') + lines += ['```', '', 'Select individual datasets with `--dataset`, using commas for multiple datasets.', '', '```bash', + f'python -m preprocess.huggingface download --repo {repo} --task eval --dataset picasso', + f'python -m preprocess.huggingface download --repo {repo} --task eval --dataset picasso,messykitchen', + f'python -m preprocess.huggingface download --repo {repo} --task slat-seg --dataset foundationpose', + '```', '', 'FoundationPose supports SS and segmentation. Its shape targets remain unavailable.', '', + 'Shape defaults include 3D-FRONT and SAGE. An explicit FoundationPose shape request fails before archive transfer.', '', + 'SS uses the published native targets without another target encoding pass.', + 'Segmentation computes its instance codes and image features during training.', '', + 'Online shape conditioning avoids a separate image-feature cache.', '', + 'Model weights remain separate. Download only the assets required by the selected model.', '', + 'Old commands without `--task` still restore all training components.', CARD_END] + return '\n'.join(lines) + + +def update_card(card, inventory, repo): + if inventory: + card = re.sub(r'Use project Git revision `[^`]+` or later\.', + f'Use project Git revision `{inventory["restore_git_revision"]}` or later.', card) + section = card_section(inventory, repo) + if CARD_START in card: + start, end = card.index(CARD_START), card.index(CARD_END) + len(CARD_END) + return card[:start] + section + card[end:] + # Put the task choices before the historical all-training instructions. + marker = '## Restore tools' + position = card.index(marker) if marker in card else len(card.rstrip()) + return card[:position].rstrip() + '\n\n' + section + '\n\n' + card[position:] + + +def publish(repo, output, *, revision='main'): + """Publish small task inventories without moving or uploading data archives.""" + from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download + from huggingface_hub.errors import HfHubHTTPError + output = Path(output).resolve() + for attempt in range(5): + snapshot = Snapshot(repo, revision, output / 'remote') + inventory = catalog(snapshot) + folder = output / 'tasks' + folder.mkdir(parents=True, exist_ok=True) + atomic_json(folder / 'index.json', inventory) + section = card_section(inventory, repo) + lines = ['# Task-specific data downloads', '', + f'Use project Git revision `{inventory["restore_git_revision"]}` or later.', + f'The measured sizes refer to HF data revision `{snapshot.revision}`.', + 'Sizes use decimal GB. Local extracted data needs additional space.', + 'A dry run reads small indices. It does not transfer data archives.', '', + section.replace('](tasks/', ']('), '', + '| Task | Dataset | Transfer, GB |', '| --- | --- | ---: |'] + paths = ['tasks/index.json', 'tasks/README.md'] + for task, profile in inventory['profiles'].items(): + (folder / task).mkdir(exist_ok=True) + atomic_json(folder / task / 'index.json', profile) + paths.append(f'tasks/{task}/index.json') + for name, row in profile['by_dataset'].items(): + lines.append(f'| `{task}` | {name} | {row["archive_bytes"]/1e9:.3f} |') + lines += ['', 'Evaluation sizes include the shared metadata archive for each individual dataset.', + 'Combined selections download shared metadata once.', + 'Existing archives keep their original paths and checksums.', + 'No training or evaluation result changes.', '', + 'Regenerate this catalog after publishing new components:', '', '```bash', + f'python -m preprocess.tasks publish --repo {repo} --output outputs/huggingface/tasks', '```', ''] + (folder / 'README.md').write_text('\n'.join(lines)) + card = Path(hf_hub_download(repo, 'README.md', repo_type='dataset', revision=snapshot.revision, + local_dir=output / 'remote')).read_text() + # Keep the existing cache and benchmark sections while updating the SS command. + card = card.replace(f'python -m preprocess.huggingface download --repo {repo}\n```\n\nSS training', + f'python -m preprocess.huggingface download --repo {repo} --task ss\n```\n\nSS training') + (output / 'README.md').write_text(update_card(card, inventory, repo)) + paths.append('README.md') + try: + result = _retry(lambda: HfApi().create_commit(repo_id=repo, repo_type='dataset', + parent_commit=snapshot.revision, commit_message='Categorize downloads by evaluation and training task', + operations=[CommitOperationAdd(path_in_repo=path, path_or_fileobj=output / path) for path in paths])) + except HfHubHTTPError as error: + if error.response is None or error.response.status_code not in (409, 412) or attempt == 4 or revision != 'main': + raise + continue + atomic_json(output / 'status.json', {'complete': True, 'repo': repo, 'revision': result.oid, + 'data_revision': snapshot.revision, 'files': paths}) + return inventory + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('command', choices=('publish',)) + parser.add_argument('--repo', default=DEFAULT_REPO) + parser.add_argument('--output', type=Path, default=Path('outputs/huggingface/tasks')) + parser.add_argument('--revision', default='main') + args = parser.parse_args() + publish(args.repo, args.output, revision=args.revision) + + +if __name__ == '__main__': + main() diff --git a/preprocess/tests/test_reproduction.py b/preprocess/tests/test_reproduction.py new file mode 100644 index 0000000..c27f13e --- /dev/null +++ b/preprocess/tests/test_reproduction.py @@ -0,0 +1,258 @@ +"""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_repeated_package_preserves_archive_prefix_after_layout_change(tmp_path): + root, output = tmp_path / 'source', tmp_path / 'archives' + root.mkdir() + image = root / 'rgb.png' + image.write_bytes(b'frozen image') + arguments = dict(kind='frozen-evaluation', metadata=[], groups=[('fixture', [image], 1)]) + index = package(root, output, 'optional', 'evaluation', + destination=Path('datasets/evaluation/indoor'), **arguments) + index['archive_prefix'] = index['destination'] + index['destination'] = 'datasets/evaluation' + atomic_json(output / 'optional/evaluation/index.json', index) + repeated = package(root, output, 'optional', 'evaluation', + destination=Path('datasets/evaluation'), **arguments) + assert repeated == index + restored = extract(repeated, output / 'optional/evaluation', tmp_path / 'server') + assert (restored / 'rgb.png').read_bytes() == image.read_bytes() + assert not (restored / 'indoor').exists() + + +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') + + +@pytest.mark.parametrize('dataset,bundle_root,optional', [ + ('evaluation', None, False), ('ycbv', 'optional/evaluation', True)]) +def test_evaluation_download_routes_required_cohort_and_optional_dataset(monkeypatch, dataset, bundle_root, optional): + import sys + from preprocess import huggingface + arguments = ['huggingface', 'download', '--repo', 'owner/repo', '--dataset', dataset] + if optional: + arguments.extend(['--optional', 'evaluation']) + monkeypatch.setattr(sys, 'argv', arguments) + calls = [] + monkeypatch.setattr(huggingface, 'download', lambda *a, **k: calls.append((a, k))) + huggingface.main() + assert calls[0][0][1] == dataset + assert calls[0][1]['bundle_root'] == bundle_root + assert calls[0][1]['cleanup'] + + +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 diff --git a/preprocess/tests/test_ss_targets.py b/preprocess/tests/test_ss_targets.py new file mode 100644 index 0000000..7d7636f --- /dev/null +++ b/preprocess/tests/test_ss_targets.py @@ -0,0 +1,236 @@ +"""Portable SS targets retain exact supervision without another encoding pass.""" +from copy import deepcopy +import hashlib +import json +from pathlib import Path +import shutil +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +from preprocess import ss_targets as module +from preprocess.front3d.splits import MIDI_TEST_ROOM_IDS +from preprocess.generator_targets import VoxelSettings +from preprocess.huggingface import extract +from preprocess.reproduction import package, stage_observations +from preprocess.storage import atomic_json, atomic_npz +from preprocess.tests.test_extent_spec import CameraCaptures, CameraTargets +from ss_multiobj_depth.config import TARGET_SCOPE +from ss_multiobj_depth.dataloader import FEATURE_SCHEMA, OnlineObservationDataset, SSDepthDataset +from utils.hashing import sha256 + + +@pytest.fixture +def targets(tmp_path): + capture, observations, cache = (tmp_path / name for name in ('map', 'observations', 'cache')) + source = {'complete': True, 'views': [ + {'scene': scene, 'source_view': str(view), 'frame': str(view), 'split': split} + for scene, split in [('train-house/train-room', 'train'), (MIDI_TEST_ROOM_IDS[0], 'test')] + for view in range(2)]} + class Captures(CameraCaptures): + def capture_view(self, row): + view = super().capture_view(row) + for name in ('rgb', 'instance_labels', 'depth'): + values = getattr(view, name) + setattr(view, name, np.repeat(np.repeat(values, 16, axis=0), 16, axis=1)) + view.camera['renderProductResolution'] = [64, 64] + intrinsics = np.asarray(view.camera['intrinsics_K']) + intrinsics[:2] *= 16 + view.camera['intrinsics_K'] = intrinsics.tolist() + return view + Captures(source, {}).generate_captures(capture) + CameraTargets.generate_targets(capture, observations, VoxelSettings(64, minimum_mask_pixels=1, extent_strategy='mesh')) + data = SSDepthDataset(observations) + cache.mkdir() + models = {'upstream': 'third_party/Pixal3D', 'upstream_revision': 'revision', + 'encoder': 'checkpoints/encoder', 'decoder': 'checkpoints/decoder', + 'paired_decoder': 'checkpoints/paired_decoder', 'dino': 'checkpoints/DINOv3'} + files = {models[key] + suffix: 'weight-hash' for key in ('encoder', 'decoder', 'paired_decoder') + for suffix in (('.safetensors',) if key == 'paired_decoder' else ('.json', '.safetensors'))} + files['checkpoints/DINOv3/model.safetensors'] = 'image-weight-hash' + policy = {'target_scope': TARGET_SCOPE, 'dataset': data.provenance(), + 'settings': {'models': models}, 'models': {'files': files, 'upstream_revision': 'revision'}} + atomic_json(cache / 'policy.json', policy) + rows, expected = [], {} + for number, row in enumerate(data.rows): + sample = data[number] + occupancy = sample['occupancy'][0].numpy() + directory = hashlib.sha256(row['id'].encode()).hexdigest()[:24] + folder = cache / directory + folder.mkdir() + clean = torch.arange(32768, dtype=torch.float32).reshape(8, 16, 16, 16) / 32768 + number + if number % 2: + clean = clean.half() + expected[row['id']] = clean.clone() + torch.save({'clean': clean, 'historical_image_features': torch.ones(8)}, folder / 'features.pt') + atomic_npz(folder / 'targets.npz', occupancy=occupancy) + arrays, camera = data.read(number) + atomic_json(folder / 'geometry.json', {'grid': data.grid(arrays, camera).as_dict()}) + entry = {**{key: row[key] for key in ('id', 'scene', 'split')}, 'directory': directory, + 'inputs': {key: sha256(observations / row[key]) for key in ('sample', 'camera', 'scene_gt')}, + 'occupied_cells': int(occupancy.sum()), + 'files': {name: sha256(folder / name) for name in ('features.pt', 'targets.npz', 'geometry.json')}} + atomic_json(folder / 'complete.json', entry) + rows.append(entry) + atomic_json(cache / 'manifest.json', {'schema': FEATURE_SCHEMA, 'complete': True, 'dataset': '3D-FRONT', + 'policy_sha256': sha256(cache / 'policy.json'), 'entries': rows}) + return observations, cache, expected + + +def test_restore_retains_exact_latents_and_loads_without_original_environment(targets, tmp_path, monkeypatch): + observations, cache, expected = targets + manifest, metadata, groups, checksums = module.index_targets(cache, observations, monitor_views=1) + assert len(manifest['entries']) == 4 + original_manifest = sha256(cache / 'manifest.json') + original_policy = sha256(cache / 'policy.json') + policy = json.loads((cache / 'policy.json').read_text()) + assert policy['dataset']['root'] == str(observations.resolve()) + for row in manifest['entries']: + saved = torch.load(cache / row['directory'] / 'features.pt', weights_only=True) + assert 'historical_image_features' in saved + assert torch.equal(saved['clean'], expected[row['id']]) + assert saved['clean'].dtype == expected[row['id']].dtype + module.index_targets(cache, observations, monitor_views=1) + assert sha256(cache / 'manifest.json') == original_manifest + output = tmp_path / 'archives' + index = package(cache, output, 'training/ss', '3dfront', + destination=Path('outputs/ss_multiobj_depth/front3d/masked_objects/targets'), + kind='ss-latent-targets', metadata=metadata, groups=groups, checksums=checksums) + server = tmp_path / 'another-server' + restored = extract(index, output / 'training/ss/3dfront', server) + assert sha256(restored / 'manifest.json') == original_manifest + assert sha256(restored / 'policy.json') == original_policy + _, obs_metadata, obs_groups, _, obs_checksums = stage_observations(observations, tmp_path / 'obs-stage', monitor_views=1) + obs_index = package(observations, output, 'training/observations', '3dfront', + destination=Path('datasets/3dfront/extent/point_cloud'), kind='compact-training', + metadata=obs_metadata, groups=obs_groups, checksums=obs_checksums) + restored_observations = extract(obs_index, output / 'training/observations/3dfront', server) + shutil.rmtree(observations) + shutil.rmtree(cache) + import ss_multiobj_depth.prepare + monkeypatch.setattr(ss_multiobj_depth.prepare, 'load_target_encoder', + lambda *a, **k: pytest.fail('Restoration must not invoke the SS encoder')) + for split, count in [('train', 2)]: + data = OnlineObservationDataset(restored_observations, restored, split=split) + assert len(data) == count + for row, sample in zip(data.rows, data): + assert torch.equal(sample['clean'], expected[row['id']]) + assert sample['clean'].dtype == expected[row['id']].dtype + assert sample['rgb'].shape == (3, 64, 64) + + +@pytest.mark.parametrize('damage', ['latent', 'incomplete', 'dataset', 'missing_view']) +def test_export_rejects_corrupt_or_incompatible_targets(targets, tmp_path, damage): + observations, cache, _ = targets + path = cache / 'manifest.json' + manifest = json.loads(path.read_text()) + if damage == 'latent': + (cache / manifest['entries'][0]['directory'] / 'features.pt').write_bytes(b'corrupt') + elif damage == 'incomplete': + manifest['complete'] = False + atomic_json(path, manifest) + elif damage == 'dataset': + (observations / 'manifest.json').write_text((observations / 'manifest.json').read_text() + '\n') + else: + manifest['entries'] = [] + atomic_json(path, manifest) + with pytest.raises(ValueError): + module.index_targets(cache, observations, monitor_views=1) + + +def test_registration_preserves_remote_edits_and_adds_targets_to_default_download(tmp_path, monkeypatch): + import httpx + import huggingface_hub + from huggingface_hub.errors import HfHubHTTPError + recipe = {'schema': module.RECIPE_SCHEMA, 'complete': True, 'default_datasets': ['3dfront', 'sage'], + 'datasets': {name: {'bytes': 10, 'training_views': 2, 'required': [f'training/observations/{name}'], + 'source_manifest_sha256': 'dataset', 'ss_targets': {'bytes': 2, 'views': 3}} + for name in ('3dfront', 'sage', 'foundationpose')}, 'optional': {}} + del recipe['datasets']['foundationpose']['ss_targets'] + remote = tmp_path / 'remote' + remote.mkdir() + api = SimpleNamespace(dataset_info=lambda *a, **k: SimpleNamespace(sha='revision')) + attempts = [] + def download(repo, filename, **kwargs): + if filename == 'training/index.json': + value = deepcopy(recipe) + if attempts: + value['optional']['concurrent_evaluation'] = {'bytes': 123} + path = remote / 'index.json' + atomic_json(path, value) + else: + path = remote / 'README.md' + path.write_text('# Existing card\n\nKeep the evaluation section.\n') + return str(path) + def commit(**kwargs): + attempts.append(kwargs) + if len(attempts) == 1: + raise HfHubHTTPError('Concurrent edit', response=httpx.Response(409, request=httpx.Request('POST', 'https://hf.test'))) + return SimpleNamespace(oid='registered') + api.create_commit = commit + monkeypatch.setattr(huggingface_hub, 'HfApi', lambda: api) + monkeypatch.setattr(huggingface_hub, 'hf_hub_download', download) + output = tmp_path / 'output' + output.mkdir() + index = {'dataset_manifest_sha256': 'dataset', 'bytes': 5, 'views': 3, 'training_views': 2} + assert module.register('owner/repo', output, 'foundationpose', index) == 'registered' + actual = json.loads((output / 'training/index.json').read_text()) + assert actual['optional']['concurrent_evaluation']['bytes'] == 123 + assert actual['datasets']['foundationpose']['required'][-1] == 'training/ss/foundationpose' + assert actual['datasets']['foundationpose']['bytes'] == 15 + assert actual['default_datasets'] == ['3dfront', 'sage', 'foundationpose'] + assert 'Keep the evaluation section.' in (output / 'README.md').read_text() + assert all(attempt['parent_commit'] == 'revision' for attempt in attempts) + + +def test_republication_retains_only_compatible_targets_and_standard_download_restores_them(tmp_path, monkeypatch): + import huggingface_hub + import preprocess.huggingface + from preprocess.reproduction import download_training + current = {'schema': module.RECIPE_SCHEMA, 'complete': True, 'default_datasets': ['3dfront'], + 'datasets': {'3dfront': {'bytes': 10, 'required': ['training/observations/3dfront'], + 'source_manifest_sha256': 'dataset'}}, 'optional': {}} + previous = deepcopy(current) + previous['datasets']['3dfront']['ss_targets'] = {'component': 'training/ss/3dfront', 'bytes': 5, 'views': 3} + previous['restore_git_revision'] = 'code' + path = tmp_path / 'registered.json' + atomic_json(path, previous) + 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(path)) + module.retain_registered(current, 'owner/repo', tmp_path) + module.retain_registered(current, 'owner/repo', tmp_path) + assert current['datasets']['3dfront']['bytes'] == 15 + assert current['datasets']['3dfront']['required'] == ['training/observations/3dfront', 'training/ss/3dfront'] + atomic_json(path, current) + calls = [] + monkeypatch.setattr(preprocess.huggingface, 'download', lambda *a, **k: calls.append(k['bundle_root'])) + download_training('owner/repo', 'all', tmp_path) + assert calls == ['training/observations', 'training/ss'] + current['datasets']['3dfront']['source_manifest_sha256'] = 'changed' + current['datasets']['3dfront'].pop('ss_targets') + current['datasets']['3dfront']['required'] = ['training/observations/3dfront'] + module.retain_registered(current, 'owner/repo', tmp_path) + assert 'ss_targets' not in current['datasets']['3dfront'] + + +def test_complete_card_removes_ss_preparation_and_retains_other_sections(): + recipe = {'restore_git_revision': 'current-code', 'default_datasets': ['3dfront', 'sage', 'foundationpose'], + 'datasets': {name: {'bytes': 1000000000, 'ss_targets': {'views': 10, 'bytes': 100}} + for name in ('3dfront', 'sage', 'foundationpose')}} + card = ('The default transfer is **1.00 GB**, including old data.\n\n' + '## Restore tools\n\nold bootstrap patch\n\n## Default download\n\n' + 'The command restores 3D-FRONT, SAGE-10k, and their 32³ object shape targets.\n' + 'FoundationPose requires explicit selection and supports SS and segmentation.\n' + 'Run SS preparation before SS training.\n' + 'python -m ss_multiobj_depth.prepare --config ss_multiobj_depth/configs/front3d_sage.json\n' + 'python -m ss_multiobj_depth.train --config ss_multiobj_depth/configs/front3d_sage.json\n' + '\n## Evaluation\n\nKeep evaluation links.\n') + updated = module.update_card(card, recipe, 'owner/repo') + assert '**3.00 GB**' in updated and 'current-code' in updated + assert 'old bootstrap patch' not in updated and 'ss_multiobj_depth.prepare' not in updated + assert 'Keep evaluation links.' in updated and 'FoundationPose shape targets remain unavailable.' in updated + assert 'python -m preprocess.huggingface download --repo owner/repo' in updated + assert module.update_card(updated, recipe, 'owner/repo') == updated 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/ss_multiobj_depth/README.md b/ss_multiobj_depth/README.md index 8307513..fbcbca8 100644 --- a/ss_multiobj_depth/README.md +++ b/ss_multiobj_depth/README.md @@ -13,6 +13,121 @@ Partial mode connects SS and the native SLAT shape stage. Mesh evaluation uses t In this document, SS means sparse structure, and GT means ground truth. An extent defines the spatial bounds of a voxel grid. +## Configuration inventory + +This table collects the controls for SS training and inference. + +**Keep** marks active controls. **Review** marks candidates for deprecation. **Compatibility** marks historical inputs. **Fixed** marks architectural requirements. +These labels are review recommendations. They do not change supported behavior. + +Control locations are: + +- **Run:** the selected stage JSON, including the [CLI training default](configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json). +- **Optimizer:** the shared [optimization recipe](../utils/training/configs/default.json), selected through `training.optimizer_config`. +- **CFG:** the `ss` section of the shared [CFG profile](../utils/training/configs/cfg.json), selected through `cfg_config`. + +The CLI default uses object means, learned coverage gates, and online conditions across all three datasets. +Earlier point-sampling and cached presets remain available through explicit configurations. +The [two-dataset coverage preset](configs/front3d_sage_object_mean_image_coverage_gate.json) retains its historical dataset mix and batch settings. + +| Area | Control and location | Current value or choices | Recommendation and dependency | +| --- | --- | --- | --- | +| Conditioning | Run: `model.voxel_aggregation` | CLI: `object_mean`. Earlier explicit presets retain `point`. | **Keep** object means as the default. **Review** the earlier point branch. | +| Conditioning | Run: `model.voxel_condition_mode` | `depth_embedding`. Alternative: `additive`. | **Keep** the embedding gate and additive conditioning. Object means require `depth_embedding`. | +| Conditioning | Run: `model.voxel_condition_hidden_channels` | `64` for the embedding gate, `0` for additive mode. | **Keep** gate width. The additive value depends on retaining that branch. | +| Conditioning | Run: `model.depth_channels` | `128`. Positive embedding width. | **Keep.** This controls the shared depth encoder. | +| Conditioning | Run: `model.voxel_image_features` | `dino` only. | **Fixed.** Local features use DINOv3. This selector applies to object means. | +| Conditioning | Whole-mask descriptor | DINOv3/NAF, 2048 channels, in object-mean mode. | **Fixed.** SS exposes no separate mask-feature selector. | +| Conditioning | Run: `model.voxel_coverage_weighting` | Coverage preset: `learned_gate`. Earlier object means: `area`. | **Keep** learned coverage. **Review** area multiplication. Learned coverage requires object means. | +| Attention | Run: `model.cross_attention_mode` | `global`. Alternative: `occlusion_object`. | **Keep** global attention. **Review** object attention and its occlusion dependencies. Object means require `global`. | +| Adapters | Run: `model.adapter_method` | `shared` resolves to `lora`. Explicit `lora` or `nora` also works. | **Keep** the shared selector. **Review** per-run overrides after comparisons finish. | +| Adapters | Run: `model.image_projection_adaptation` | `shared` resolves to `lora`. Alternatives: `full`, `nora`, `lora`. | **Keep** shared image adapters. **Review** alternate branches after checking checkpoints and ablations. | +| Adapters | Run: `model.rank`, `model.alpha` | `8`, `8.0`. SS also accepts rank `0`. | **Keep** adapter dimensions. **Review** rank-zero training if no experiment needs it. | +| Adapters | Optimizer: `adapter_method` | `lora`. Alternative: `nora`. | **Keep.** This selects backbone and image adapters across all three stages. | +| Optimizer | Optimizer: `optimizer.name` | `AdamW` only. | **Fixed.** Consider removing this redundant selector from future presets. | +| Optimizer | Optimizer: `learning_rate` | `1e-4`. | **Keep.** Target rate for new layers. | +| Optimizer | Optimizer: `optimizer.adapter_learning_rate` | `1e-4`. | **Keep.** Target rate for adapter matrices. | +| Optimizer | Optimizer: `optimizer.betas`, `optimizer.eps` | `[0.9, 0.95]`, `1e-8`. | **Keep.** Shared optimizer controls. | +| Optimizer | Optimizer: `weight_decay` | `0.01`. | **Keep.** Decay for non-adapter matrices. | +| Optimizer | Optimizer: `optimizer.adapter_weight_decay` | `0.01`. | **Keep.** Decay for adapter matrices. | +| Optimizer | Optimizer: `optimizer.bias_norm_scalar_weight_decay` | `0`. | **Keep.** Includes biases, normalization parameters, scalars, and other vectors. | +| Optimizer | Optimizer: `optimizer.warmup_steps` | `500` optimizer updates. | **Keep one control.** The loader derives `training.warmup` from this value. | +| EMA | Optimizer: `ema_decay` | `0.999`. `null` disables EMA. | **Keep.** EMA averages trainable parameters only. | +| EMA | Run: `inference_weights` | Omitted, resolves to `auto`. Alternatives: `raw`, `ema`. | **Keep.** Auto selects EMA when available, otherwise raw weights. | +| CFG | CFG: `cfg_dropout` | `0.1`. | **Keep.** Joint condition dropout during training. | +| CFG | CFG: `guidance_strength` | `7.5`. | **Keep.** Resolves to `sampling.cfg_strength` for SS inference. | +| CFG | CFG: `guidance_rescale` | `0.7`. | **Keep.** Resolves to `sampling.cfg_rescale`. | +| CFG | CFG: `guidance_interval` | `[0.6, 1.0]`. | **Keep.** Resolves to `sampling.cfg_interval`. | +| Sampling | Run: `sampling.steps`, `sampling.rescale_t` | `12`, `5`. | **Keep.** These control inference integration, separately from CFG. | +| Objective | Loss and timestep distribution | Native dense MSE. Time is `sigmoid(N(1,1))`. | **Fixed.** No loss-weight or timestep-distribution selector exists. | +| Data | Run: `sources[].dataset`, `sources[].cache` | 3D-FRONT and SAGE, sampled with equal probability. | **Keep.** Combined runs need distinct datasets and cache paths. | +| Data | Run: `dataset`, `cache` | Used instead of `sources` for a single dataset. | **Keep.** Single-source preparation and training still use this form. | +| Data | Run: `training.conditioning_source` | CLI: omitted, resolves to `cached`. Coverage preset: `online`. | **Keep both pending a default decision.** Online extraction requires object means and verified cached SS targets. | +| Data | Run: `depth_source`, `moge_config` | Training: `gt`. Inference uses the MoGe-3 configuration. | **Keep.** Training requires saved GT depth and calibration. | +| Extent | Evaluation: `method_config.extent_spec`, including `strategy` and `options` | Inference uses `point_cloud` defaults. Training reads the saved dataset grid. | **Keep** inference extent controls. The training JSON rejects extent overrides. See [extent behavior](#inference-extent-definition). | +| Augmentation | Run: `training.depth_augmentation.noise_probability` | `0.3`. | **Keep.** Probability of Gaussian depth noise for each view. | +| Augmentation | Run: `training.depth_augmentation.noise_std_fraction` | `0.015625`. | **Keep.** Noise standard deviation as a fraction of cube size. | +| Augmentation | Run: `training.depth_augmentation.pixel_dropout` | `0.1`. | **Keep.** Independent removal of valid depth pixels during training. | +| Training | Run: `training.steps` | `20000`. | **Keep.** Number of optimizer updates. | +| Training | Run: `training.batch_size`, `training.accumulation` | `16`, `1`. Effective batch: `16`. | **Keep.** These control memory use and effective batch size. | +| Training | Run: `training.workers` | `4`. | **Keep.** CPU data-loader workers. | +| Monitoring | Run: `training.save_every`, `training.eval_every`, `training.eval_limit` | `500`, `500`, `8` test views per dataset. | **Keep.** Zero evaluation cadence disables scheduled monitoring. | +| Monitoring | Run: `training.wandb_mode`, `wandb_project`, `wandb_entity` | `online`, `PartProbe3D`, `null`, all under `training`. | **Keep.** W&B mode also accepts `offline` and `disabled`. | +| Runtime | Run: `device`, `seed`, `output`, `checkpoints` | `cuda:0`, `0`, preset-specific directories. | **Keep.** Select a logical device from the visible GPUs. | +| Assets | Run: `models.*` | Pinned Pixal3D, DINOv3, SS encoder/decoder, and optional NAF assets. | **Keep.** Asset paths and source revisions define initialization and provenance. | +| CLI | Training: `--config`, `--resume`, `--accept-source-changes` | Default preset, fresh run, strict source checks. | **Keep.** These select the run and control explicit resume behavior. | +| CLI | Preparation: `--shard`, `--shards` | `0`, `1`. | **Keep.** Preparation can process independent interleaved shards. | +| Compatibility | Inline optimizer/CFG values in saved runs | Resolved historical settings. | **Compatibility.** New presets use shared files. Inline overrides cannot accompany their corresponding profile reference. | +| Compatibility | Optimizer: `optimizer.adapter_learning_rate_after_warmup`, `optimizer.exclude_bias_norm_from_weight_decay` | Absent from the shared default. Earlier rate and decay policies. | **Review** independent scheduling. **Compatibility** for the older decay flag. | + +The equations below explain the supported branches. +The table is the configuration reference, including candidates for deprecation. +Historical experiment sections retain the values used by those runs. +Saved run configurations retain resolved optimization and CFG values with their source hashes. +The [configuration loader](config.py) and [shared voxel settings](../models/voxel_condition.py) define validation and checkpoint compatibility. + +## Default training + +The default includes 3D-FRONT, SAGE-10k, and FoundationPose with equal sampling probability. +It uses a real batch of 16 and one accumulation step. +The [preset for `cuda:1`](configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json) selects the second visible GPU and separate run directories. +It initializes from pretrained Pixal3D SS weights. + +Local image conditions use 1024-channel DINOv3 features. +Whole-mask descriptors use 2048-channel DINOv3/NAF features. +Object means use depth embeddings and raw mask coverage in learned gates. +Native global image cross-attention remains enabled. +The backbone and image projections use rank-8 LoRA with alpha 8 and trainable image biases. + +Both learning rates target `1e-4` after 500 linear warmup updates. +AdamW uses betas `[0.9, 0.95]`, matrix decay `0.01`, and zero decay for biases and normalization parameters. +The run uses 20,000 optimizer updates, EMA decay `0.999`, and online W&B logging. +It saves checkpoints and evaluates eight test views per dataset every 500 updates. +Training uses GT depth with the configured noise and dropout. + +The [portable SS guide](../preprocess/SS_TARGETS.md) describes HF restoration without target encoding. +Use its standard download when the selected release includes all required SS components. +Prepare native SS targets when a compatible encoded cache is unavailable: + +```bash +envs/sam3d/bin/python -m ss_multiobj_depth.prepare_targets \ + --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json \ + --batch-size 64 --workers 16 +``` + +Preparation encodes saved voxel labels and requires no shape meshes or SLAT targets. +It preserves completed records after source and artifact checksum checks. +The target caches reside under `outputs/ss_multiobj_depth//masked_objects/targets/`. +The training batch remains 16 regardless of the preparation batch. + +Run training after all three caches are complete: + +```bash +PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ + envs/sam3d/bin/python -m ss_multiobj_depth.train \ + --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json +``` + ## Object-wise region pooling Each voxel defines a projected region in the image. @@ -22,19 +137,22 @@ The local region feature uses this intersection, while the whole-mask object des The mask coverage fraction divides the object-region area by the projected-region area, including background. The [object-mean configuration](configs/front3d_sage_object_footprint_mean.json) enables the shared [region aggregator](../models/object_region_pool.py). -It uses DINOv3 and NAF for local image features and whole-mask object descriptors. +It uses DINOv3 for local image features by default. +Whole-mask object descriptors retain DINOv3 and NAF features. Local features and observed depth use arithmetic means within each object's projected voxel region. No feature replacement or median correction occurs. Let $R_v$ contain visible encoder pixels whose positive camera rays intersect the SS node's spatial box. SS uses its native 16³ endpoint lattice, with midpoint boundaries and boxes clipped to the scene cube. -Let $R_{vi}=R_v\cap M_i$, and let $F(u)$ concatenate bilinear DINOv3 and NAF features at 512 × 512 resolution. +Let $R_{vi}=R_v\cap M_i$. +Let $F_{\mathrm{DINO}}(u)$ contain bilinear DINOv3 features at 512 × 512 resolution. +Let $F_{\mathrm{DINO+NAF}}(u)$ concatenate those features with NAF features at the same resolution. The features and local block update are: $$ \begin{aligned} -f_{vi}&=\operatorname{mean}_{u\in R_{vi}}F(u),\qquad -m_i=\operatorname{mean}_{u\in M_i}F(u),\qquad +f_{vi}&=\operatorname{mean}_{u\in R_{vi}}F_{\mathrm{DINO}}(u),\qquad +m_i=\operatorname{mean}_{u\in M_i}F_{\mathrm{DINO+NAF}}(u),\qquad r_{vi}=|R_{vi}|/|R_v|,\\ D_{vi}&=\operatorname{mean}_{u\in R_{vi},\;D(u)\text{ valid}}D(u),\\ \delta_{vi}&=\operatorname{clip}((z_v-D_{vi})/L_{\mathrm{cube}},-1,1),\\ @@ -44,23 +162,24 @@ L_{v,\ell}&=\sum_i r_{vi}g_{vi,\ell} \end{aligned} $$ -Both feature terms contain 2048 channels. -The optional `voxel_image_features="dino"` selects 1024 local channels while retaining the combined mask descriptor. +Local image features contain 1024 channels by default, with `voxel_image_features="dino"`. +Whole-mask descriptors contain 2048 DINOv3 and NAF channels. The denominator includes background pixels inside the original camera image and encoder crop. Missing depth produces a zero depth embedding. Empty object intersections contribute nothing, while the image bias remains outside the sum. SS has no segmentation identity-code term; generative SLAT segmentation adds that term through the same shared block. Native SS image projections accept 1024 channels. -The combined mode copies their DINO weights and initializes the additional NAF columns at zero. -It preserves the pretrained bias and trains every image weight and bias. +SS copies these weights and their bias from the pretrained Pixal3D SS checkpoint. +The `full` adaptation mode trains every image weight and bias. The new mask projection accepts the combined descriptor and initializes at zero. The configuration uses separate feature caches because historical caches lack object regions and NAF descriptors. Depth corruption changes each original observed pixel once before the object means are calculated. -### Learned coverage gate with image NoRA +### Learned coverage gate with shared adapters -The [SS coverage preset](configs/front3d_sage_object_mean_image_nora_coverage_gate.json) matches the conditioning in the [SLAT coverage preset](../slat_segvigen/configs/object_mean_image_nora_coverage_gate.json). +The [SS coverage preset](configs/front3d_sage_object_mean_image_coverage_gate.json) shares region pooling and coverage gates with the [SLAT coverage preset](../slat_segvigen/configs/object_mean_image_nora_coverage_gate.json). +SS uses DINO-only local features, while the SLAT preset retains DINOv3 and NAF local features. It aggregates image features, whole-mask descriptors, and depth separately for each voxel–object intersection. SS uses no one-hot instance codes or segmentation projection. Its target remains one combined occupancy grid for objects with supplied masks. @@ -89,18 +208,22 @@ The gate initializes to $\sigma(3)$, approximately 0.953. The initial coverage weights are zero. Empty intersections contribute nothing, and the native image bias occurs once after summation. Native global image attention remains active. -The backbone and image projections use rank-8 NoRA with `alpha=8`. -Image projection biases remain trainable. +The backbone and image projections use rank-8 LoRA with `alpha=8` by default. +The [shared recipe](../utils/training/configs/default.json) selects LoRA or NoRA for both projections across all three stages. +The image base retains the native 1024-channel Pixal3D SS weights. +LoRA initializes its residual to zero and keeps those base weights frozen. +The copied image biases remain trainable. This preset uses `training.conditioning_source="online"`. CPU workers prepare crops and ray intersections from the saved extent views. Frozen DINOv3 and NAF encoders calculate conditioning during training. +NAF contributes only to the whole-mask descriptors in the default SS presets. Training reuses the existing verified SS latent targets for complete masked-object occupancy. It does not duplicate the full conditioning cache. Dataset sampling gives equal probability to 3D-FRONT and SAGE-10k. -The [three-dataset configuration](configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json) also uses the FoundationPose export for training. -It retains object-mean conditioning, image NoRA, learned coverage gates, and the shared learning rate of `1e-4`. +The [three-dataset configuration](configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json) also uses the FoundationPose export for training. +It retains object-mean conditioning, image adapters, learned coverage gates, and the shared learning rate of `1e-4`. Each dataset has probability one third for each sampled training view. Sampling gives a 1:1:1 ratio in expectation. Individual batches can contain unequal dataset counts. The run uses 39,930 3D-FRONT views, 17,456 SAGE views, and 42,256 FoundationPose views for training. @@ -109,7 +232,7 @@ Prepare FoundationPose latent targets before this run: ```bash python -m ss_multiobj_depth.prepare_targets \ - --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json \ + --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json \ --dataset foundationpose --batch-size 64 --workers 16 ``` @@ -123,10 +246,12 @@ Run the separate training command: ```bash python -m ss_multiobj_depth.train \ - --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json + --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json ``` -The [2026-10-19 training run](https://wandb.ai/jaeyun/PartProbe3D/runs/58321290) uses this configuration on GPU 1. +The [2026-10-19 training run](https://wandb.ai/jaeyun/PartProbe3D/runs/58321290) used DINOv3 and NAF local features on GPU 1. +The current preset selects DINO-only local features for new runs. +Existing runs and checkpoints retain their recorded feature settings. It used pretrained Pixal3D SS weights with fresh NoRA adapters and conditioning layers. On one RTX 3090, preparation took 19.4 minutes with batch size 64 and 16 CPU workers. @@ -137,7 +262,7 @@ Run a fresh training job from the repository root: ```bash python -m ss_multiobj_depth.train \ - --config ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json + --config ss_multiobj_depth/configs/front3d_sage_object_mean_image_coverage_gate.json ``` The preset uses 20,000 steps and an effective batch size of eight. @@ -301,7 +426,7 @@ $$ #### (3) Selectable voxel conditioning Both SS and SLAT shape use the shared [voxel conditioning module](../models/voxel_condition.py). -The modes `additive`, `depth_scalar`, and `depth_embedding` use the same observation features and latent targets. +The modes `additive` and `depth_embedding` use the same observation features and latent targets. New training selects `depth_embedding` when you omit `--config`. Explicit configurations retain their declared architecture for existing checkpoints and ablations. They control pixel conditioning independently of the attention type. @@ -309,7 +434,7 @@ The setting `model.cross_attention_mode` selects global scene tokens or [occlusi Let $x_v=\operatorname{LN}(h_v(t))$, where $h_v(t)$ is the voxel state after self-attention. The flow timestep $t$ already affects this state. -All three settings use the same residual update: +Both modes use the same residual update: $$ h_v' = h_v(t) + A_v + P_v^{\mathrm{mode}},\qquad @@ -319,11 +444,9 @@ $$ Here, $A_v$ is the selected attention update, and $P_v^{\mathrm{mode}}$ is pixel conditioning. The matrices $W_{\mathrm{mask}}$ and $W_{\mathrm{depth}}$ are linear projections without bias. -| `model.voxel_condition_mode` | Gate input with the hidden state | Separate depth projection | -| --- | --- | --- | -| `additive` | No gate | $W_{\mathrm{depth}}f_d(v)$ | -| `depth_scalar` | Signed residual $\Delta_v = s_d(v)$ | $W_{\mathrm{depth}}f_d(v)$ | -| `depth_embedding` | Depth embedding $f_d(v)$ | None | +The [configuration inventory](#configuration-inventory) lists the mode controls and their review status. +Additive mode has no gate. +Embedding mode gates from the depth embedding and omits the separate depth projection. The pixel-conditioning terms compare directly: @@ -331,9 +454,6 @@ $$ \begin{aligned} P_v^{\mathrm{additive}} &= W_{\mathrm{block}}f_v+W_{\mathrm{mask}}f_m +W_{\mathrm{depth}}f_d+b_{\mathrm{block}},\\ -P_v^{\mathrm{scalar}} &= V_v^{\mathrm{scalar}}(t) - (W_{\mathrm{block}}f_v+W_{\mathrm{mask}}f_m) - +W_{\mathrm{depth}}f_d+b_{\mathrm{block}},\\ P_v^{\mathrm{embedding}} &= V_v^{\mathrm{embedding}}(t) (W_{\mathrm{block}}f_v+W_{\mathrm{mask}}f_m) +b_{\mathrm{block}}. @@ -341,15 +461,12 @@ P_v^{\mathrm{embedding}} &= V_v^{\mathrm{embedding}}(t) $$ The `additive` mode adds image, mask, and depth terms without a gate. -The `depth_scalar` mode gates image and mask terms but retains additive depth. The `depth_embedding` mode uses depth inside its gate and omits the separate depth projection. -Neither gate multiplies the attention update $A_v$ or the projection bias $b_{\mathrm{block}}$. -The two gates are: +The embedding gate does not multiply the attention update $A_v$ or the projection bias $b_{\mathrm{block}}$. +Its equation is: $$ \begin{aligned} -V_v^{\mathrm{scalar}}(t) &= \sigma\!\left(\operatorname{MLP}_{\mathrm{scalar}}( - \operatorname{concat}(x_v,\Delta_v))\right),\\ V_v^{\mathrm{embedding}}(t) &= \sigma\!\left(\operatorname{MLP}_{\mathrm{embedding}}( \operatorname{concat}(x_v,f_d(v)))\right). \end{aligned} @@ -375,37 +492,35 @@ SS has no segmentation identity term $W_{S,\ell}s_v$. The [shared implementation](../models/voxel_condition.py) gates image features before their affine projection. Thus, $W_{I,\ell}(g_{v,\ell}f_v)+b_{I,\ell}=g_{v,\ell}W_{I,\ell}f_v+b_{I,\ell}$. -New training fully updates $W_{I,\ell}$ and $b_{I,\ell}$ from their pretrained Pixal3D values. -This projection uses no low-rank adapter and no random reinitialization. -Its trainable parameters remain float32, while forward computation retains the native feature precision. -Checkpoints store the complete image weight and bias for every block. - -Older checkpoints without these tensors retain Pixal3D image projections during inference. -Their optimizer cannot resume under the new trainable parameter set. -Start a new run to train the image projection and bias. +New training adapts $W_{I,\ell}$ with LoRA and trains $b_{I,\ell}$ from their pretrained Pixal3D values. +The shared recipe selects LoRA or NoRA, and `full` trains the complete projection. +Trainable parameters remain float32, while forward computation retains the native feature precision. +Checkpoints store the selected adapter format and all trainable tensors. +Checkpoint loading requires current parameter names and complete image projection tensors. Each block has its own gate MLP with one hidden layer and SiLU activation. The setting `model.voxel_condition_hidden_channels` controls its width. -Its default is 64 for either depth gate and zero for `additive`. +Its default is 64 for `depth_embedding` and zero for `additive`. The final layer has zero initial weights and bias 3, giving an initial gate near 0.95. The symbol $\sigma$ denotes the sigmoid function. The operator $\operatorname{concat}$ joins feature vectors along their channel dimension. -Neither gate receives a separate timestep embedding or a `depth_valid` channel. +The embedding gate receives no separate timestep embedding or `depth_valid` channel. The existing validity flag still zeros $f_d$ after its MLP. Missing depth produces a zero residual. Training learns the gate through the flow loss. It does not supervise visibility or guarantee sharpening during denoising. -The optimizer separates NoRA/LoRA parameters from all other trainable layers. -The depth MLP, gate MLP, and other trainable projections share `training.learning_rate`. -NoRA/LoRA parameters use `training.optimizer.adapter_learning_rate` when specified, or the same learning rate otherwise. -The supplied configurations use `1e-4` for both groups. -Both groups use the same linear warmup. Training has no separate depth learning rate. +SS, SegviGen, and SLAT shape share one [optimization recipe](../utils/training/configs/default.json). +The [training guide](../utils/training/README.md) describes its parameter groups, 500-update warmup, and weight EMA. +Each preset references this recipe through `training.optimizer_config`. +The loader records resolved values in each run snapshot and checkpoint. +Training resumes raw weights and EMA history, while evaluation selects EMA weights when available. +Training has no separate depth learning rate. Checkpoints with the former flow/depth groups require optimizer state conversion before training resumes. This conversion does not change model weights. #### Crop borders and the original camera view -All three settings repeat DINOv3 border features without a camera-validity multiplier. +Both modes repeat DINOv3 border features without a camera-validity multiplier. Projection follows these conditions: - Inside the crop, sample the projected image feature. @@ -433,33 +548,16 @@ In global attention mode, global attention and the projection bias can still con `model.cross_attention_mode` selects cross-attention independently of `model.voxel_condition_mode`. CA means cross-attention. -Both SS and SLAT shape accept the same mode names: - -| Mode | SS attention keys | SLAT shape attention keys | -| --- | --- | --- | -| `global` | Native global DINOv3 scene tokens | Native global DINOv3 scene tokens | -| `occlusion_object` | Object descriptors filtered by directed occlusion candidates, plus a null descriptor | One descriptor for the token's assigned instance | - -The default mode is `global`. -Either CA mode can use `additive`, `depth_scalar`, or `depth_embedding` voxel conditioning. -CA selects the attention keys, while voxel conditioning controls the local image, mask, and depth terms. - -Set these fields inside `model` for object CA with a depth gate: - -```json -{ - "cross_attention_mode": "occlusion_object", - "voxel_condition_mode": "depth_embedding", - "voxel_condition_hidden_channels": 64 -} -``` +The [configuration inventory](#configuration-inventory) lists accepted modes, defaults, and their constraints. +Global CA reads native DINOv3 scene tokens. +Object CA reads descriptors selected through directed occlusion candidates, plus a null descriptor. +The [shape attention guide](../slat_multiobj_shape/README.md#select-cross-attention) describes its separate owner-based rule and default disabled CA. -The [object preset](configs/front3d_sage_object_attention_1.json) selects this combination. +The [object preset](configs/front3d_sage_object_attention_1.json) selects object CA with the depth-embedding gate. Its filename preserves the historical run identity. Each native SS transformer block contains one CA layer in either mode. Set `cross_attention_mode` explicitly for new configurations. -The loader rejects the retired `object_attention_layers` field. Checkpoints record the resolved CA mode. A CA change requires a new adapter run. Evaluation rejects an explicit mode that differs from the checkpoint. @@ -470,7 +568,7 @@ The intended method replaces global scene-token attention with masked attention It uses **one cross-attention layer per native SS transformer block**. Voxel projection and occlusion relations select the instance registers that each query can attend to. An instance register is an attention token that represents one object. -The visibility gate remains independent and can use `none`, `scalar`, or `embedding`. +Voxel conditioning remains independent and supports `additive` or `depth_embedding`. The SS decoder still generates one scene occupancy grid. ##### Replacement of global attention @@ -546,7 +644,7 @@ The block follows **SA → CA → pixel conditioning → MLP**: 1. **SA:** Apply native self-attention to the voxel states. 2. **CA:** Apply one occlusion-aware masked cross-attention layer over the eligible instance registers. -3. **Pixel conditioning:** Add projected image, mask, and depth terms according to the selected visibility mode. +3. **Pixel conditioning:** Apply the selected additive or depth-embedding equation. 4. **MLP:** Apply the native feed-forward network, a multilayer perceptron. CA and pixel conditioning use the same normalized voxel state after SA. @@ -862,13 +960,7 @@ As of 2026-10-10, the [official repository](https://github.com/cvlab-kaist/Tetri 5. Sample augmentations during training with resumable random number generator (RNG) state. Evaluate generated occupancy on observations without augmentation. -Configure the corruption under `training.depth_augmentation`: - -```json -{"noise_probability": 0.3, "noise_std_fraction": 0.015625, "pixel_dropout": 0.1} -``` - -Set the noise scale with `noise_std_fraction` as a fraction of the cube's side length. +The [configuration inventory](#configuration-inventory) collects the depth augmentation controls and their defaults. The feature cache retains these values: @@ -1020,8 +1112,9 @@ Follow the [checkpoint download guide](../HF_MODEL_CHECKPOINTS.md) for authentic The [masked-object snapshot at step 9,000](https://huggingface.co/cubec/PartProbe3D-checkpoints/blob/9b15cd5ea5d5fad506ae7998c6fe03146f120644/checkpoints/training/ss_multiobj_depth/front3d_sage_object_attention_masked_objects/step_009000.pt) uses 3D-FRONT and SAGE-10k. It retains object attention, the depth-embedding gate, and complete occupancy for objects with supplied masks. -The repository also provides two snapshots trained on combined 3D-FRONT and SAGE data. +The repository also preserves two historical snapshots trained on combined 3D-FRONT and SAGE data. Both snapshots retain the crop-border fix. +These historical snapshots require their recorded source revisions. | Gate | Saved step | Checkpoint directory under `checkpoints/training/ss_multiobj_depth/` | | --- | ---: | --- | @@ -1138,10 +1231,10 @@ The preset uses batch size 8 and one accumulation step. Its effective batch remains eight views per optimizer update, matching the previous settings of two views and four accumulation steps. A training profile on one RTX PRO 6000 Blackwell GPU used 13.2 GiB for allocated tensors and 16.1 GiB for reserved memory. These values include forward calculation, gradients, and an optimizer update with real samples from both datasets. -The trainer uses one GPU. Prepare caches on both permitted GPUs before training. +The trainer uses one GPU. Prepare caches on the configured devices before training. -For this workspace, set `CUDA_VISIBLE_DEVICES=4,6` and `CUDA_DEVICE_ORDER=PCI_BUS_ID` before each GPU command. -Use `cuda:0` for physical GPU 4 and `cuda:1` for physical GPU 6. +Select visible GPUs through `CUDA_VISIBLE_DEVICES`. +Select logical devices within that visible set through the configuration. Local training requires complete feature caches and GT occlusion relations for both sources. Use `wandb_mode="offline"` when no W&B login is available. @@ -1180,7 +1273,7 @@ ln -s /path/to/existing/ss_features /path/to/overlay/conditioning ### Combined 3D-FRONT + SAGE-10k training -The default [embedding configuration](configs/front3d_sage_depth_embedding_gate.json) trains one SS model from separate feature caches for the two datasets. +The earlier [embedding configuration](configs/front3d_sage_depth_embedding_gate.json) trains one SS model from separate feature caches for two datasets. Its `sources` list contains a `dataset` and `cache` pair for each source. The sampler selects either dataset with probability 50%. It then samples uniformly from that dataset's training views. The saved MIDI room split and SAGE layout split remain unchanged. @@ -1216,7 +1309,7 @@ Use `--config` to select the equation and run directories: ```bash python -m ss_multiobj_depth.train \ - --config ss_multiobj_depth/configs/front3d_sage_depth_residual_gate.json + --config ss_multiobj_depth/configs/front3d_sage.json python -m ss_multiobj_depth.train \ --config ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json @@ -1225,29 +1318,25 @@ python -m ss_multiobj_depth.train \ Only the configuration path changes between these commands. The configurations share feature caches and all other training settings. -| Configuration | `model.voxel_condition_mode` | Equation | -| --- | --- | --- | -| [front3d_sage_depth_residual_gate.json](configs/front3d_sage_depth_residual_gate.json) | `depth_scalar` | Gate from the signed depth residual, with a separate additive depth projection | -| [front3d_sage_depth_embedding_gate.json](configs/front3d_sage_depth_embedding_gate.json) | `depth_embedding` | Gate from the depth embedding, without a separate additive depth projection | -| [front3d_sage.json](configs/front3d_sage.json) | Absent, defaults to `additive` | Additive mask and depth projections without a gate | +The [configuration inventory](#configuration-inventory) compares these mode choices and identifies the CLI default. +The [combined preset](configs/front3d_sage.json) uses additive conditioning. +The [embedding preset](configs/front3d_sage_depth_embedding_gate.json) uses the depth-embedding gate. Each configuration explicitly defines `output` and `checkpoints`. Loading it does not change those paths. -The training command defaults to the embedding configuration. +The training command defaults to object means and learned coverage across 3D-FRONT, SAGE-10k, and FoundationPose. Explicit `front3d.json`, `sage.json`, and `front3d_sage.json` retain additive conditioning for their existing runs. -The two gate configurations use separate directories named `front3d_sage_depth_residual_gate` and `front3d_sage_depth_embedding_gate`. -They do not overwrite each other's checkpoints or the existing baseline run. -The CLI no longer accepts `--visibility-mode`. +The presets use separate output and checkpoint directories. +The CLI selects the conditioning equation through `--config`. Append `--resume` to the same command to continue its run. For an existing run, select its saved `config.json` with its original directories. New gated runs require `model.voxel_condition_mode` in JSON. -Uploaded gate checkpoints retain their recorded width fields and tensor names. Saved configurations, checkpoints, and W&B record the resolved mode and gate width. -Evaluation and resume infer missing mode metadata from legacy checkpoint tensors. -The loader rejects the retired `visibility_mode` field. -It also accepts historical `visibility_hidden_channels` fields and `.visibility.` tensor keys. +Evaluation and resume check the architecture against saved adapter tensors. +Unknown configuration fields and unsupported checkpoint formats cause errors. + An explicit mode must match the checkpoint. Switching equations requires a new run. Source changes still require `--accept-source-changes` for resume. Data and objective checks remain active. @@ -1341,19 +1430,26 @@ It concatenates their cosine and sine values and learns a shared MLP. It masks missing or nonfinite depth **after** the biased MLP. Each native projection block receives a bias-free `W_mask` addition. -The `scalar` and `none` modes also use `W_depth`. The `embedding` mode has no separate depth projection. +The `additive` mode also uses `W_depth`. The `depth_embedding` mode has no separate depth projection. The code initializes these additions to zero after it loads pretrained weights. -Training updates these additions, any visibility heads, the depth MLP, and rank-8 NoRA adapters. +Training updates these additions, the embedding gates, the depth MLP, and rank-8 LoRA adapters by default. Object attention mode also trains the depth queries, geometric biases, and null descriptors. Other original flow parameters, DINOv3, and the SS codec remain frozen. The native flow-matching objective uses `1000*t` timesteps and one denoising trajectory per scene. Classifier-free guidance (CFG) removes RGB, mask, and depth features together. +The [shared CFG profile](../utils/training/configs/cfg.json) supplies `training.cfg_dropout=0.1`, matching GenRecon and WorldSculpt's configured rate. This removal matches the all-zero negative condition for sampling. The implementation does not include the proposed 2×2 ablations. +The same profile sets inference strength `7.5`, guidance rescaling `0.7`, and the guidance interval `[0.6, 1.0]`. + Training uses one device, minibatches, and gradient accumulation. -The default effective batch contains eight views (`batch_size=2`, `accumulation=4`). +The loss uses native Pixal3D averaging over every dense latent element within each microbatch. +This mean includes all samples, channels, and grid cells without occupancy filtering. +Gradient accumulation averages microbatch losses. + +The default effective batch contains sixteen views (`batch_size=16`, `accumulation=1`). Sampling is deterministic by optimizer step. Resume restores optimizer and Torch RNG state. It rejects changes to the model, feature manifest, or training objective. diff --git a/ss_multiobj_depth/conditioning.py b/ss_multiobj_depth/conditioning.py index 1bf89c1..36871a8 100644 --- a/ss_multiobj_depth/conditioning.py +++ b/ss_multiobj_depth/conditioning.py @@ -109,6 +109,10 @@ class SSVoxelConditioner(VoxelConditioner): """Extend shared voxel carriers with optional SS object-token context.""" def __init__(self, image_channels=1024, depth_channels=128, *, voxel_condition_mode='additive', mask_channels=None, object_attention=False, object_aggregation=False): + if voxel_condition_mode not in ('additive', 'depth_embedding'): + raise ValueError('SS voxel_condition_mode must be additive or depth_embedding') + if object_aggregation and image_channels != 1024: + raise ValueError('SS object means require 1024-channel DINO local features') super().__init__(image_channels, depth_channels, voxel_condition_mode=voxel_condition_mode, mask_channels=mask_channels, object_aggregation=object_aggregation, packed_object_pairs=object_aggregation) diff --git a/ss_multiobj_depth/config.py b/ss_multiobj_depth/config.py index f5e50c5..612cbf2 100644 --- a/ss_multiobj_depth/config.py +++ b/ss_multiobj_depth/config.py @@ -7,13 +7,26 @@ import subprocess from utils.hashing import sha256 from utils.training.depth_augmentation import validate_settings -from models.voxel_condition import canonical_voxel_settings, voxel_condition_settings, voxel_condition_width -from models.cross_attention import canonical_attention_settings, cross_attention_settings +from utils.training.settings import resolve_training_settings, resolve_adapter_settings +from utils.training.cfg import resolve_cfg_settings +from utils.training.ema import validate_ema_decay +from models.voxel_condition import voxel_condition_settings, voxel_adapter_settings +from models.cross_attention import cross_attention_settings from .runtime import ROOT, path_under, configure_runtime DEFAULT_CONFIG = Path(__file__).parent / 'configs/front3d.json' -DEFAULT_TRAINING_CONFIG = DEFAULT_CONFIG.with_name('front3d_sage_depth_embedding_gate.json') +DEFAULT_TRAINING_CONFIG = DEFAULT_CONFIG.with_name('front3d_sage_foundationpose_object_mean_image_coverage_gate.json') TARGET_SCOPE = 'masked_objects_complete_occupancy' +CONFIG_KEYS = {'schema', 'cfg_config', 'cfg_profile', 'dataset', 'cache', 'sources', 'output', + 'checkpoints', 'device', 'seed', 'depth_source', 'moge_config', 'models', 'model', + 'training', 'sampling', 'inference_weights', 'occlusion_model'} +MODEL_KEYS = {'depth_channels', 'rank', 'alpha', 'mask_channels', 'voxel_condition_mode', + 'voxel_condition_hidden_channels', 'cross_attention_mode', 'voxel_aggregation', + 'voxel_image_features', 'voxel_coverage_weighting', 'image_projection_adaptation', 'adapter_method'} +TRAINING_KEYS = {'optimizer_config', 'optimizer_profile', 'adapter_method', 'learning_rate', 'weight_decay', + 'warmup', 'optimizer', 'ema_decay', 'cfg_dropout', 'steps', 'batch_size', 'accumulation', + 'workers', 'depth_augmentation', 'save_every', 'eval_every', 'eval_limit', + 'wandb_mode', 'wandb_project', 'wandb_entity', 'conditioning_source'} def online_conditioning(config): @@ -28,15 +41,45 @@ def online_conditioning(config): def model_settings(settings, adapters=None): - """Resolve the architecture, using saved tensors for legacy gated checkpoints.""" - return cross_attention_settings(voxel_condition_settings(settings, adapters), adapters) + """Resolve supported SS options and check the saved architecture.""" + unknown = set(settings) - MODEL_KEYS + if unknown: + raise ValueError(f'Unknown SS model settings: {sorted(unknown)}') + if settings.get('voxel_image_features', 'dino') != 'dino': + raise ValueError('SS voxel_image_features must be dino') + if adapters is not None and any('.visibility.' in key for key in adapters['flow']): + raise ValueError('SS checkpoint contains unsupported adapter names') + settings = voxel_condition_settings(settings, adapters) + settings = cross_attention_settings(settings, adapters) + settings = voxel_adapter_settings(settings, adapters) + if settings['voxel_condition_mode'] not in ('additive', 'depth_embedding'): + raise ValueError('SS voxel_condition_mode must be additive or depth_embedding') + if settings['image_projection_adaptation'] not in ('full', 'lora', 'nora'): + raise ValueError('SS image_projection_adaptation must be full, lora or nora') + from models.object_region_pool import enabled, coverage_gate + coverage_gate(settings) + if enabled(settings): + settings.setdefault('voxel_image_features', 'dino') + if settings['voxel_condition_mode'] != 'depth_embedding' or settings['cross_attention_mode'] != 'global': + raise ValueError('Object means require depth_embedding and global cross-attention') + if adapters is not None and any( + value.shape[-1] != 1024 for key, value in adapters['flow'].items() + if key.endswith(('.proj_linear.weight', '.proj_linear.lora_A'))): + raise ValueError('SS checkpoint local image projections must use DINO features') + return settings def checkpoint_model_config(config, saved): """Use the checkpoint mode unless the caller explicitly selects a mode.""" recorded = model_settings(saved['config']['model'], saved['adapters']) - requested = canonical_attention_settings(canonical_voxel_settings(config['model'])) - for key in ('cross_attention_mode', 'voxel_condition_mode', 'voxel_condition_hidden_channels'): + requested = dict(config['model']) + unknown = set(requested) - MODEL_KEYS + if unknown: + raise ValueError(f'Unknown SS model settings: {sorted(unknown)}') + for key in ('cross_attention_mode', 'voxel_condition_mode', 'voxel_condition_hidden_channels', + 'voxel_image_features', 'adapter_method', 'image_projection_adaptation'): + if key not in recorded: + continue if key in requested and requested[key] != recorded[key]: raise ValueError('Evaluation/resume model differs from training checkpoint') requested.setdefault(key, recorded[key]) @@ -80,6 +123,14 @@ def load_config(path=DEFAULT_CONFIG): config = json.loads(Path(path).read_text()) if config.get('schema') != 'ss-multiobj-depth-v1': raise ValueError('Expected ss-multiobj-depth-v1 JSON settings') + for label, settings, allowed in (('configuration', config, CONFIG_KEYS), + ('training', config['training'], TRAINING_KEYS)): + unknown = set(settings) - allowed + if unknown: + raise ValueError(f'Unknown SS {label} settings: {sorted(unknown)}') + config['training'] = resolve_training_settings(config['training']) + config = resolve_cfg_settings(config, 'ss') + config['model'] = resolve_adapter_settings(config['model'], config['training']) for source in source_configs(config): path_under(source['cache'], 'outputs') for key, folder in [('output', 'outputs'), ('checkpoints', 'checkpoints')]: @@ -88,19 +139,8 @@ def load_config(path=DEFAULT_CONFIG): for key in ('dino', 'encoder', 'decoder', 'paired_decoder', 'flow'): path_under(config['models'][key], 'checkpoints') require_gt_depth(config) - if 'extent_spec' in config or 'cube_size' in config: - raise ValueError('Choose extents in stage-two preprocessing; training reads the saved dataset grid') - config['model'] = canonical_attention_settings(canonical_voxel_settings(config['model'])) + config['model'] = model_settings(config['model']) train, model = config['training'], config['model'] - from models.object_region_pool import enabled, image_channels, coverage_gate - from models.voxel_condition import image_projection_adaptation - image_projection_adaptation(model) - coverage_gate(model) - if enabled(model): - image_channels(model) - if (model_settings(model)['voxel_condition_mode'] != 'depth_embedding' - or model_settings(model)['cross_attention_mode'] != 'global'): - raise ValueError('Object means require depth_embedding and global cross-attention') online_conditioning(config) # Older explicit run configs keep their unaugmented objective. New runs # select the rates and cube noise scale in configs/front3d.json. @@ -117,21 +157,16 @@ def load_config(path=DEFAULT_CONFIG): raise ValueError('Scheduled monitoring needs a positive eval_limit') from utils.training.optim import validate_optimizer validate_optimizer(train) + if train.get('ema_decay') is not None: + validate_ema_decay(train['ema_decay']) + if config.get('inference_weights', 'auto') not in ('auto', 'raw', 'ema'): + raise ValueError('SS inference_weights must be auto, raw or ema') if not 0 <= train['cfg_dropout'] < 1: raise ValueError('cfg_dropout must lie in [0,1)') - if 'routing_loss_weight' in train: - raise ValueError('SS training uses only flow-matching MSE. Remove training.routing_loss_weight.') if (type(model['rank']) is not int or model['rank'] < 0 or type(model['depth_channels']) is not int or model['depth_channels'] < 1 or not math.isfinite(model['alpha']) or model['alpha'] <= 0): raise ValueError('Invalid adapter dimensions/scaling') - if 'voxel_condition_mode' in model: - voxel_condition_width(model['voxel_condition_mode'], model.get('voxel_condition_hidden_channels')) - elif 'voxel_condition_hidden_channels' in model: - # Old branch configs omit the mode. Checkpoints identify it at load time. - width = model['voxel_condition_hidden_channels'] - if type(width) is not int or width < 0: - raise ValueError('voxel_condition_hidden_channels must be a nonnegative integer') if train['wandb_mode'] not in ('disabled', 'offline', 'online'): raise ValueError('Invalid W&B mode') sampling = config['sampling'] @@ -193,7 +228,7 @@ def training_protocol(config, dataset): for key in ('steps', 'save_every', 'eval_every', 'eval_limit', 'workers', 'wandb_mode', 'wandb_project', 'wandb_entity'): value['training'].pop(key, None) - for key in ('device', 'output', 'checkpoints', 'sampling'): + for key in ('device', 'output', 'checkpoints', 'sampling', 'inference_weights', 'cfg_profile'): value.pop(key, None) if 'sources' in config: value['manifest_sha256'] = {source['cache']: sha256(data.root / 'manifest.json') @@ -206,7 +241,7 @@ def training_protocol(config, dataset): 'ss_multiobj_depth/config.py', 'ss_multiobj_depth/dataloader.py', 'utils/training/lora.py', 'models/mask_latent.py', 'models/pixal3d.py', 'models/conditioning.py', 'models/ss_conditioning.py', 'models/voxel_condition.py', 'models/cross_attention.py', 'extent/grid.py', - 'utils/training/optim.py'] + 'utils/training/optim.py', 'utils/training/settings.py', 'utils/training/ema.py', 'utils/training/cfg.py'] from models.object_region_pool import enabled if enabled(config['model']): sources.extend(['models/object_region_pool.py', 'utils/region_fields.py', diff --git a/ss_multiobj_depth/configs/foundationpose.json b/ss_multiobj_depth/configs/foundationpose.json index 4e95cb5..1077bcf 100644 --- a/ss_multiobj_depth/configs/foundationpose.json +++ b/ss_multiobj_depth/configs/foundationpose.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "dataset": "datasets/foundationpose/extent/point_cloud", "cache": "outputs/ss_multiobj_depth/foundationpose/features", "output": "outputs/ss_multiobj_depth/foundationpose/train", @@ -26,13 +27,11 @@ "voxel_condition_hidden_channels": 64 }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -47,12 +46,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/configs/front3d.json b/ss_multiobj_depth/configs/front3d.json index bd7c4e7..9c6243a 100644 --- a/ss_multiobj_depth/configs/front3d.json +++ b/ss_multiobj_depth/configs/front3d.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "dataset": "datasets/3dfront/extent/point_cloud", "cache": "outputs/ss_multiobj_depth/front3d/features", "output": "outputs/ss_multiobj_depth/front3d/train", @@ -18,15 +19,19 @@ "flow": "checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16" }, "model": { - "cross_attention_mode": "global","depth_channels": 128, "rank": 8, "alpha": 8.0}, + "cross_attention_mode": "global", + "depth_channels": 128, + "rank": 8, + "alpha": 8.0, + "adapter_method": "shared", + "image_projection_adaptation": "shared" + }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -41,9 +46,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [0.6, 1.0], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/configs/front3d_sage.json b/ss_multiobj_depth/configs/front3d_sage.json index 069dcfa..c5f112a 100644 --- a/ss_multiobj_depth/configs/front3d_sage.json +++ b/ss_multiobj_depth/configs/front3d_sage.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "sources": [ { "dataset": "datasets/3dfront/extent/point_cloud", @@ -32,13 +33,11 @@ "alpha": 8.0 }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -53,12 +52,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json b/ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json index 8123712..b155796 100644 --- a/ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json +++ b/ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "sources": [ { "dataset": "datasets/3dfront/extent/point_cloud", @@ -31,16 +32,16 @@ "rank": 8, "alpha": 8.0, "voxel_condition_mode": "depth_embedding", - "voxel_condition_hidden_channels": 64 + "voxel_condition_hidden_channels": 64, + "adapter_method": "shared", + "image_projection_adaptation": "shared" }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -55,12 +56,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json new file mode 100644 index 0000000..cd1b069 --- /dev/null +++ b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json @@ -0,0 +1,72 @@ +{ + "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", + "sources": [ + { + "dataset": "datasets/3dfront/extent/point_cloud", + "cache": "outputs/ss_multiobj_depth/front3d/masked_objects/targets" + }, + { + "dataset": "datasets/sage/extent/point_cloud", + "cache": "outputs/ss_multiobj_depth/sage/masked_objects/targets" + }, + { + "dataset": "datasets/foundationpose/extent/point_cloud", + "cache": "outputs/ss_multiobj_depth/foundationpose/masked_objects/targets" + } + ], + "output": "outputs/ss_multiobj_depth/front3d_sage_foundationpose_object_mean_image_coverage_gate/train", + "checkpoints": "checkpoints/training/ss_multiobj_depth/front3d_sage_foundationpose_object_mean_image_coverage_gate", + "device": "cuda:0", + "seed": 0, + "depth_source": "gt", + "moge_config": "ss_multiobj_depth/configs/moge3.json", + "models": { + "upstream": "third_party/Pixal3D", + "upstream_revision": "cdbb2bbffbf4e6f298b5f2af3d1d76a8d823d2af", + "dino": "checkpoints/DINOv3", + "encoder": "checkpoints/TRELLIS/ckpts/ss_enc_conv3d_16l8_fp16", + "paired_decoder": "checkpoints/TRELLIS/ckpts/ss_dec_conv3d_16l8_fp16", + "decoder": "checkpoints/Pixal3D/ckpts/ss_dec_conv3d_16l8_fp16", + "flow": "checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16", + "naf": "checkpoints/NAF/naf_release.pth", + "naf_upstream": "third_party/NAF", + "naf_revision": "37f2dfc180f2de53d98bd601109c0da0dd6b0f43" + }, + "model": { + "depth_channels": 128, + "rank": 8, + "alpha": 8.0, + "cross_attention_mode": "global", + "voxel_condition_mode": "depth_embedding", + "voxel_condition_hidden_channels": 64, + "voxel_aggregation": "object_mean", + "voxel_image_features": "dino", + "image_projection_adaptation": "shared", + "voxel_coverage_weighting": "learned_gate", + "adapter_method": "shared" + }, + "training": { + "optimizer_config": "utils/training/configs/default.json", + "steps": 20000, + "batch_size": 16, + "accumulation": 1, + "workers": 4, + "depth_augmentation": { + "noise_probability": 0.3, + "noise_std_fraction": 0.015625, + "pixel_dropout": 0.1 + }, + "save_every": 500, + "eval_every": 500, + "eval_limit": 8, + "wandb_mode": "online", + "wandb_project": "PartProbe3D", + "wandb_entity": null, + "conditioning_source": "online" + }, + "sampling": { + "steps": 12, + "rescale_t": 5 + } +} diff --git a/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json new file mode 100644 index 0000000..e5c87fa --- /dev/null +++ b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json @@ -0,0 +1,72 @@ +{ + "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", + "sources": [ + { + "dataset": "datasets/3dfront/extent/point_cloud", + "cache": "outputs/ss_multiobj_depth/front3d/masked_objects/targets" + }, + { + "dataset": "datasets/sage/extent/point_cloud", + "cache": "outputs/ss_multiobj_depth/sage/masked_objects/targets" + }, + { + "dataset": "datasets/foundationpose/extent/point_cloud", + "cache": "outputs/ss_multiobj_depth/foundationpose/masked_objects/targets" + } + ], + "output": "outputs/ss_multiobj_depth/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6_20261021/train", + "checkpoints": "checkpoints/training/ss_multiobj_depth/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6_20261021", + "device": "cuda:1", + "seed": 0, + "depth_source": "gt", + "moge_config": "ss_multiobj_depth/configs/moge3.json", + "models": { + "upstream": "third_party/Pixal3D", + "upstream_revision": "cdbb2bbffbf4e6f298b5f2af3d1d76a8d823d2af", + "dino": "checkpoints/DINOv3", + "encoder": "checkpoints/TRELLIS/ckpts/ss_enc_conv3d_16l8_fp16", + "paired_decoder": "checkpoints/TRELLIS/ckpts/ss_dec_conv3d_16l8_fp16", + "decoder": "checkpoints/Pixal3D/ckpts/ss_dec_conv3d_16l8_fp16", + "flow": "checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16", + "naf": "checkpoints/NAF/naf_release.pth", + "naf_upstream": "third_party/NAF", + "naf_revision": "37f2dfc180f2de53d98bd601109c0da0dd6b0f43" + }, + "model": { + "depth_channels": 128, + "rank": 8, + "alpha": 8.0, + "cross_attention_mode": "global", + "voxel_condition_mode": "depth_embedding", + "voxel_condition_hidden_channels": 64, + "voxel_aggregation": "object_mean", + "voxel_image_features": "dino", + "image_projection_adaptation": "shared", + "voxel_coverage_weighting": "learned_gate", + "adapter_method": "shared" + }, + "training": { + "optimizer_config": "utils/training/configs/default.json", + "steps": 20000, + "batch_size": 16, + "accumulation": 1, + "workers": 4, + "depth_augmentation": { + "noise_probability": 0.3, + "noise_std_fraction": 0.015625, + "pixel_dropout": 0.1 + }, + "save_every": 500, + "eval_every": 500, + "eval_limit": 8, + "wandb_mode": "online", + "wandb_project": "PartProbe3D", + "wandb_entity": null, + "conditioning_source": "online" + }, + "sampling": { + "steps": 12, + "rescale_t": 5 + } +} diff --git a/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json index 063e12f..d6f6501 100644 --- a/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json +++ b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "sources": [ { "dataset": "datasets/3dfront/extent/point_cloud", @@ -40,18 +41,17 @@ "voxel_condition_mode": "depth_embedding", "voxel_condition_hidden_channels": 64, "voxel_aggregation": "object_mean", - "voxel_image_features": "dino_naf", + "voxel_image_features": "dino", "image_projection_adaptation": "nora", - "voxel_coverage_weighting": "learned_gate" + "voxel_coverage_weighting": "learned_gate", + "adapter_method": "nora" }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -67,12 +67,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/configs/front3d_sage_object_attention_1.json b/ss_multiobj_depth/configs/front3d_sage_object_attention_1.json index cca4958..49200b3 100644 --- a/ss_multiobj_depth/configs/front3d_sage_object_attention_1.json +++ b/ss_multiobj_depth/configs/front3d_sage_object_attention_1.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "sources": [ { "dataset": "datasets/3dfront/extent/point_cloud", @@ -34,13 +35,11 @@ "voxel_condition_hidden_channels": 64 }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -55,12 +54,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 }, "occlusion_model": { diff --git a/ss_multiobj_depth/configs/front3d_sage_object_attention_masked_objects.json b/ss_multiobj_depth/configs/front3d_sage_object_attention_masked_objects.json index 73a4f8b..c55639e 100644 --- a/ss_multiobj_depth/configs/front3d_sage_object_attention_masked_objects.json +++ b/ss_multiobj_depth/configs/front3d_sage_object_attention_masked_objects.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "sources": [ { "dataset": "datasets/3dfront/extent/point_cloud", @@ -34,13 +35,11 @@ "voxel_condition_hidden_channels": 64 }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 8, "accumulation": 1, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -55,12 +54,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 }, "occlusion_model": { diff --git a/ss_multiobj_depth/configs/front3d_sage_object_footprint_mean.json b/ss_multiobj_depth/configs/front3d_sage_object_footprint_mean.json index 171c5cb..ac676aa 100644 --- a/ss_multiobj_depth/configs/front3d_sage_object_footprint_mean.json +++ b/ss_multiobj_depth/configs/front3d_sage_object_footprint_mean.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "sources": [ { "dataset": "datasets/3dfront/extent/point_cloud", @@ -36,16 +37,14 @@ "voxel_condition_mode": "depth_embedding", "voxel_condition_hidden_channels": 64, "voxel_aggregation": "object_mean", - "voxel_image_features": "dino_naf" + "voxel_image_features": "dino" }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -60,12 +59,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/configs/front3d_sage_object_mean_image_coverage_gate.json b/ss_multiobj_depth/configs/front3d_sage_object_mean_image_coverage_gate.json new file mode 100644 index 0000000..8b5746d --- /dev/null +++ b/ss_multiobj_depth/configs/front3d_sage_object_mean_image_coverage_gate.json @@ -0,0 +1,68 @@ +{ + "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", + "sources": [ + { + "dataset": "datasets/3dfront/extent/point_cloud", + "cache": "outputs/ss_multiobj_depth/front3d/masked_objects/features" + }, + { + "dataset": "datasets/sage/extent/point_cloud", + "cache": "outputs/ss_multiobj_depth/sage/masked_objects/features" + } + ], + "output": "outputs/ss_multiobj_depth/object_mean_image_coverage_gate/train", + "checkpoints": "checkpoints/training/ss_multiobj_depth/object_mean_image_coverage_gate", + "device": "cuda:0", + "seed": 0, + "depth_source": "gt", + "moge_config": "ss_multiobj_depth/configs/moge3.json", + "models": { + "upstream": "third_party/Pixal3D", + "upstream_revision": "cdbb2bbffbf4e6f298b5f2af3d1d76a8d823d2af", + "dino": "checkpoints/DINOv3", + "encoder": "checkpoints/TRELLIS/ckpts/ss_enc_conv3d_16l8_fp16", + "paired_decoder": "checkpoints/TRELLIS/ckpts/ss_dec_conv3d_16l8_fp16", + "decoder": "checkpoints/Pixal3D/ckpts/ss_dec_conv3d_16l8_fp16", + "flow": "checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16", + "naf": "checkpoints/NAF/naf_release.pth", + "naf_upstream": "third_party/NAF", + "naf_revision": "37f2dfc180f2de53d98bd601109c0da0dd6b0f43" + }, + "model": { + "depth_channels": 128, + "rank": 8, + "alpha": 8.0, + "cross_attention_mode": "global", + "voxel_condition_mode": "depth_embedding", + "voxel_condition_hidden_channels": 64, + "voxel_aggregation": "object_mean", + "voxel_image_features": "dino", + "image_projection_adaptation": "shared", + "voxel_coverage_weighting": "learned_gate", + "adapter_method": "shared" + }, + "training": { + "optimizer_config": "utils/training/configs/default.json", + "steps": 20000, + "batch_size": 2, + "accumulation": 4, + "workers": 4, + "depth_augmentation": { + "noise_probability": 0.3, + "noise_std_fraction": 0.015625, + "pixel_dropout": 0.1 + }, + "save_every": 500, + "eval_every": 500, + "eval_limit": 8, + "wandb_mode": "online", + "wandb_project": "PartProbe3D", + "wandb_entity": null, + "conditioning_source": "online" + }, + "sampling": { + "steps": 12, + "rescale_t": 5 + } +} diff --git a/ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json b/ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json index 9c779b3..2fbac91 100644 --- a/ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json +++ b/ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "sources": [ { "dataset": "datasets/3dfront/extent/point_cloud", @@ -36,18 +37,17 @@ "voxel_condition_mode": "depth_embedding", "voxel_condition_hidden_channels": 64, "voxel_aggregation": "object_mean", - "voxel_image_features": "dino_naf", + "voxel_image_features": "dino", "image_projection_adaptation": "nora", - "voxel_coverage_weighting": "learned_gate" + "voxel_coverage_weighting": "learned_gate", + "adapter_method": "nora" }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -63,12 +63,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/configs/sage.json b/ss_multiobj_depth/configs/sage.json index ae75588..4e299e3 100644 --- a/ss_multiobj_depth/configs/sage.json +++ b/ss_multiobj_depth/configs/sage.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "dataset": "datasets/sage/extent/point_cloud", "cache": "outputs/ss_multiobj_depth/sage/features", "output": "outputs/ss_multiobj_depth/sage/train", @@ -24,13 +25,11 @@ "alpha": 8.0 }, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -45,12 +44,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [ - 0.6, - 1.0 - ], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/configs/ycbv.json b/ss_multiobj_depth/configs/ycbv.json index 6b60aa2..ae48d63 100644 --- a/ss_multiobj_depth/configs/ycbv.json +++ b/ss_multiobj_depth/configs/ycbv.json @@ -1,5 +1,6 @@ { "schema": "ss-multiobj-depth-v1", + "cfg_config": "utils/training/configs/cfg.json", "dataset": "datasets/ycbv/extent/point_cloud", "cache": "outputs/ss_multiobj_depth/ycbv/features", "output": "outputs/ss_multiobj_depth/ycbv/train", @@ -20,13 +21,11 @@ "model": { "cross_attention_mode": "global","depth_channels": 128, "rank": 8, "alpha": 8.0}, "training": { + "optimizer_config": "utils/training/configs/default.json", "steps": 20000, "batch_size": 2, "accumulation": 4, "workers": 4, - "learning_rate": 0.0001, - "warmup": 250, - "cfg_dropout": 0.1, "depth_augmentation": { "noise_probability": 0.3, "noise_std_fraction": 0.015625, @@ -41,9 +40,6 @@ }, "sampling": { "steps": 12, - "cfg_strength": 7.5, - "cfg_rescale": 0.7, - "cfg_interval": [0.6, 1.0], "rescale_t": 5 } } diff --git a/ss_multiobj_depth/inference.py b/ss_multiobj_depth/inference.py index 8246426..1ab412e 100644 --- a/ss_multiobj_depth/inference.py +++ b/ss_multiobj_depth/inference.py @@ -100,7 +100,9 @@ class SSInference: if saved['provenance'] != provenance: raise ValueError('Evaluation model/weights differ from training checkpoint') flow, conditioner = make_model(config) - restore_checkpoint(self.checkpoint, flow, conditioner) + restored = restore_checkpoint(self.checkpoint, flow, conditioner, + weights=config.get('inference_weights', 'auto')) + saved['checkpoint_weights'] = restored['checkpoint_weights'] flow.eval(); conditioner.eval() from pixal3d.pipelines.samplers import FlowEulerGuidanceIntervalSampler self._ss = {'flow': flow, 'conditioner': conditioner, diff --git a/ss_multiobj_depth/model.py b/ss_multiobj_depth/model.py index b45053d..453b85e 100644 --- a/ss_multiobj_depth/model.py +++ b/ss_multiobj_depth/model.py @@ -6,9 +6,18 @@ from .object_attention import OcclusionObjectAttention def install_adapters(flow, *, depth_channels=128, rank=8, alpha=8., voxel_condition_mode='additive', voxel_condition_hidden_channels=None, mask_channels=None, - cross_attention_mode='global', voxel_aggregation='point', voxel_image_features='dino_naf', - voxel_coverage_weighting='area', image_projection_adaptation='full'): - from models.object_region_pool import enabled, image_channels, coverage_gate + cross_attention_mode='global', voxel_aggregation='point', voxel_image_features='dino', + voxel_coverage_weighting='area', image_projection_adaptation=None, adapter_method='lora'): + from models.object_region_pool import enabled, coverage_gate + from .config import model_settings + settings = dict(depth_channels=depth_channels, rank=rank, alpha=alpha, adapter_method=adapter_method, + voxel_condition_mode=voxel_condition_mode, + voxel_condition_hidden_channels=voxel_condition_hidden_channels, + cross_attention_mode=cross_attention_mode, voxel_aggregation=voxel_aggregation, + voxel_image_features=voxel_image_features, voxel_coverage_weighting=voxel_coverage_weighting) + if image_projection_adaptation is not None: + settings['image_projection_adaptation'] = image_projection_adaptation + image_projection_adaptation = model_settings(settings)['image_projection_adaptation'] object_regions = enabled({'voxel_aggregation': voxel_aggregation}) coverage = coverage_gate({'voxel_aggregation': voxel_aggregation, 'voxel_coverage_weighting': voxel_coverage_weighting}) @@ -21,8 +30,9 @@ def install_adapters(flow, *, depth_channels=128, rank=8, alpha=8., install_voxel_adapters(flow, depth_channels=depth_channels, rank=rank, alpha=alpha, voxel_condition_mode=voxel_condition_mode, voxel_condition_hidden_channels=voxel_condition_hidden_channels, mask_channels=mask_channels, object_context=objects, object_aggregation=object_regions, - region_image_channels=image_channels({'voxel_image_features': voxel_image_features}), - coverage_conditioned=coverage, image_projection_adaptation=image_projection_adaptation) + region_image_channels=1024, + coverage_conditioned=coverage, image_projection_adaptation=image_projection_adaptation, + adapter_method=adapter_method) if objects: for block in flow.blocks: projection = block.cross_attn.base diff --git a/ss_multiobj_depth/observations.py b/ss_multiobj_depth/observations.py index 7cc109d..7e938b2 100644 --- a/ss_multiobj_depth/observations.py +++ b/ss_multiobj_depth/observations.py @@ -25,9 +25,11 @@ class ObservationEncoder: def __init__(self, config, *, use_moge=False): configure_runtime() self.device = config['device'] + from .config import model_settings from models.object_region_pool import enabled, image_channels - self.object_aggregation = enabled(config['model']) - self.local_channels = image_channels(config['model']) + settings = model_settings(config['model']) + self.object_aggregation = enabled(settings) + self.local_channels = image_channels(settings) self.object_attention = cross_attention_settings(config['model'])['cross_attention_mode'] == 'occlusion_object' self.dino = load_dino(path_under(config['models']['dino'], 'checkpoints'), self.device) self.naf = None diff --git a/ss_multiobj_depth/tests/test_conditioning_training.py b/ss_multiobj_depth/tests/test_conditioning_training.py index 8e76706..1b4e01c 100644 --- a/ss_multiobj_depth/tests/test_conditioning_training.py +++ b/ss_multiobj_depth/tests/test_conditioning_training.py @@ -15,6 +15,7 @@ from models.voxel_condition import negative_condition from models.voxel_condition import VoxelConditionProjection, load_adapter_state from ss_multiobj_depth.model import install_adapters from ss_multiobj_depth.train import flow_loss, UpdateSampler, save_checkpoint, restore_checkpoint +from utils.training.lora import LoRALinear def entry(channels=4, resolution=2, latent_channels=2): @@ -37,6 +38,18 @@ def compact_entry(channels=4, resolution=2): return {**{k: v for k, v in dense.items() if k not in ('image_proj', 'mask_features')}, **carriers} +def test_ss_loss_matches_native_dense_mse_and_gradients(monkeypatch): + clean = torch.arange(32, dtype=torch.float32).reshape(2, 2, 2, 2, 2) / 10 + prediction = torch.zeros_like(clean, requires_grad=True) + entries = [{'clean': value} for value in clean] + monkeypatch.setattr(torch, 'randn_like', torch.zeros_like) + loss = flow_loss(lambda *args: prediction, lambda *args, **kwargs: {}, entries, cfg_dropout=0) + expected = torch.nn.functional.mse_loss(prediction, -clean) + torch.testing.assert_close(loss, expected) + torch.testing.assert_close(torch.autograd.grad(loss, prediction, retain_graph=True)[0], + torch.autograd.grad(expected, prediction)[0]) + + def test_depth_projection_sign_validity_and_object_features(): cube = Cube(np.array([0., 0., 1.5]), 3.) intrinsics = np.array([[1., 0, 2], [0, 1., 2], [0, 0, 1.]]) @@ -126,7 +139,7 @@ def native_flow(): return flow -@pytest.mark.parametrize('mode', ['additive', 'depth_scalar', 'depth_embedding']) +@pytest.mark.parametrize('mode', ['additive', 'depth_embedding']) def test_native_flow_backward_and_checkpoint_resume(tmp_path, monkeypatch, mode): torch.manual_seed(8) flow = native_flow() @@ -136,7 +149,8 @@ def test_native_flow_backward_and_checkpoint_resume(tmp_path, monkeypatch, mode) image = block.cross_attn.base.proj_linear torch.testing.assert_close(image.weight, original.cross_attn.proj_linear.weight, rtol=0, atol=0) torch.testing.assert_close(image.bias, original.cross_attn.proj_linear.bias, rtol=0, atol=0) - assert image.weight.requires_grad and image.bias.requires_grad + assert type(image) is LoRALinear + assert not image.weight.requires_grad and image.bias.requires_grad conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode=mode) entries = [entry(), entry()] condition = conditioner(entries) @@ -164,8 +178,9 @@ def test_native_flow_backward_and_checkpoint_resume(tmp_path, monkeypatch, mode) assert conditioner.depth_mlp[0].weight.grad.abs().sum() > 0 for block, original in zip(flow.blocks, native.blocks): image = block.cross_attn.base.proj_linear - assert image.weight.grad.abs().sum() > 0 and image.bias.grad.abs().sum() > 0 - assert not torch.equal(image.weight, original.cross_attn.proj_linear.weight) + assert image.lora_A.grad.abs().sum() > 0 and image.lora_B.grad.abs().sum() > 0 + assert image.bias.grad.abs().sum() > 0 + torch.testing.assert_close(image.weight, original.cross_attn.proj_linear.weight, rtol=0, atol=0) assert not torch.equal(image.bias, original.cross_attn.proj_linear.bias) assert all(p.grad is None for p in flow.parameters() if not p.requires_grad) # Use the real serializer with a temporary top-level checkpoint owner. @@ -213,7 +228,7 @@ import evaluation.inference.ss_multiobj_depth @pytest.mark.parametrize('dataset', ['3D-FRONT', 'SAGE-10k', 'combined']) -@pytest.mark.parametrize('mode', ['additive', 'depth_scalar', 'depth_embedding']) +@pytest.mark.parametrize('mode', ['additive', 'depth_embedding']) def test_full_training_run_matches_resumed_training(tmp_path, monkeypatch, dataset, mode): """Exact depth corruption/optimizer resume despite worker prefetch changes.""" import json @@ -223,13 +238,15 @@ def test_full_training_run_matches_resumed_training(tmp_path, monkeypatch, datas from ss_multiobj_depth.dataloader import FEATURE_SCHEMA from utils.hashing import sha256 config = load_config() - config['model'].update(depth_channels=6, rank=2, alpha=2, voxel_condition_mode=mode) + config['model'].update(depth_channels=6, rank=2, alpha=2, voxel_condition_mode=mode, + voxel_condition_hidden_channels=0 if mode == 'additive' else 64) config.update(device='cpu', cache='outputs/features', output='outputs/continuous', checkpoints='checkpoints/continuous') if dataset == 'SAGE-10k': config.update(dataset='datasets/sage/extent/point_cloud') config['training'].update(steps=4, batch_size=2, accumulation=2, workers=2, warmup=2, eval_every=0, save_every=2, wandb_mode='disabled') + config['training']['optimizer']['warmup_steps'] = 2 config['training']['depth_augmentation'] = { 'noise_probability': .7, 'noise_std_fraction': 1 / 64, 'pixel_dropout': .3} cache = tmp_path / config['cache'] @@ -289,6 +306,9 @@ def test_full_training_run_matches_resumed_training(tmp_path, monkeypatch, datas runner.train(config, resume=True) resumed = torch.load(tmp_path / 'checkpoints/resumed/last.pt', weights_only=True) assert resumed['step'] == continuous['step'] == 4 + assert resumed['ema']['num_updates'] == continuous['ema']['num_updates'] == 4 + for name, value in continuous['ema']['parameters'].items(): + torch.testing.assert_close(value, resumed['ema']['parameters'][name], rtol=0, atol=0) assert continuous['protocol']['training']['depth_augmentation'] == config['training']['depth_augmentation'] assert continuous['protocol']['target_scope'] == TARGET_SCOPE if dataset == 'combined': diff --git a/ss_multiobj_depth/tests/test_object_attention.py b/ss_multiobj_depth/tests/test_object_attention.py index 8315fa3..140ac6a 100644 --- a/ss_multiobj_depth/tests/test_object_attention.py +++ b/ss_multiobj_depth/tests/test_object_attention.py @@ -219,11 +219,11 @@ def test_option_validation_and_default_checkpoint_compatibility(tmp_path): config['training']['routing_loss_weight'] = .1 path = tmp_path / 'config.json' path.write_text(json.dumps(config)) - with pytest.raises(ValueError, match='only flow-matching MSE'): + with pytest.raises(ValueError, match='routing_loss_weight'): load_config(path) -@pytest.mark.parametrize('mode', ['additive', 'depth_scalar', 'depth_embedding']) +@pytest.mark.parametrize('mode', ['additive', 'depth_embedding']) @pytest.mark.parametrize('ca', ['global', 'occlusion_object']) def test_voxel_condition_modes_and_complete_cfg_dropout(mode, ca): flow = install_adapters(native_flow(), depth_channels=6, rank=2, alpha=2, diff --git a/ss_multiobj_depth/tests/test_object_mean_training.py b/ss_multiobj_depth/tests/test_object_mean_training.py index 3516225..a8440c6 100644 --- a/ss_multiobj_depth/tests/test_object_mean_training.py +++ b/ss_multiobj_depth/tests/test_object_mean_training.py @@ -7,7 +7,7 @@ import torch from torch import nn from models.voxel_condition import adapter_state, load_adapter_state -from ss_multiobj_depth.config import load_config, model_settings, online_conditioning +from ss_multiobj_depth.config import checkpoint_model_config, load_config, model_settings, online_conditioning from ss_multiobj_depth.conditioning import SSVoxelConditioner from ss_multiobj_depth.dataloader import FEATURE_SCHEMA, FeatureDataset, OnlineObservationDataset from ss_multiobj_depth.model import install_adapters @@ -33,16 +33,30 @@ def test_three_dataset_config_preserves_conditioning_and_balances_sources(): torch.testing.assert_close(torch.stack(masses), torch.ones(3, dtype=torch.float64)) -def test_reference_conditioning_matches_without_instance_codes(): +def test_ss_defaults_use_dino_local_features_with_shared_gates_without_instance_codes(): config = load_config(CONFIG) reference = json.loads(Path('slat_segvigen/configs/object_mean_image_nora_coverage_gate.json').read_text()) - for key in ('voxel_aggregation', 'voxel_image_features', 'voxel_coverage_weighting', 'image_projection_adaptation'): + for key in ('voxel_aggregation', 'voxel_coverage_weighting', 'image_projection_adaptation'): assert config['model'][key] == reference['model'][key] + assert config['model']['voxel_image_features'] == 'dino' + assert reference['model']['voxel_image_features'] == 'dino_naf' + shape = json.loads(Path('slat_multiobj_shape/configs/front3d_sage_32_assigned_object.json').read_text()) + assert shape['model']['voxel_image_features'] == 'dino_naf' + assert config['models']['flow'] == 'checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16' assert config['model']['cross_attention_mode'] == 'global' assert online_conditioning(config) assert not {'instance_basis', 'occupancy_encoding', 'max_objects', 'instance_conditioning'} & config['model'].keys() +def test_omitted_ss_image_features_default_to_dino(tmp_path): + config = json.loads(Path(CONFIG).read_text()) + config['model'].pop('voxel_image_features') + path = tmp_path / 'default.json' + path.write_text(json.dumps(config)) + assert load_config(path)['model']['voxel_image_features'] == 'dino' + assert model_settings(config['model'])['voxel_image_features'] == 'dino' + + @pytest.mark.parametrize('fields', [ {'voxel_aggregation': 'point'}, {'cross_attention_mode': 'occlusion_object'}, {'voxel_condition_mode': 'depth_scalar'}, {'image_projection_adaptation': 'unknown'}, @@ -57,25 +71,51 @@ def test_invalid_ss_object_policies_fail_before_loading_weights(tmp_path, fields load_config(path) -def object_flow(): +def object_flow(image_features=None): flow = native_flow() for block in flow.blocks: - block.cross_attn.proj_linear = nn.Linear(2048, 12) - return install_adapters(flow, **model_settings({ + block.cross_attn.proj_linear = nn.Linear(1024, 12) + settings = { 'depth_channels': 6, 'rank': 2, 'alpha': 2., 'cross_attention_mode': 'global', 'voxel_condition_mode': 'depth_embedding', 'voxel_aggregation': 'object_mean', - 'image_projection_adaptation': 'nora', 'voxel_coverage_weighting': 'learned_gate'})) + 'image_projection_adaptation': 'nora', 'voxel_coverage_weighting': 'learned_gate'} + if image_features is not None: + settings['voxel_image_features'] = image_features + return install_adapters(flow, **model_settings(settings)) + + +def test_dino_default_preserves_native_ss_projection_weights_and_bias(): + flow = native_flow() + for block in flow.blocks: + block.cross_attn.proj_linear = nn.Linear(1024, 12) + pretrained = [(block.cross_attn.proj_linear.weight.detach().clone(), + block.cross_attn.proj_linear.bias.detach().clone()) for block in flow.blocks] + # Exercise the SS installer default directly, without a feature override. + install_adapters(flow, depth_channels=6, rank=2, alpha=2., voxel_condition_mode='depth_embedding', + voxel_aggregation='object_mean', voxel_coverage_weighting='learned_gate', + image_projection_adaptation='nora') + image = torch.randn(3, 1024) + for block, (weight, bias) in zip(flow.blocks, pretrained): + projection = block.cross_attn.base.proj_linear + assert isinstance(projection, NoRALinear) and projection.in_features == 1024 + torch.testing.assert_close(projection.weight, weight, rtol=0, atol=0) + torch.testing.assert_close(projection.bias, bias, rtol=0, atol=0) + torch.testing.assert_close(projection.forward_without_bias(image), image @ weight.T, rtol=0, atol=0) + assert not projection.weight.requires_grad and projection.bias.requires_grad + assert block.cross_attn.mask_projection.in_features == 2048 + assert not block.cross_attn.mask_projection.weight.any() def test_native_ss_backward_and_roundtrip_have_no_segmentation_parameters(): + image_features, channels = 'dino', 1024 torch.manual_seed(3) - flow = object_flow() - conditioner = SSVoxelConditioner(2048, 6, voxel_condition_mode='depth_embedding', + flow = object_flow(image_features) + conditioner = SSVoxelConditioner(channels, 6, mask_channels=2048, voxel_condition_mode='depth_embedding', object_aggregation=True) entry = { - 'global': torch.randn(5, 4), 'image_proj': torch.zeros(8, 2048), + 'global': torch.randn(5, 4), 'image_proj': torch.zeros(8, channels), 'region_indices': torch.tensor([[0, 0, 1], [0, 1, 1]]), - 'region_image_features': torch.randn(3, 2048), + 'region_image_features': torch.randn(3, channels), 'region_object_descriptors': torch.randn(3, 2048), 'region_depth_residual': torch.tensor([[-.2], [.1], [.4]]), 'region_depth_valid': torch.ones(3, 1, dtype=torch.bool), @@ -103,12 +143,32 @@ def test_native_ss_backward_and_roundtrip_have_no_segmentation_parameters(): saved = adapter_state(flow, conditioner) assert saved['image_projection_format'] == 'nora-image-projection-v1' assert not any('segmentation' in key for key in saved['flow']) - restored = object_flow() + restored = object_flow(image_features) load_adapter_state(restored, conditioner, saved) for key, value in adapter_state(restored, conditioner)['flow'].items(): torch.testing.assert_close(value, saved['flow'][key], rtol=0, atol=0) +@pytest.mark.parametrize('explicit', [False, True]) +def test_combined_feature_checkpoint_is_rejected(explicit): + flow = object_flow() + conditioner = SSVoxelConditioner(1024, 6, mask_channels=2048, + voxel_condition_mode='depth_embedding', object_aggregation=True) + settings = { + 'depth_channels': 6, 'rank': 2, 'alpha': 2., 'cross_attention_mode': 'global', + 'voxel_condition_mode': 'depth_embedding', 'voxel_aggregation': 'object_mean', + 'image_projection_adaptation': 'nora', 'voxel_coverage_weighting': 'learned_gate'} + adapters = adapter_state(flow, conditioner) + for name, value in list(adapters['flow'].items()): + if name.endswith('.proj_linear.lora_A'): + adapters['flow'][name] = torch.cat((value, value), -1) + if explicit: + settings['voxel_image_features'] = 'dino_naf' + saved = {'config': {'model': settings}, 'adapters': adapters} + with pytest.raises(ValueError, match='DINO|voxel_image_features'): + checkpoint_model_config({'model': settings}, saved) + + def test_online_views_reuse_verified_latents_without_reading_old_conditions(tmp_path, monkeypatch): from dataloader.prepared import ExtentDataset from ss_multiobj_depth.config import TARGET_SCOPE diff --git a/ss_multiobj_depth/tests/test_sage_training_data.py b/ss_multiobj_depth/tests/test_sage_training_data.py index 2bb6161..14eea0d 100644 --- a/ss_multiobj_depth/tests/test_sage_training_data.py +++ b/ss_multiobj_depth/tests/test_sage_training_data.py @@ -86,5 +86,5 @@ def test_training_config_has_no_extent_policy(tmp_path): config['extent_spec'] = {'strategy': 'point_cloud', 'options': {'padding': 1.4}} path = tmp_path / 'config.json' path.write_text(json.dumps(config)) - with pytest.raises(ValueError, match='stage-two preprocessing'): + with pytest.raises(ValueError, match='extent_spec'): load_config(path) diff --git a/ss_multiobj_depth/tests/test_ss_preparation_workers.py b/ss_multiobj_depth/tests/test_ss_preparation_workers.py index c4f0b04..4b04f0f 100644 --- a/ss_multiobj_depth/tests/test_ss_preparation_workers.py +++ b/ss_multiobj_depth/tests/test_ss_preparation_workers.py @@ -16,10 +16,11 @@ from ss_multiobj_depth.observations import ObservationEncoder, object_lattice from slat_multiobj_shape.tests.test_finetuning import view -def test_ss_worker_preserves_native_endpoint_features_and_rng(monkeypatch): +@pytest.mark.parametrize('local_channels', [2, 4]) +def test_ss_worker_preserves_native_endpoint_features_and_rng(monkeypatch, local_channels): sample = {**view(), 'resolution': 64} encoder = ObservationEncoder.__new__(ObservationEncoder) - encoder.device, encoder.object_aggregation, encoder.local_channels = 'cpu', True, 4 + encoder.device, encoder.object_aggregation, encoder.local_channels = 'cpu', True, local_channels encoder.dino = SimpleNamespace(config=SimpleNamespace(num_register_tokens=0)) encoder.naf = SimpleNamespace(query_encoder=lambda x: x, image_encoder=lambda x, **kw: x, key_encoder=lambda q, f: f, upsampler=SimpleNamespace(num_heads=1, kernel_size=(9, 9))) @@ -31,6 +32,10 @@ def test_ss_worker_preserves_native_endpoint_features_and_rng(monkeypatch): np.testing.assert_allclose(grid.to_camera(coords.numpy()/15-.5), cube.to_camera(coords.numpy()/15-.5)) args = (sample['rgb'], sample['masks'], sample['depth'], sample['depth_valid'], sample['intrinsics'].numpy(), cube) expected, expected_image, expected_transform = encoder.encode(*args, compact=True) + assert expected['region_image_features'].shape[1] == local_channels + assert expected['region_object_descriptors'].shape[1] == 4 + torch.testing.assert_close(expected['region_image_features'][:, :2], + torch.ones_like(expected['region_image_features'][:, :2])) rng = torch.get_rng_state().clone() loader = DataLoader(PreparationDataset([sample], [0], object_aggregation=True), batch_size=1, num_workers=1, collate_fn=collate_views, generator=torch.Generator().manual_seed(31)) diff --git a/ss_multiobj_depth/tests/test_voxel_condition.py b/ss_multiobj_depth/tests/test_voxel_condition.py index a539733..35b5537 100644 --- a/ss_multiobj_depth/tests/test_voxel_condition.py +++ b/ss_multiobj_depth/tests/test_voxel_condition.py @@ -1,4 +1,4 @@ -"""Both depth gate equations, mode selection, and legacy checkpoint loading.""" +"""Supported SS equations, configuration boundaries, and checkpoint loading.""" from copy import deepcopy import json from pathlib import Path @@ -15,8 +15,8 @@ from ss_multiobj_depth.tests.test_conditioning_training import Projection, entry from ss_multiobj_depth.train import restore_checkpoint, save_checkpoint -@pytest.mark.parametrize('mode', ['depth_scalar', 'depth_embedding']) -def test_gate_only_scales_local_image_and_mask(mode): +def test_gate_only_scales_local_image_and_mask(): + mode = 'depth_embedding' adapter = VoxelConditionProjection(Projection(), 6, voxel_condition_mode=mode) sample = entry() conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode=mode) @@ -25,12 +25,8 @@ def test_gate_only_scales_local_image_and_mask(mode): with torch.no_grad(): adapter.base.proj_linear.bias.fill_(2) adapter.mask_projection.weight.fill_(.3) - if mode == 'depth_scalar': - adapter.depth_projection.weight.fill_(.2) - else: - assert adapter.depth_projection is None + assert adapter.depth_projection is None image, mask = condition['proj'][..., :4], condition['proj'][..., 4:8] - depth = condition['proj'][..., 8:14] for bias in (-100., 0., 3., 100.): with torch.no_grad(): adapter.gate[-1].bias.fill_(bias) @@ -39,19 +35,17 @@ def test_gate_only_scales_local_image_and_mask(mode): expected = x + 2 + gate * ( torch.nn.functional.linear(image, adapter.base.proj_linear.weight) + adapter.mask_projection(mask)) - if mode == 'depth_scalar': - expected = expected + adapter.depth_projection(depth) torch.testing.assert_close(adapter(x, condition), expected) -@pytest.mark.parametrize('mode', ['depth_scalar', 'depth_embedding']) -def test_gate_input_and_cfg_follow_selected_equation(mode): +def test_gate_input_and_cfg_follow_selected_equation(): + mode = 'depth_embedding' adapter = VoxelConditionProjection(Projection(), 6, voxel_condition_mode=mode) sample = entry() sample['depth_valid'][0] = False conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode=mode) condition = conditioner([sample, sample], drop=torch.tensor([False, True])) - assert condition['proj'].shape == (2, 8, 15 if mode == 'depth_scalar' else 14) + assert condition['proj'].shape == (2, 8, 14) assert not condition['proj'][1].any() and not condition['global'][1].any() assert not condition['proj'][0, 0, 8:14].any() assert all(not value.any() for value in negative_condition(condition).values()) @@ -65,20 +59,14 @@ def test_gate_input_and_cfg_follow_selected_equation(mode): adapter(x, condition | {'proj': changed}) finally: hook.remove() - if mode == 'depth_scalar': - torch.testing.assert_close(condition['proj'][0, :, -1:], sample['depth_residual'].clamp(-1, 1)) - expected = torch.cat((x, condition['proj'][..., -1:]), -1) - for value in inputs: - torch.testing.assert_close(value, expected) - else: - torch.testing.assert_close(inputs[0], torch.cat((x, condition['proj'][..., 8:14]), -1)) - torch.testing.assert_close(inputs[1][..., 7:], inputs[0][..., 7:] + 100) + torch.testing.assert_close(inputs[0], torch.cat((x, condition['proj'][..., 8:14]), -1)) + torch.testing.assert_close(inputs[1][..., 7:], inputs[0][..., 7:] + 100) with pytest.raises(ValueError, match='Packed'): adapter(x, condition | {'proj': condition['proj'][..., :-1]}) -@pytest.mark.parametrize(('name', 'mode'), [('depth_residual_gate', 'depth_scalar'), ('depth_embedding_gate', 'depth_embedding')]) -def test_config_selects_equation_and_explicit_run_directories(monkeypatch, name, mode): +def test_config_selects_equation_and_explicit_run_directories(monkeypatch): + name, mode = 'depth_embedding_gate', 'depth_embedding' import ss_multiobj_depth.train as runner original = load_config('ss_multiobj_depth/configs/front3d_sage.json') path = f'ss_multiobj_depth/configs/front3d_sage_{name}.json' @@ -106,8 +94,25 @@ def test_training_rejects_removed_visibility_flag(monkeypatch): assert error.value.code == 2 -@pytest.mark.parametrize('mode', ['additive', 'depth_scalar', 'depth_embedding']) -def test_checkpoint_mode_detection_and_legacy_adapter_restore(mode): +def test_historical_nora_checkpoint_cannot_load_into_lora_with_identical_tensor_names(): + settings = {'depth_channels': 6, 'rank': 2, 'alpha': 2, 'voxel_condition_mode': 'depth_embedding', + 'image_projection_adaptation': 'full'} + conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode='depth_embedding') + native_nora = install_adapters(native_flow(), **settings, adapter_method='nora') + state = adapter_state(native_nora, conditioner) + saved = {'config': {'model': settings}, 'adapters': state} + resolved = checkpoint_model_config({'model': settings}, saved) + assert resolved['model']['adapter_method'] == 'nora' + restored = install_adapters(native_flow(), **resolved['model']) + load_adapter_state(restored, conditioner, state) + lora = install_adapters(native_flow(), **settings, adapter_method='lora') + assert adapter_state(lora, conditioner)['flow'].keys() == state['flow'].keys() + with pytest.raises(ValueError, match='backbone adapter method differs'): + load_adapter_state(lora, conditioner, state) + + +@pytest.mark.parametrize('mode', ['additive', 'depth_embedding']) +def test_checkpoint_mode_detection_and_adapter_restore(mode): settings = {'depth_channels': 6, 'rank': 2, 'alpha': 2, 'voxel_condition_mode': mode} flow = install_adapters(native_flow(), **settings) conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode=mode) @@ -123,11 +128,11 @@ def test_checkpoint_mode_detection_and_legacy_adapter_restore(mode): load_adapter_state(restored, conditioner, saved['adapters']) for key, value in adapter_state(restored, conditioner)['flow'].items(): torch.testing.assert_close(value, saved['adapters']['flow'][key], rtol=0, atol=0) - for wrong in {'additive', 'depth_scalar', 'depth_embedding'} - {mode}: + for wrong in {'additive', 'depth_embedding'} - {mode}: with pytest.raises(ValueError, match='differs'): checkpoint_model_config({'model': {**original['model'], 'voxel_condition_mode': wrong}}, saved) corrupt = deepcopy(saved) - corrupt['config']['model']['voxel_condition_mode'] = 'depth_embedding' if mode != 'depth_embedding' else 'depth_scalar' + corrupt['config']['model']['voxel_condition_mode'] = 'depth_embedding' if mode != 'depth_embedding' else 'additive' with pytest.raises(ValueError, match='differs from its adapter tensors'): checkpoint_model_config(original, corrupt) @@ -152,8 +157,73 @@ def test_new_run_with_ambiguous_legacy_settings_requires_a_mode(): model_settings({'depth_channels': 6, 'rank': 2, 'alpha': 2, 'voxel_condition_hidden_channels': 64}) -@pytest.mark.parametrize('mode', ['depth_scalar', 'depth_embedding']) -def test_legacy_resume_still_checks_mode_data_and_source(tmp_path, monkeypatch, mode): +@pytest.mark.parametrize('fields', [ + {'voxel_condition_mode': 'depth_scalar'}, {'voxel_image_features': 'dino_naf'}, + {'image_projection_adaptation': 'frozen'}, {'visibility_hidden_channels': 64}, + {'visibility_mode': 'embedding'}, {'object_attention_layers': 1}, +]) +def test_removed_ss_model_options_are_rejected_in_configs_and_installers(tmp_path, fields): + config = json.loads(Path('ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json').read_text()) + config['model'].update(fields) + path = tmp_path / 'invalid.json' + path.write_text(json.dumps(config)) + with pytest.raises(ValueError): + load_config(path) + with pytest.raises(ValueError): + model_settings(config['model']) + with pytest.raises((ValueError, TypeError)): + install_adapters(object(), **fields) + + +def test_removed_conditioner_modes_and_local_width_are_rejected(): + with pytest.raises(ValueError, match='voxel_condition_mode'): + SSVoxelConditioner(voxel_condition_mode='depth_scalar') + with pytest.raises(ValueError, match='DINO local features'): + SSVoxelConditioner(2048, object_aggregation=True, voxel_condition_mode='depth_embedding') + + +def test_every_retained_ss_run_preset_loads(): + paths = Path('ss_multiobj_depth/configs').glob('*.json') + for path in paths: + if json.loads(path.read_text()).get('schema') != 'ss-multiobj-depth-v1': + continue + config = load_config(path) + assert config['model']['voxel_condition_mode'] in ('additive', 'depth_embedding') + assert config['model']['image_projection_adaptation'] in ('full', 'lora', 'nora') + assert config['model'].get('voxel_image_features', 'dino') == 'dino' + + +@pytest.mark.parametrize('change', ['gate_names', 'image_weights', 'image_format', 'adapter_method']) +def test_retired_checkpoint_formats_are_rejected_for_inference_and_resume(tmp_path, monkeypatch, change): + import utils.paths + monkeypatch.setattr(utils.paths, 'REPO_ROOT', tmp_path) + settings = {'depth_channels': 6, 'rank': 2, 'alpha': 2, + 'voxel_condition_mode': 'depth_embedding', 'image_projection_adaptation': 'full'} + flow = install_adapters(native_flow(), **settings) + conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode='depth_embedding') + optimizer = torch.optim.AdamW([p for p in flow.parameters() if p.requires_grad] + + list(conditioner.parameters())) + path = tmp_path / 'checkpoints/last.pt' + save_checkpoint(path, flow, conditioner, optimizer, step=1, + config={'device': 'cpu', 'model': settings}, protocol={}, provenance={}) + state = torch.load(path, weights_only=True) + adapters = state['adapters'] + if change == 'gate_names': + adapters['flow'] = {key.replace('.gate.', '.visibility.'): value for key, value in adapters['flow'].items()} + elif change == 'image_weights': + adapters['flow'] = {key: value for key, value in adapters['flow'].items() if '.proj_linear.' not in key} + elif change == 'image_format': + del adapters['image_projection_format'] + else: + del adapters['backbone_adapter_method'] + torch.save(state, path) + for resume_optimizer in (None, optimizer): + with pytest.raises(ValueError, match='adapter format or trainable parameters'): + restore_checkpoint(path, flow, conditioner, optimizer=resume_optimizer) + + +def test_resume_checks_mode_data_and_source(tmp_path, monkeypatch): + mode = 'depth_embedding' import utils.paths monkeypatch.setattr(utils.paths, 'REPO_ROOT', tmp_path) settings = {'depth_channels': 6, 'rank': 2, 'alpha': 2, 'voxel_condition_mode': mode} @@ -172,13 +242,13 @@ def test_legacy_resume_still_checks_mode_data_and_source(tmp_path, monkeypatch, restore_checkpoint(path, flow, conditioner, protocol=current) state = restore_checkpoint(path, flow, conditioner, protocol=current, accept_source_changes=True) assert state['source_changes'] == {'train.py': {'checkpoint': 'old', 'current': 'new'}} - wrong_mode = 'depth_embedding' if mode == 'depth_scalar' else 'depth_scalar' - for change in ({'manifest_sha256': 'other'}, {'model': {**current['model'], 'voxel_condition_mode': wrong_mode}}): + wrong_mode = 'additive' + for change in ({'manifest_sha256': 'other'}, {'model': {**current['model'], 'voxel_condition_mode': wrong_mode, 'voxel_condition_hidden_channels': 0}}): with pytest.raises(ValueError, match='only source changes'): restore_checkpoint(path, flow, conditioner, protocol={**current, **change}, accept_source_changes=True) -def test_training_cli_defaults_to_embedding_without_changing_legacy_configs(monkeypatch): +def test_training_cli_defaults_to_three_dataset_coverage_and_preserves_additive_presets(monkeypatch): import ss_multiobj_depth.train as runner from ss_multiobj_depth.config import DEFAULT_TRAINING_CONFIG calls = [] @@ -190,8 +260,18 @@ def test_training_cli_defaults_to_embedding_without_changing_legacy_configs(monk assert options == {'resume': False, 'accept_source_changes': False} assert config['model']['voxel_condition_mode'] == 'depth_embedding' assert config['model']['voxel_condition_hidden_channels'] == 64 + assert config['model']['voxel_aggregation'] == 'object_mean' + assert config['model']['voxel_coverage_weighting'] == 'learned_gate' + assert config['training']['conditioning_source'] == 'online' + assert config['training']['batch_size'] == 16 + assert config['training']['accumulation'] == 1 + assert [source['dataset'] for source in config['sources']] == [ + 'datasets/3dfront/extent/point_cloud', + 'datasets/sage/extent/point_cloud', + 'datasets/foundationpose/extent/point_cloud', + ] legacy = load_config('ss_multiobj_depth/configs/front3d_sage.json') - assert config['sources'] == legacy['sources'] + assert len(legacy['sources']) == 2 for key in ('output', 'checkpoints'): assert config[key] != legacy[key] assert model_settings(load_config()['model'])['voxel_condition_mode'] == 'additive' diff --git a/ss_multiobj_depth/train.py b/ss_multiobj_depth/train.py index dd0b4ee..77c1c01 100644 --- a/ss_multiobj_depth/train.py +++ b/ss_multiobj_depth/train.py @@ -20,6 +20,8 @@ from utils.training.checkpoints import (load_training_checkpoint, restore_optimi save_training_checkpoint) from utils.training.depth_augmentation import augment_depth from utils.training.optim import make_optimizer, optimizer_record, set_learning_rates +from utils.training.ema import TrainableEMA, checkpoint_ema, restore_ema +from utils.training.cfg import cfg_defaults from .config import (DEFAULT_TRAINING_CONFIG, TARGET_SCOPE, checkpoint_model_config, load_config, make_model, model_provenance, model_settings, preparation_settings, source_configs, training_protocol, online_conditioning) @@ -30,7 +32,9 @@ from .runtime import ROOT, path_under CHECKPOINT_SCHEMA = 'ss-multiobj-depth-checkpoint-v1' -def flow_loss(flow, conditioner, entries, cfg_dropout=.1): +def flow_loss(flow, conditioner, entries, cfg_dropout=None): + if cfg_dropout is None: + cfg_dropout = cfg_defaults('ss')['cfg_dropout'] if not 0 <= cfg_dropout <= 1: raise ValueError('Invalid joint CFG dropout') clean = torch.stack([entry['clean'] for entry in entries]) @@ -75,10 +79,11 @@ class UpdateSampler(Sampler): return (self.steps - self.start) * self.per_update -def save_checkpoint(path, flow, conditioner, optimizer, *, step, config, protocol, provenance, history=()): +def save_checkpoint(path, flow, conditioner, optimizer, *, step, config, protocol, provenance, history=(), ema=None): payload = {'schema': CHECKPOINT_SCHEMA, 'step': step, 'config': config, 'protocol': protocol, 'provenance': provenance, 'adapters': adapter_state(flow, conditioner), 'accepted_source_changes': list(history)} + payload.update(checkpoint_ema(ema, config.get('training', {}), step)) save_training_checkpoint(path, payload, optimizer=optimizer, device=config['device']) @@ -97,7 +102,8 @@ def source_changes(saved, protocol): for path, digest in protocol['source_sha256'].items() if recorded.get(path) != digest} -def restore_checkpoint(path, flow, conditioner, *, protocol=None, optimizer=None, accept_source_changes=False): +def restore_checkpoint(path, flow, conditioner, *, protocol=None, optimizer=None, accept_source_changes=False, + ema=None, weights='raw'): """Load adapters and optimizer state; the protocol must match unless source changes are accepted.""" state = load_training_checkpoint(path, CHECKPOINT_SCHEMA) if protocol is not None: @@ -109,10 +115,18 @@ def restore_checkpoint(path, flow, conditioner, *, protocol=None, optimizer=None state['source_changes'] = source_changes(recorded, current) elif recorded != current: raise ValueError('Resume data, model, objective or source code changed') - legacy = load_adapter_state(flow, conditioner, state['adapters'], allow_legacy=optimizer is None) + from models.voxel_condition import image_projection_format + adapters = state['adapters'] + required = {name for name, parameter in flow.named_parameters() if parameter.requires_grad} + if (set(adapters['flow']) != required + or adapters.get('image_projection_format') != image_projection_format(flow) + or adapters.get('backbone_adapter_method') != getattr(flow, 'voxel_adapter_method', 'nora')): + raise ValueError('SS checkpoint adapter format or trainable parameters differ from this model') + load_adapter_state(flow, conditioner, adapters, allow_legacy=False) + trainable = torch.nn.ModuleDict({'flow': flow, 'conditioner': conditioner}) + restore_ema(state, trainable, ema=ema, training=optimizer is not None, weights=weights) if optimizer is not None: restore_optimizer_state(state, optimizer, next(flow.parameters()).device) - state['pretrained_image_projection_parameters'] = legacy return state @@ -226,10 +240,11 @@ def train(config, *, resume=False, accept_source_changes=False): trainable = torch.nn.ModuleDict({'flow': flow, 'conditioner': conditioner}) parameters = [p for p in trainable.parameters() if p.requires_grad] optimizer = make_optimizer(trainable, settings) + ema = TrainableEMA(trainable, settings['ema_decay']) if settings.get('ema_decay') is not None else None step, history = 0, [] if resume: state = restore_checkpoint(checkpoint, flow, conditioner, protocol=protocol, optimizer=optimizer, - accept_source_changes=accept_source_changes) + accept_source_changes=accept_source_changes, ema=ema) if state['provenance'] != provenance: raise ValueError('Base model weights changed since checkpoint') step = state['step'] @@ -249,7 +264,7 @@ def train(config, *, resume=False, accept_source_changes=False): for source, cache in zip(sources, caches)], 'accepted_source_changes': history}) save = lambda: save_checkpoint(checkpoint, flow, conditioner, optimizer, step=step, config=config, - protocol=protocol, provenance=provenance, history=history) + protocol=protocol, provenance=provenance, history=history, ema=ema) if not resume: save() tracker = None @@ -297,10 +312,14 @@ def train(config, *, resume=False, accept_source_changes=False): losses.append(float(loss.detach())) norm = torch.nn.utils.clip_grad_norm_(parameters, 1., error_if_nonfinite=True) optimizer.step() + if ema is not None: + ema.update(trainable) step += 1 record = {'step': step, 'flow_mse': sum(losses) / len(losses), 'grad_norm': float(norm), 'learning_rate': optimizer.param_groups[0]['lr'], 'seconds': time.monotonic() - started} + if ema is not None: + record.update(ema_decay=ema.decay, ema_updates=ema.num_updates) for group in optimizer.param_groups: if group['name'] == 'adapter': record['adapter_learning_rate'] = group['lr'] diff --git a/utils/training/README.md b/utils/training/README.md new file mode 100644 index 0000000..9557e28 --- /dev/null +++ b/utils/training/README.md @@ -0,0 +1,96 @@ +# Shared training settings + +SS, generative SLAT segmentation, and SLAT shape use one optimization recipe in [configs/default.json](configs/default.json). +Each training preset references this file through `training.optimizer_config`. +Presets cannot combine this reference with inline optimization settings. + +| Parameter | Shared value | +| --- | --- | +| Optimizer | AdamW | +| Adapter method | LoRA, with `adapter_method="lora"` | +| New-layer learning rate | `1e-4` | +| Adapter learning rate | `1e-4` | +| Betas | `(0.9, 0.95)` | +| Non-adapter matrix decay | `0.01` | +| Adapter decay | `0.01` | +| Bias, normalization, scalar, and vector decay | `0` | +| Linear warmup | 500 optimizer updates | +| Epsilon | `1e-8` | +| Weight EMA decay | `0.999` | + +Edit `configs/default.json` to change the recipe for all three stages. +Set `adapter_method` to `lora` or `nora` in that file to select the adapter implementation. + +The default presets use `shared` for backbone adapters and image projection adapters. +SS and SLAT shape read `model.adapter_method`. +SLAT segmentation reads `model.mode`. +Their `model.image_projection_adaptation` values also resolve from the shared method. +The loaders replace `shared` with the selected method before constructing each model. +Explicit historical configurations retain their own adapter choices. + +LoRA keeps pretrained base matrices frozen and trains its low-rank residuals. +Image biases remain trainable, and image residuals initialize to zero. + +Each loader resolves the reference before training starts. +The run snapshot and checkpoint store the resolved values and the source file hash. +Later edits to the shared file do not change stored run snapshots. +Resume checks reject a changed optimization recipe. + +EMA means exponential moving average. +EMA starts from the initial trainable weights and updates once after each completed optimizer step, including warmup. +Accumulation batches do not trigger separate EMA updates. +The FP32 averages include only trainable parameters and require no additional frozen backbone copy. + +Checkpoints store raw weights, optimizer state, EMA weights, and the EMA update count. +Training resumes raw weights and the saved EMA history. +Evaluation and inference use EMA weights when available. +Segmentation monitoring temporarily applies EMA weights and preserves raw weights on CPU until evaluation ends. + +The optional top-level `inference_weights` setting accepts `auto`, `raw`, or `ema`. +The default `auto` selects raw weights for historical checkpoints without EMA. +An explicit `ema` selection requires saved EMA weights. +Historical run snapshots with inline settings retain their recorded values. +An optimizer resume cannot invent missing EMA history or silently change parameter groups. + +All three stages use Pixal3D's native loss averaging. +A microbatch is one forward and backward batch within an optimizer update. +Sparse SLAT losses average all supervised token and channel errors within each microbatch. +SS averages every element of its dense latent tensor, including all channels and grid cells. +Gradient accumulation averages microbatch losses, as Pixal3D does. + +Per-scene MSE remains available for diagnostics and does not define sparse training weights. +SLAT shape excludes tokens without matching GT latents. +Empty segmentation scenes contribute no errors and do not dilute nonempty scenes. + +CFG means classifier-free guidance. +All CFG controls reside in [configs/cfg.json](configs/cfg.json). +Each training preset references that file through the top-level `cfg_config` field. +The profile controls training dropout, inference guidance strength, guidance rescaling, and the guidance interval. + +| Stage | Training dropout | Inference strength | Guidance rescale | Guidance interval | +| --- | --- | --- | --- | --- | +| SS | `0.1` | `7.5` | `0.7` | `[0.6, 1.0]` | +| SLAT shape | `0.1` | `7.5` | `0.5` | `[0.6, 1.0]` | +| Generative SLAT segmentation | `0.0` | `1.0` | `0.0` | `[0.0, 1.0]` | + +Loaders resolve the profile into `training.cfg_dropout` and the stage's `sampling` fields. +SS retains its `cfg_strength`, `cfg_rescale`, and `cfg_interval` field names in resolved settings. +SLAT stages use `guidance_strength`, `guidance_rescale`, and `guidance_interval`. +Sampling steps, timestep warping, and the minimum noise level remain separate from CFG controls. + +The run snapshot stores resolved values and the profile hash. +Later profile edits change new runs without changing resolved snapshots or running jobs. +A shared reference cannot include inline CFG values. +Historical configurations without a shared reference retain their explicit values. +Resume checks compare training dropout and permit changes to inference guidance independently. + +SS and SLAT shape match [GenRecon's 10% dropout recipe](https://github.com/kasothaphie/GenRecon/blob/eaf1468118d20469d17079a4a19737297d2ef87b/configs/gen/slat_flow_img2shape/genrecon_512.json) and [WorldSculpt's released checkpoint settings](https://huggingface.co/AlayaLab/WorldSculpt/blob/main/shape_ft1024_mv_lora_ibr_texverse_fixedmem05/config.json). +Each scene receives one independent dropout decision, shared across its observation conditions. +Dropout occurs after the learned depth embedding and preserves spatial support, object assignments, and supervision. +Training uses one prediction per scene without multiplying its velocity by the sampling guidance strength. + +SLAT segmentation keeps condition dropout disabled and samples with conditional predictions only. +The loader requires zero training dropout, inference strength one, and zero guidance rescaling for segmentation. +An omitted rate in historical configurations also means zero. +This project choice matches [SegviGen's default conditional sampling](https://github.com/Nelipot-Lee/SegviGen/blob/81ec99ede1fbe566c73322dd968cd64bb508f5f7/inference_full.py). +SegviGen does not report its actual finetuning dropout rate, so this choice does not establish an exact match for training. diff --git a/utils/training/cfg.py b/utils/training/cfg.py new file mode 100644 index 0000000..1930ea8 --- /dev/null +++ b/utils/training/cfg.py @@ -0,0 +1,97 @@ +"""Resolve stage CFG settings and preserve explicit values in saved runs.""" +from copy import deepcopy +import json +import math + +from utils.hashing import sha256 +from utils.paths import REPO_ROOT + +DEFAULT_CFG_CONFIG = 'utils/training/configs/cfg.json' +STAGES = ('ss', 'slat_shape', 'slat_segmentation') +GUIDANCE_KEYS = ('guidance_strength', 'guidance_rescale', 'guidance_interval') +SS_GUIDANCE_KEYS = dict(zip(GUIDANCE_KEYS, ('cfg_strength', 'cfg_rescale', 'cfg_interval'))) + + +def validate_cfg(settings, stage): + if stage not in STAGES: + raise ValueError('Unknown CFG stage') + if stage == 'slat_segmentation': + dropout = settings['cfg_dropout'] + if type(dropout) not in (int, float) or dropout != 0: + raise ValueError('SLAT segmentation requires cfg_dropout=0. Condition dropout is disabled') + if settings['guidance_strength'] != 1 or settings['guidance_rescale'] != 0: + raise ValueError('Conditional-only SLAT segmentation requires guidance_strength=1 and guidance_rescale=0') + for key in ('cfg_dropout', 'guidance_strength', 'guidance_rescale'): + if type(settings[key]) not in (int, float) or not math.isfinite(settings[key]): + raise ValueError(f'{key} must be a finite number') + if not 0 <= settings['cfg_dropout'] < 1: + raise ValueError('cfg_dropout must lie in [0,1)') + if settings['guidance_strength'] < 0 or not 0 <= settings['guidance_rescale'] <= 1: + raise ValueError('Invalid CFG strength or rescale') + interval = settings['guidance_interval'] + if (not isinstance(interval, (list, tuple)) or len(interval) != 2 + or any(type(value) not in (int, float) or not math.isfinite(value) for value in interval) + or not 0 <= interval[0] <= interval[1] <= 1): + raise ValueError('guidance_interval must be ordered within [0,1]') + + +def read_cfg_profile(path=DEFAULT_CFG_CONFIG): + if not isinstance(path, str) or not path: + raise ValueError('cfg_config must name a shared settings file') + path = (REPO_ROOT / path).resolve() + if not path.is_relative_to(REPO_ROOT / 'utils/training/configs'): + raise ValueError('CFG settings must reside under utils/training/configs') + recipe = json.loads(path.read_text()) + if (not isinstance(recipe, dict) or set(recipe) != {'schema', *STAGES} + or recipe['schema'] != 'partprobe3d-cfg-v1'): + raise ValueError('Expected partprobe3d-cfg-v1 settings') + for stage in STAGES: + if not isinstance(recipe[stage], dict) or set(recipe[stage]) != {'cfg_dropout', *GUIDANCE_KEYS}: + raise ValueError('Every CFG stage must specify dropout, strength, rescale, and interval') + validate_cfg(recipe[stage], stage) + return recipe, {'path': str(path.relative_to(REPO_ROOT)), 'sha256': sha256(path)} + + +def cfg_defaults(stage): + if stage not in STAGES: + raise ValueError('Unknown CFG stage') + recipe, _ = read_cfg_profile() + return recipe[stage] + + +def guidance_defaults(stage): + settings = cfg_defaults(stage) + return {key: settings[key] for key in GUIDANCE_KEYS} + + +def resolve_cfg_settings(config, stage): + """Resolve one reference. Historical literals and resolved snapshots stay fixed.""" + if stage not in STAGES: + raise ValueError('Unknown CFG stage') + aliases = SS_GUIDANCE_KEYS if stage == 'ss' else {key: key for key in GUIDANCE_KEYS} + if 'cfg_config' not in config: + if 'cfg_profile' in config: + if config['cfg_profile']['stage'] != stage: + raise ValueError('The saved CFG profile belongs to another stage') + settings = {key: config['sampling'][alias] for key, alias in aliases.items()} + settings['cfg_dropout'] = config.get('training', {}).get('cfg_dropout', 0.) + validate_cfg(settings, stage) + elif stage == 'slat_segmentation': + settings = {'cfg_dropout': config['training'].get('cfg_dropout', 0.), + 'guidance_strength': 1., 'guidance_rescale': 0., 'guidance_interval': [0., 1.], + **config.get('sampling', {})} + validate_cfg(settings, stage) + return config + if ('cfg_profile' in config or 'cfg_dropout' in config.get('training', {}) + or (set(GUIDANCE_KEYS) | set(SS_GUIDANCE_KEYS.values())).intersection(config.get('sampling', {}))): + raise ValueError('Shared cfg_config cannot have inline CFG settings') + recipe, profile = read_cfg_profile(config['cfg_config']) + selected = recipe[stage] + result = deepcopy(config) + del result['cfg_config'] + if 'training' in result: + result['training']['cfg_dropout'] = selected['cfg_dropout'] + result['sampling'] = {**result.get('sampling', {}), + **{alias: selected[key] for key, alias in aliases.items()}} + result['cfg_profile'] = {**profile, 'stage': stage} + return result diff --git a/utils/training/configs/cfg.json b/utils/training/configs/cfg.json new file mode 100644 index 0000000..610777c --- /dev/null +++ b/utils/training/configs/cfg.json @@ -0,0 +1,21 @@ +{ + "schema": "partprobe3d-cfg-v1", + "ss": { + "cfg_dropout": 0.1, + "guidance_strength": 7.5, + "guidance_rescale": 0.7, + "guidance_interval": [0.6, 1.0] + }, + "slat_shape": { + "cfg_dropout": 0.1, + "guidance_strength": 7.5, + "guidance_rescale": 0.5, + "guidance_interval": [0.6, 1.0] + }, + "slat_segmentation": { + "cfg_dropout": 0.0, + "guidance_strength": 1.0, + "guidance_rescale": 0.0, + "guidance_interval": [0.0, 1.0] + } +} diff --git a/utils/training/configs/default.json b/utils/training/configs/default.json new file mode 100644 index 0000000..e97363b --- /dev/null +++ b/utils/training/configs/default.json @@ -0,0 +1,16 @@ +{ + "schema": "partprobe3d-optimization-v1", + "adapter_method": "lora", + "learning_rate": 0.0001, + "weight_decay": 0.01, + "ema_decay": 0.999, + "optimizer": { + "name": "AdamW", + "adapter_learning_rate": 0.0001, + "betas": [0.9, 0.95], + "adapter_weight_decay": 0.01, + "bias_norm_scalar_weight_decay": 0.0, + "warmup_steps": 500, + "eps": 1e-8 + } +} diff --git a/utils/training/ema.py b/utils/training/ema.py new file mode 100644 index 0000000..9b22290 --- /dev/null +++ b/utils/training/ema.py @@ -0,0 +1,129 @@ +"""Maintain an FP32 moving average of trainable parameters without copying the backbone.""" +import math +from contextlib import contextmanager + +import torch + + +def validate_ema_decay(decay): + if (isinstance(decay, bool) or not isinstance(decay, (int, float)) + or not math.isfinite(decay) or not 0 <= decay < 1): + raise ValueError('EMA decay must be finite and in [0,1)') + + +def _parameters(model): + return {name: p for name, p in model.named_parameters() if p.requires_grad} + + +def _validate_state(parameters, state): + if not isinstance(state, dict) or set(state) != {'decay', 'num_updates', 'parameters'}: + raise ValueError('Invalid EMA checkpoint state') + validate_ema_decay(state['decay']) + if type(state['num_updates']) is not int or state['num_updates'] < 0: + raise ValueError('EMA update count must be a nonnegative integer') + values = state['parameters'] + if not isinstance(values, dict) or set(values) != set(parameters): + raise ValueError('EMA parameters differ from the trainable model parameters') + for name, p in parameters.items(): + value = values[name] + if not isinstance(value, torch.Tensor) or value.shape != p.shape or value.dtype != torch.float32: + raise ValueError(f'EMA parameter shape or dtype differs: {name}') + + +@torch.no_grad() +def load_ema_weights(model, state): + """Copy saved averages into the model without allocating another EMA on its device.""" + parameters = _parameters(model) + _validate_state(parameters, state) + for name, p in parameters.items(): + p.copy_(state['parameters'][name]) + + +def checkpoint_ema(ema, settings, step): + """Require complete EMA history when the run enables averaging.""" + if ema is None: + if settings.get('ema_decay') is not None: + raise ValueError('EMA is enabled but its checkpoint state is missing') + return {} + if ema.num_updates != step: + raise ValueError('EMA update count differs from the checkpoint step') + if ema.decay != settings.get('ema_decay'): + raise ValueError('EMA decay differs from the checkpoint training settings') + return {'ema': ema.state_dict()} + + +def restore_ema(saved, model, *, ema=None, training=False, weights='raw'): + """Resume EMA history or select inference weights without creating a second model.""" + if weights not in ('auto', 'raw', 'ema') or (training and weights != 'raw'): + raise ValueError('Optimizer resume requires raw weights. Inference weights must be auto, raw or ema') + state = saved.get('ema') + selected = weights == 'ema' or (weights == 'auto' and state is not None) + if ema is not None or selected: + if state is None: + raise ValueError('The checkpoint has no EMA state') + _validate_state(_parameters(model), state) + if state['num_updates'] != saved['step']: + raise ValueError('EMA update count differs from the checkpoint step') + if state['decay'] != saved['config'].get('training', {}).get('ema_decay'): + raise ValueError('EMA decay differs from the checkpoint training settings') + if ema is not None: + ema.load_state_dict(state) + elif training and state is not None: + raise ValueError('The checkpoint uses EMA but training has EMA disabled') + if selected: + load_ema_weights(model, state) + saved['checkpoint_weights'] = 'ema' if selected else 'raw' + + +class TrainableEMA: + """Initialize from current weights and update once after each optimizer step.""" + def __init__(self, model, decay): + validate_ema_decay(decay) + self.decay = float(decay) + self.num_updates = 0 + self.parameters = {name: p.detach().to(dtype=torch.float32, copy=True) + for name, p in _parameters(model).items()} + + @torch.no_grad() + def update(self, model): + parameters = _parameters(model) + if set(parameters) != set(self.parameters): + raise ValueError('EMA parameters changed during training') + for name, p in parameters.items(): + self.parameters[name].lerp_(p.detach().float(), 1 - self.decay) + self.num_updates += 1 + + @torch.no_grad() + def reset_parameters(self, model, names): + """Apply intentional parameter resets to the corresponding averages only.""" + parameters = _parameters(model) + for name in names: + self.parameters[name].copy_(parameters[name]) + + def state_dict(self): + return {'decay': self.decay, 'num_updates': self.num_updates, + 'parameters': {name: p.detach().cpu() for name, p in self.parameters.items()}} + + @contextmanager + def average_parameters(self, model): + """Evaluate averages temporarily, keeping the raw backup on CPU to limit VRAM.""" + parameters = _parameters(model) + backup = {name: p.detach().to(device='cpu', copy=True) for name, p in parameters.items()} + try: + with torch.no_grad(): + for name, p in parameters.items(): + p.copy_(self.parameters[name]) + yield + finally: + with torch.no_grad(): + for name, p in parameters.items(): + p.copy_(backup[name]) + + @torch.no_grad() + def load_state_dict(self, state): + _validate_state(self.parameters, state) + if state['decay'] != self.decay: + raise ValueError('EMA decay differs from the checkpoint') + for name, p in self.parameters.items(): + p.copy_(state['parameters'][name]) + self.num_updates = state['num_updates'] diff --git a/utils/training/losses.py b/utils/training/losses.py index 55c34aa..ef58439 100644 --- a/utils/training/losses.py +++ b/utils/training/losses.py @@ -1,8 +1,21 @@ -"""Small visible-membership training utilities, separate from occupancy labels.""" +"""Shared loss reductions and utilities for observed membership.""" import torch from torch.nn import functional as F +def native_batch_mean(losses, element_counts): + """Weight sample means by scalar counts, matching Pixal3D's pooled MSE. + + Empty samples supply a differentiable zero with a count of zero. + """ + if not losses or len(losses) != len(element_counts): + raise ValueError('Supply one scalar count for each sample loss') + values = torch.stack(losses) + counts = torch.stack([torch.as_tensor(count, device=values.device, dtype=values.dtype) + for count in element_counts]) + return (values * counts).sum() / counts.sum().clamp_min(1) + + def asset_components(scene_assets): """Connected scene groups; no source asset can cross between groups.""" remaining = set(scene_assets) diff --git a/utils/training/optim.py b/utils/training/optim.py index 7b47bff..171ca0f 100644 --- a/utils/training/optim.py +++ b/utils/training/optim.py @@ -12,9 +12,17 @@ def validate_optimizer(settings): raise ValueError(f'Invalid optimizer {key}') extra = settings.get('optimizer', {}) allowed = {'betas', 'eps', 'adapter_learning_rate', 'adapter_weight_decay', 'warmup_steps', - 'adapter_learning_rate_after_warmup'} + 'adapter_learning_rate_after_warmup', 'exclude_bias_norm_from_weight_decay', + 'name', 'bias_norm_scalar_weight_decay'} if not isinstance(extra, dict) or set(extra) - allowed: - raise ValueError('Unknown segmentation optimizer settings') + raise ValueError('Unknown optimizer settings') + if extra.get('name', 'AdamW') != 'AdamW': + raise ValueError('The supported optimizer is AdamW') + decay = extra.get('bias_norm_scalar_weight_decay', 0.) + if isinstance(decay, bool) or not isinstance(decay, (int, float)) or not math.isfinite(decay) or decay < 0: + raise ValueError('Invalid optimizer bias_norm_scalar_weight_decay') + if type(extra.get('exclude_bias_norm_from_weight_decay', False)) is not bool: + raise ValueError('Optimizer exclude_bias_norm_from_weight_decay must be a boolean') betas = extra.get('betas', [.9, .999]) if (not isinstance(betas, (list, tuple)) or len(betas) != 2 or any(not isinstance(b, (int, float)) or not math.isfinite(b) or not 0 <= b < 1 for b in betas)): @@ -39,15 +47,32 @@ def make_optimizer(model, settings): parameters = [(name, p) for name, p in model.named_parameters() if p.requires_grad] extra = settings.get('optimizer', {}) weight_decay = settings.get('weight_decay', .01) + exclude = extra.get('exclude_bias_norm_from_weight_decay', False) or 'bias_norm_scalar_weight_decay' in extra + bias_decay = extra.get('bias_norm_scalar_weight_decay', 0.) + # Include multidimensional normalization weights, even without "norm" in their path. + norm_parameters = {id(p) for module in model.modules() if 'norm' in type(module).__name__.lower() + for p in module.parameters(recurse=False)} if exclude else set() groups = [] for adapter, name in ((False, 'new'), (True, 'adapter')): selected = [(key, p) for key, p in parameters if key.endswith(('.lora_A', '.lora_B')) == adapter] - values = [p for _, p in selected] - if values: - groups.append({'params': values, 'param_names': [key for key, _ in selected], 'name': name, - 'lr': extra.get('adapter_learning_rate', settings['learning_rate']) if adapter else settings['learning_rate'], - 'weight_decay': extra.get('adapter_weight_decay', weight_decay) if adapter else weight_decay}) - return torch.optim.AdamW(groups, betas=tuple(extra.get('betas', [.9, .999])), eps=extra.get('eps', 1e-8)) + decay = extra.get('adapter_weight_decay', weight_decay) if adapter else weight_decay + partitions = [(name, selected, decay)] + if exclude and not adapter: + def no_decay(key, p): + return (p.ndim < 2 or p.numel() == 1 or key.lower() == 'bias' + or key.lower().endswith('.bias') or 'norm' in key.lower() + or id(p) in norm_parameters) + partitions = [('new', [(key, p) for key, p in selected if not no_decay(key, p)], decay), + ('new_no_decay' if bias_decay == 0 else 'new_bias_norm_scalar', + [(key, p) for key, p in selected if no_decay(key, p)], bias_decay)] + for group_name, members, group_decay in partitions: + if members: + groups.append({'params': [p for _, p in members], 'param_names': [key for key, _ in members], + 'name': group_name, + 'lr': extra.get('adapter_learning_rate', settings['learning_rate']) if adapter else settings['learning_rate'], + 'weight_decay': group_decay}) + optimizer_class = {'AdamW': torch.optim.AdamW}[extra.get('name', 'AdamW')] + return optimizer_class(groups, betas=tuple(extra.get('betas', [.9, .999])), eps=extra.get('eps', 1e-8)) def set_learning_rates(optimizer, settings, update): diff --git a/utils/training/settings.py b/utils/training/settings.py new file mode 100644 index 0000000..bb56780 --- /dev/null +++ b/utils/training/settings.py @@ -0,0 +1,55 @@ +"""Resolve the shared optimization recipe and freeze its values in each run snapshot.""" +from copy import deepcopy +import json + +from utils.hashing import sha256 +from utils.paths import REPO_ROOT +from .ema import validate_ema_decay +from .optim import validate_optimizer + +DEFAULT_OPTIMIZER_CONFIG = 'utils/training/configs/default.json' +OPTIMIZATION_KEYS = {'learning_rate', 'weight_decay', 'warmup', 'optimizer', 'ema_decay', 'adapter_method'} + + +def resolve_adapter_settings(model, training, *, method_key='adapter_method'): + """Replace explicit shared adapter selectors with the frozen recipe value.""" + result = dict(model) + for key in (method_key, 'image_projection_adaptation'): + if result.get(key) == 'shared': + method = training.get('adapter_method') + if method not in ('lora', 'nora'): + raise ValueError('Shared model adapters require a recipe adapter_method of lora or nora') + result[key] = method + return result + + +def resolve_training_settings(settings): + """Read one recipe reference. Already resolved snapshots retain their original values.""" + if 'optimizer_config' not in settings: + return settings + if OPTIMIZATION_KEYS.intersection(settings) or 'optimizer_profile' in settings: + raise ValueError('Shared optimizer_config cannot have inline optimization settings') + if not isinstance(settings['optimizer_config'], str) or not settings['optimizer_config']: + raise ValueError('optimizer_config must name a shared settings file') + path = (REPO_ROOT / settings['optimizer_config']).resolve() + if not path.is_relative_to(REPO_ROOT / 'utils/training/configs'): + raise ValueError('Optimizer settings must reside under utils/training/configs') + recipe = json.loads(path.read_text()) + required = {'schema', 'learning_rate', 'weight_decay', 'optimizer', 'ema_decay', 'adapter_method'} + if not isinstance(recipe, dict) or set(recipe) != required or recipe['schema'] != 'partprobe3d-optimization-v1': + raise ValueError('Expected partprobe3d-optimization-v1 settings') + if recipe['adapter_method'] not in ('lora', 'nora'): + raise ValueError('The shared recipe adapter_method must be lora or nora') + optimizer_keys = {'name', 'adapter_learning_rate', 'betas', 'adapter_weight_decay', + 'bias_norm_scalar_weight_decay', 'warmup_steps', 'eps'} + if not isinstance(recipe['optimizer'], dict) or not optimizer_keys.issubset(recipe['optimizer']): + raise ValueError('The shared recipe must specify every optimizer parameter') + result = deepcopy(settings) + del result['optimizer_config'] + result.update({key: value for key, value in recipe.items() if key != 'schema'}) + result['warmup'] = result['optimizer']['warmup_steps'] + result['optimizer_profile'] = {'path': str(path.relative_to(REPO_ROOT)), 'sha256': sha256(path)} + validate_optimizer(result) + if result['ema_decay'] is not None: + validate_ema_decay(result['ema_decay']) + return result diff --git a/utils/training/tests/test_cfg.py b/utils/training/tests/test_cfg.py new file mode 100644 index 0000000..9662346 --- /dev/null +++ b/utils/training/tests/test_cfg.py @@ -0,0 +1,151 @@ +"""Check shared CFG controls, frozen snapshots, and actual sampling arguments.""" +from copy import deepcopy +import json +from types import SimpleNamespace + +import pytest +import torch + +from utils.training import cfg + + +def stages(): + from ss_multiobj_depth.config import DEFAULT_TRAINING_CONFIG, load_config as ss, training_protocol as ss_protocol + from slat_multiobj_shape.config import load_config as shape, training_protocol as shape_protocol + from slat_segvigen.config import load_config as seg, training_protocol as seg_protocol + return [('ss', lambda path=None: ss(path or DEFAULT_TRAINING_CONFIG), ss_protocol), + ('slat_shape', shape, shape_protocol), ('slat_segmentation', seg, seg_protocol)] + + +def profile(tmp_path, monkeypatch): + recipe = json.loads((cfg.REPO_ROOT / cfg.DEFAULT_CFG_CONFIG).read_text()) + path = tmp_path / cfg.DEFAULT_CFG_CONFIG + path.parent.mkdir(parents=True) + path.write_text(json.dumps(recipe)) + monkeypatch.setattr(cfg, 'REPO_ROOT', tmp_path) + return path, recipe + + +def test_defaults_share_one_cfg_source_and_keep_stage_specific_guidance(): + for stage, load, _ in stages(): + settings = load() + expected = cfg.cfg_defaults(stage) + assert settings['training']['cfg_dropout'] == expected['cfg_dropout'] + aliases = cfg.SS_GUIDANCE_KEYS if stage == 'ss' else {key: key for key in cfg.GUIDANCE_KEYS} + assert all(settings['sampling'][alias] == expected[key] for key, alias in aliases.items()) + assert settings['cfg_profile']['path'] == cfg.DEFAULT_CFG_CONFIG + assert settings['cfg_profile']['stage'] == stage + assert 'cfg_config' not in settings + + +def test_one_edit_changes_new_runs_and_saved_runs_need_no_profile_file(tmp_path, monkeypatch): + original = [load() for _, load, _ in stages()] + path, recipe = profile(tmp_path, monkeypatch) + recipe['ss'].update(cfg_dropout=.2, guidance_strength=3.25, guidance_rescale=.4, guidance_interval=[.2, .9]) + recipe['slat_shape'].update(cfg_dropout=.3, guidance_strength=4.5, guidance_rescale=.2, guidance_interval=[.3, .8]) + path.write_text(json.dumps(recipe)) + for stage, load, _ in stages(): + changed = load() + key = 'cfg_strength' if stage == 'ss' else 'guidance_strength' + assert changed['sampling'][key] == recipe[stage]['guidance_strength'] + assert changed['training']['cfg_dropout'] == recipe[stage]['cfg_dropout'] + assert changed['cfg_profile']['sha256'] != original[0]['cfg_profile']['sha256'] + path.unlink() + for (stage, load, _), recorded in zip(stages(), original): + snapshot = tmp_path / f'{stage}.json' + snapshot.write_text(json.dumps(recorded)) + assert load(snapshot) == recorded + + +@pytest.mark.parametrize('change', [ + {'training': {'cfg_dropout': .1}}, + {'sampling': {'cfg_strength': 3.}}, + {'sampling': {'guidance_rescale': .2}}, +]) +def test_shared_profile_rejects_inline_cfg_values(change): + with pytest.raises(ValueError, match='inline CFG'): + cfg.resolve_cfg_settings({'cfg_config': cfg.DEFAULT_CFG_CONFIG, **change}, 'ss') + + +@pytest.mark.parametrize(('stage', 'key', 'value'), [ + ('ss', 'cfg_dropout', 1.), + ('ss', 'guidance_strength', True), + ('slat_shape', 'guidance_rescale', float('nan')), + ('slat_shape', 'guidance_interval', [.8, .2]), + ('slat_segmentation', 'cfg_dropout', .1), + ('slat_segmentation', 'guidance_strength', 2.), +]) +def test_invalid_profile_values_fail_before_training(tmp_path, monkeypatch, stage, key, value): + path, recipe = profile(tmp_path, monkeypatch) + recipe[stage][key] = value + path.write_text(json.dumps(recipe)) + with pytest.raises(ValueError): + cfg.cfg_defaults(stage) + + +def test_ss_inference_passes_shared_guidance_to_the_sampler(tmp_path, monkeypatch): + from ss_multiobj_depth.inference import SSInference + path, recipe = profile(tmp_path, monkeypatch) + recipe['ss'].update(guidance_strength=3.25, guidance_rescale=.4, guidance_interval=[.2, .9]) + path.write_text(json.dumps(recipe)) + calls = [] + + class Sampler: + def sample(self, flow, noise, **kwargs): + calls.append(kwargs) + return SimpleNamespace(samples=noise) + + inference = SSInference.__new__(SSInference) + inference.config = stages()[0][1]() + inference.device = 'cpu' + inference.load = lambda: {'flow': SimpleNamespace(in_channels=2, resolution=2), 'sampler': Sampler(), + 'decoder': lambda _: torch.ones(1, 1, 2, 2, 2)} + inference.sample({'global': torch.ones(1, 2, 4), 'proj': torch.ones(1, 8, 4)}, seed=4) + assert calls[0]['guidance_strength'] == 3.25 + assert calls[0]['guidance_rescale'] == .4 + assert calls[0]['guidance_interval'] == [.2, .9] + assert all(not value.any() for value in calls[0]['neg_cond'].values()) + + +def test_shape_constructor_uses_shared_defaults_and_preserves_explicit_sampling(tmp_path, monkeypatch): + from slat_multiobj_shape.model import MultiObjectShape + from slat_multiobj_shape.tests.test_shape import tiny_native, normalization + path, recipe = profile(tmp_path, monkeypatch) + recipe['slat_shape'].update(guidance_strength=4.5, guidance_rescale=.2, guidance_interval=[.3, .8]) + path.write_text(json.dumps(recipe)) + model = MultiObjectShape(tiny_native(32), normalization(), resolution=32) + assert all(model.sampling[key] == recipe['slat_shape'][key] for key in cfg.GUIDANCE_KEYS) + path.unlink() + frozen = MultiObjectShape(tiny_native(32), normalization(), resolution=32, sampling=model.sampling) + assert frozen.sampling == model.sampling + + +def test_training_protocols_ignore_inference_cfg_but_preserve_training_dropout(tmp_path): + (tmp_path / 'manifest.json').write_text('{}') + + class Data: + root = tmp_path + target_scope = 'masked_objects_complete_occupancy' + + def target_manifests(self): + return ['fixed-targets'] + + def checksums(self): + return {'view': 'fixed-latents'} + + def cache_provenance(self): + return [{'policy': {'support_scope': self.target_scope}}] * 2 + + data = Data() + data.datasets = [data, data] + for stage, load, protocol in stages(): + settings = load() + before = protocol(settings, data) + changed = deepcopy(settings) + key = 'cfg_interval' if stage == 'ss' else 'guidance_interval' + changed['sampling'][key] = [.2, .8] + changed['cfg_profile']['sha256'] = 'updated inference profile' + assert protocol(changed, data) == before + if stage != 'slat_segmentation': + changed['training']['cfg_dropout'] = .2 + assert protocol(changed, data) != before diff --git a/utils/training/tests/test_ema.py b/utils/training/tests/test_ema.py new file mode 100644 index 0000000..28edb1f --- /dev/null +++ b/utils/training/tests/test_ema.py @@ -0,0 +1,114 @@ +from copy import deepcopy + +import pytest +import torch +from torch import nn + +from utils.training.ema import TrainableEMA, load_ema_weights + + +def model(): + result = nn.ModuleDict({'frozen': nn.Linear(2, 2).requires_grad_(False), 'head': nn.Linear(2, 1)}) + result.register_parameter('lambda_param', nn.Parameter(torch.ones(()))) + return result + + +def test_ema_averages_only_trainable_parameters_in_fp32_without_changing_model_or_rng(): + net = model().to(dtype=torch.bfloat16) + random_state = torch.get_rng_state() + ema = TrainableEMA(net, .9995) + assert torch.equal(random_state, torch.get_rng_state()) + assert set(ema.parameters) == {'lambda_param', 'head.weight', 'head.bias'} + assert all(p.dtype == torch.float32 and not p.requires_grad for p in ema.parameters.values()) + before = {name: p.clone() for name, p in ema.parameters.items()} + with torch.no_grad(): + for p in net.parameters(): + p.add_(2.) + raw = deepcopy(net.state_dict()) + ema.update(net) + assert ema.num_updates == 1 + for name, p in ema.parameters.items(): + expected = before[name] * .9995 + raw[name].float() * .0005 + torch.testing.assert_close(p, expected) + assert p.data_ptr() != dict(net.named_parameters())[name].data_ptr() + for name, value in net.state_dict().items(): + torch.testing.assert_close(value, raw[name], rtol=0, atol=0) + assert torch.equal(random_state, torch.get_rng_state()) + load_ema_weights(net, ema.state_dict()) + for name, p in net.named_parameters(): + expected = ema.parameters[name].to(p.dtype) if p.requires_grad else raw[name] + torch.testing.assert_close(p, expected, rtol=0, atol=0) + + +def test_ema_checkpoint_continues_exact_history_and_resets_only_selected_parameters(tmp_path): + net = model() + ema = TrainableEMA(net, .9995) + for _ in range(2): + with torch.no_grad(): + net['head'].weight.add_(.2) + ema.update(net) + path = tmp_path / 'ema.pt' + torch.save(ema.state_dict(), path) + restored = TrainableEMA(net, .9995) + restored.load_state_dict(torch.load(path, weights_only=True)) + assert restored.num_updates == ema.num_updates == 2 + with torch.no_grad(): + net['head'].bias.add_(.4) + net.lambda_param.fill_(.7) + ema.update(net) + restored.update(net) + for name in ema.parameters: + torch.testing.assert_close(ema.parameters[name], restored.parameters[name], rtol=0, atol=0) + before = deepcopy(restored.state_dict()) + restored.reset_parameters(net, ['lambda_param']) + torch.testing.assert_close(restored.parameters['lambda_param'], net.lambda_param) + assert restored.num_updates == 3 + for name in ('head.weight', 'head.bias'): + torch.testing.assert_close(restored.parameters[name], before['parameters'][name], rtol=0, atol=0) + + +@pytest.mark.parametrize('decay', [True, '0.9995', -1., 1., float('nan'), float('inf')]) +def test_ema_rejects_invalid_decay(decay): + with pytest.raises(ValueError, match='EMA decay'): + TrainableEMA(model(), decay) + + +@pytest.mark.parametrize('change,match', [ + ({'decay': .99}, 'decay differs'), ({'num_updates': True}, 'update count'), + ({'parameters': {}}, 'parameters differ'), ({'extra': True}, 'Invalid EMA')]) +def test_ema_rejects_incompatible_checkpoint_state(change, match): + ema = TrainableEMA(model(), .9995) + state = ema.state_dict() + state.update(change) + with pytest.raises(ValueError, match=match): + ema.load_state_dict(state) + + +def test_ema_rejects_changed_parameter_shapes_and_training_set(): + net = model() + ema = TrainableEMA(net, .9995) + state = deepcopy(ema.state_dict()) + state['parameters']['head.weight'] = torch.zeros(3) + with pytest.raises(ValueError, match='shape or dtype'): + load_ema_weights(net, state) + net['frozen'].requires_grad_(True) + with pytest.raises(ValueError, match='parameters changed'): + ema.update(net) + + +def test_temporary_ema_evaluation_restores_raw_weights_even_on_failure(): + net = model() + ema = TrainableEMA(net, .9995) + with torch.no_grad(): + net['head'].weight.add_(1.) + ema.update(net) + raw = deepcopy(net.state_dict()) + with pytest.raises(RuntimeError, match='evaluation failed'): + with ema.average_parameters(net): + for name, p in net.named_parameters(): + if p.requires_grad: + torch.testing.assert_close(p, ema.parameters[name], rtol=0, atol=0) + raise RuntimeError('evaluation failed') + for name, value in net.state_dict().items(): + torch.testing.assert_close(value, raw[name], rtol=0, atol=0) + assert ema.num_updates == 1 diff --git a/utils/training/tests/test_losses.py b/utils/training/tests/test_losses.py index 43e0b24..1822dbc 100644 --- a/utils/training/tests/test_losses.py +++ b/utils/training/tests/test_losses.py @@ -1,5 +1,36 @@ +import pytest import torch -from utils.training.losses import asset_components, clean_from_velocity, membership_metrics, visible_membership_loss +from utils.training.losses import (asset_components, clean_from_velocity, membership_metrics, + native_batch_mean, visible_membership_loss) + + +@pytest.mark.parametrize('shapes', [ + [(2, 32), (9, 32)], + [(8, 16, 16, 16), (8, 16, 16, 16)], + [(0, 32), (5, 32)], +]) +def test_native_reduction_matches_concatenated_mse_and_gradients(shapes): + generator = torch.Generator().manual_seed(91) + predictions = [torch.randn(shape, generator=generator, requires_grad=True) for shape in shapes] + targets = [torch.randn(shape, generator=generator) for shape in shapes] + losses = [torch.nn.functional.mse_loss(prediction, target) if target.numel() else prediction.sum() + for prediction, target in zip(predictions, targets)] + actual = native_batch_mean(losses, [target.numel() for target in targets]) + expected = torch.nn.functional.mse_loss(torch.cat([value.flatten() for value in predictions]), + torch.cat([value.flatten() for value in targets])) + torch.testing.assert_close(actual, expected) + actual_grads = torch.autograd.grad(actual, predictions, retain_graph=True) + expected_grads = torch.autograd.grad(expected, predictions) + for actual_grad, expected_grad in zip(actual_grads, expected_grads): + torch.testing.assert_close(actual_grad, expected_grad) + + +def test_empty_native_batch_retains_a_differentiable_zero(): + parameter = torch.tensor(3., requires_grad=True) + loss = native_batch_mean([parameter * 0, parameter * 0], [0, 0]) + assert loss.item() == 0 + loss.backward() + assert parameter.grad.item() == 0 def test_scene_split_keeps_transitive_asset_overlap_together(): diff --git a/utils/training/tests/test_optim.py b/utils/training/tests/test_optim.py index 2b289db..a561ca7 100644 --- a/utils/training/tests/test_optim.py +++ b/utils/training/tests/test_optim.py @@ -4,7 +4,7 @@ import pytest import torch from torch import nn -from utils.training.optim import make_optimizer, set_learning_rates, validate_optimizer +from utils.training.optim import make_optimizer, optimizer_record, set_learning_rates, validate_optimizer from utils.training.lora import LoRALinear, NoRALinear @@ -40,6 +40,8 @@ def test_adapter_groups_cover_each_trainable_parameter_and_exclude_frozen_weight @pytest.mark.parametrize('change', [{'betas': [.9, 1.]}, {'betas': [.9]}, {'eps': 0.}, {'adapter_learning_rate': float('nan')}, {'warmup_steps': -1}, {'adapter_weight_decay': -.1}, {'unknown': True}, + {'exclude_bias_norm_from_weight_decay': 1}, + {'exclude_bias_norm_from_weight_decay': 'true'}, {'adapter_learning_rate_after_warmup': 0.}, {'adapter_learning_rate_after_warmup': float('nan')}, {'adapter_learning_rate_after_warmup': 1e-4, 'warmup_steps': 0}]) @@ -90,3 +92,77 @@ def test_default_groups_share_one_rate_for_depth_gate_and_adapters(): for update in (1, 122, 250, 251): set_learning_rates(optimizer, value, update) assert all(group['lr'] == pytest.approx(1e-4*min(update/250, 1.)) for group in optimizer.param_groups) + + +def decay_model(wrapper=NoRALinear): + model = nn.ModuleDict({'flow': wrapper(nn.Linear(3, 4), rank=2, alpha=2), + 'head': nn.Linear(4, 2), 'affine': nn.LayerNorm((2, 2))}) + model.register_parameter('scalar', nn.Parameter(torch.ones(()))) + model.register_parameter('singleton', nn.Parameter(torch.ones(1, 1))) + model.register_parameter('lambda_param', nn.Parameter(torch.ones(4))) + return model + + +@pytest.mark.parametrize('wrapper', [LoRALinear, NoRALinear]) +@pytest.mark.parametrize('adapter_decay', [0., .01]) +def test_decay_exclusions_apply_to_bias_norm_scalars_and_vectors_only(wrapper, adapter_decay): + model = decay_model(wrapper) + value = settings() + value['learning_rate'] = .1 + value['optimizer'].update(exclude_bias_norm_from_weight_decay=True, + adapter_weight_decay=adapter_decay) + optimizer = make_optimizer(model, value) + groups = {g['name']: g for g in optimizer.param_groups} + assert set(groups) == {'new', 'new_no_decay', 'adapter'} + assert groups['new']['param_names'] == ['head.weight'] + assert set(groups['new_no_decay']['param_names']) == { + 'scalar', 'singleton', 'lambda_param', 'head.bias', 'affine.weight', 'affine.bias'} + assert groups['adapter']['param_names'] == ['flow.lora_A', 'flow.lora_B'] + assert [g['weight_decay'] for g in optimizer.param_groups] == [.01, 0., adapter_decay] + parameters = [p for group in optimizer.param_groups for p in group['params']] + assert len(parameters) == len({id(p) for p in parameters}) + assert {id(p) for p in parameters} == {id(p) for p in model.parameters() if p.requires_grad} + assert all(g['betas'] == (.9, .95) for g in optimizer.param_groups) + # Zero gradients isolate AdamW's decoupled decay from gradient updates. + before = {name: p.detach().clone() for name, p in model.named_parameters()} + for p in parameters: + p.grad = torch.zeros_like(p) + optimizer.step() + for group in optimizer.param_groups: + for name, p in zip(group['param_names'], group['params']): + torch.testing.assert_close(p, before[name] * (1 - group['lr'] * group['weight_decay'])) + torch.testing.assert_close(model['flow'].base.weight, before['flow.base.weight']) + for update in (1, 1000, 2000, 2001): + set_learning_rates(optimizer, value, update) + fraction = min(update / 2000, 1.) + assert groups['new']['lr'] == groups['new_no_decay']['lr'] == pytest.approx(.1 * fraction) + assert groups['adapter']['lr'] == pytest.approx(3e-5 * fraction) + record = optimizer_record(optimizer, value) + assert [group['weight_decay'] for group in record['groups']] == [.01, 0., adapter_decay] + + +def test_decay_groups_resume_the_same_optimizer_updates(tmp_path): + value = settings() + value['optimizer']['exclude_bias_norm_from_weight_decay'] = True + model = decay_model() + optimizer = make_optimizer(model, value) + for p in model.parameters(): + if p.requires_grad: + p.grad = torch.ones_like(p) + set_learning_rates(optimizer, value, 1) + optimizer.step() + path = tmp_path / 'optimizer.pt' + torch.save({'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, path) + restored = decay_model() + other = make_optimizer(restored, value) + saved = torch.load(path, weights_only=True) + restored.load_state_dict(saved['model']) + other.load_state_dict(saved['optimizer']) + for candidate, optim in ((model, optimizer), (restored, other)): + for p in candidate.parameters(): + if p.requires_grad: + p.grad = torch.full_like(p, .3) + set_learning_rates(optim, value, 2) + optim.step() + for p, resumed in zip(model.parameters(), restored.parameters()): + torch.testing.assert_close(resumed, p, rtol=0, atol=0) diff --git a/utils/training/tests/test_settings.py b/utils/training/tests/test_settings.py new file mode 100644 index 0000000..7c970f0 --- /dev/null +++ b/utils/training/tests/test_settings.py @@ -0,0 +1,139 @@ +from copy import deepcopy +import json +from pathlib import Path + +import pytest +import torch + +from utils.paths import REPO_ROOT +from utils.training import settings as shared +from utils.training.lora import LoRALinear, NoRALinear +from utils.training.optim import make_optimizer, set_learning_rates + + +def loaders(): + from ss_multiobj_depth.config import DEFAULT_TRAINING_CONFIG, load_config as ss + from slat_segvigen.config import load_config as seg + from slat_multiobj_shape.config import load_config as shape + return (lambda: ss(DEFAULT_TRAINING_CONFIG), seg, shape) + + +def test_all_training_presets_reference_one_recipe_without_inline_optimization_values(): + count = 0 + for package in ('ss_multiobj_depth', 'slat_segvigen', 'slat_multiobj_shape'): + for path in (REPO_ROOT / package / 'configs').glob('*.json'): + config = json.loads(path.read_text()) + if 'training' not in config: + continue + training = config['training'] + assert training['optimizer_config'] == shared.DEFAULT_OPTIMIZER_CONFIG, path + assert not shared.OPTIMIZATION_KEYS.intersection(training), path + count += 1 + assert count >= 3 + + +def test_all_three_defaults_use_the_same_actual_optimizer_groups_and_warmup(): + records = [load()['training'] for load in loaders()] + assert [record['cfg_dropout'] for record in records] == [.1, 0., .1] + for key in shared.OPTIMIZATION_KEYS | {'optimizer_profile'}: + assert all(record[key] == records[0][key] for record in records) + for training in records: + assert training['ema_decay'] == .999 + assert training['warmup'] == 500 + model = torch.nn.ModuleDict({'flow': NoRALinear(torch.nn.Linear(3, 4), rank=2, alpha=2), + 'head': torch.nn.Linear(4, 2), 'norm': torch.nn.LayerNorm(2)}) + optimizer = make_optimizer(model, training) + assert type(optimizer) is torch.optim.AdamW + groups = {group['name']: group for group in optimizer.param_groups} + assert set(groups) == {'new', 'new_no_decay', 'adapter'} + assert groups['new']['weight_decay'] == groups['adapter']['weight_decay'] == .01 + assert groups['new_no_decay']['weight_decay'] == 0. + assert all(group['betas'] == (.9, .95) for group in groups.values()) + assert all(group['lr'] == 1e-4 for group in groups.values()) + for update in (1, 250, 500, 501): + set_learning_rates(optimizer, training, update) + assert all(group['lr'] == pytest.approx(1e-4 * min(update / 500, 1.)) for group in groups.values()) + + +def test_one_recipe_edit_updates_every_stage_but_saved_snapshots_retain_resolved_values(tmp_path, monkeypatch): + from ss_multiobj_depth.config import load_config as ss + before = [load() for load in loaders()] + snapshot = tmp_path / 'snapshot.json' + snapshot.write_text(json.dumps(before[0])) + path = tmp_path / shared.DEFAULT_OPTIMIZER_CONFIG + path.parent.mkdir(parents=True) + recipe = json.loads((REPO_ROOT / shared.DEFAULT_OPTIMIZER_CONFIG).read_text()) + recipe.update(learning_rate=2e-4, ema_decay=.99, adapter_method='nora') + recipe['optimizer'].update(warmup_steps=37, adapter_learning_rate=8e-5) + path.write_text(json.dumps(recipe)) + monkeypatch.setattr(shared, 'REPO_ROOT', tmp_path) + for load in loaders(): + selected = load() + resolved = selected['training'] + assert selected['model'].get('adapter_method', selected['model'].get('mode')) == 'nora' + assert selected['model']['image_projection_adaptation'] == 'nora' + assert resolved['adapter_method'] == 'nora' + assert resolved['learning_rate'] == 2e-4 + assert resolved['ema_decay'] == .99 + assert resolved['warmup'] == resolved['optimizer']['warmup_steps'] == 37 + assert resolved['optimizer']['adapter_learning_rate'] == 8e-5 + assert resolved['optimizer_profile']['sha256'] != before[0]['training']['optimizer_profile']['sha256'] + assert 'optimizer_config' not in resolved + path.unlink() + assert ss(snapshot)['training'] == before[0]['training'] + assert ss(snapshot)['model'] == before[0]['model'] + + +@pytest.mark.parametrize('inline', ['learning_rate', 'weight_decay', 'warmup', 'optimizer', 'ema_decay', 'adapter_method']) +def test_shared_reference_rejects_inline_control_points(inline): + with pytest.raises(ValueError, match='inline optimization'): + shared.resolve_training_settings({'optimizer_config': shared.DEFAULT_OPTIMIZER_CONFIG, inline: 1}) + + +def test_historical_inline_settings_remain_literal(): + settings = {'learning_rate': 3e-5, 'warmup': 2, 'optimizer': {'betas': [.9, .999]}} + assert shared.resolve_training_settings(deepcopy(settings)) == settings + + +def test_shared_recipe_cannot_escape_its_owned_directory(): + with pytest.raises(ValueError, match='under utils/training/configs'): + shared.resolve_training_settings({'optimizer_config': '/tmp/outside.json'}) + + +@pytest.mark.parametrize('method', ['lora', 'nora']) +def test_one_recipe_constructs_the_selected_backbone_and_image_adapters_in_every_stage(tmp_path, monkeypatch, method): + from ss_multiobj_depth.model import install_adapters + from ss_multiobj_depth.tests.test_conditioning_training import native_flow + from slat_multiobj_shape.model import MultiObjectShape + from slat_multiobj_shape.tests.test_shape import tiny_native, normalization + from slat_segvigen import config as segmentation + + path = tmp_path / shared.DEFAULT_OPTIMIZER_CONFIG + path.parent.mkdir(parents=True) + recipe = json.loads((REPO_ROOT / shared.DEFAULT_OPTIMIZER_CONFIG).read_text()) + recipe['adapter_method'] = method + path.write_text(json.dumps(recipe)) + monkeypatch.setattr(shared, 'REPO_ROOT', tmp_path) + ss, seg, shape = [load() for load in loaders()] + dense = install_adapters(native_flow(), **ss['model']) + + def shape_flow(): + flow = tiny_native(32) + flow.proj_in_channels = 2048 + for block in flow.blocks: + block.cross_attn.proj_linear = torch.nn.Linear(2048, 24) + return flow + + sparse = MultiObjectShape(shape_flow(), normalization(), resolution=32, adaptation=shape['model']) + monkeypatch.setattr('models.pixal3d.load_frozen', lambda *_: shape_flow()) + monkeypatch.setattr(segmentation, 'configure_runtime', lambda _: None) + seg['device'] = 'cpu' + segmenter = segmentation.make_model(seg) + expected = LoRALinear if method == 'lora' else NoRALinear + for model in (dense, sparse, segmenter): + backbone = [module for name, module in model.named_modules() if name.endswith('.to_qkv')] + image = [module for name, module in model.named_modules() if name.endswith('.proj_linear')] + assert backbone and image + assert all(type(module) is expected for module in backbone + image) + assert all(not module.weight.requires_grad and not module.lora_B.any() for module in backbone + image) + assert all(module.bias.requires_grad for module in image) diff --git a/utils/training/tests/test_stage_ema.py b/utils/training/tests/test_stage_ema.py new file mode 100644 index 0000000..59b02d7 --- /dev/null +++ b/utils/training/tests/test_stage_ema.py @@ -0,0 +1,68 @@ +from pathlib import Path + +import pytest +import torch +from torch import nn + +from utils.training.ema import TrainableEMA +from utils.training.lora import NoRALinear +from utils.training.optim import make_optimizer +from utils.training.settings import DEFAULT_OPTIMIZER_CONFIG, resolve_training_settings + + +def network(stage): + flow = nn.ModuleDict({'adapter': NoRALinear(nn.Linear(3, 4), rank=2, alpha=2), 'head': nn.Linear(4, 2)}) + model = nn.ModuleDict({'flow': flow, 'conditioner': nn.Linear(1, 2)}) + model.checkpoint_schema = 'ema-stage-test-v1' + return model + + +@pytest.mark.parametrize('stage', ['ss', 'seg']) +def test_stage_checkpoints_preserve_raw_and_ema_weights_and_select_ema_at_inference(tmp_path, monkeypatch, stage): + if stage == 'ss': + from ss_multiobj_depth import train as owner + def save(path, model, optimizer, **kwargs): + return owner.save_checkpoint(path, model['flow'], model['conditioner'], optimizer, **kwargs) + def restore(path, model, **kwargs): + return owner.restore_checkpoint(path, model['flow'], model['conditioner'], **kwargs) + else: + from slat_segvigen import shared_checkpoint as owner + monkeypatch.setattr(owner, 'path_under', lambda path, _: Path(path)) + save, restore = owner.save_checkpoint, owner.restore_checkpoint + model = network(stage) + settings = resolve_training_settings({'optimizer_config': DEFAULT_OPTIMIZER_CONFIG, 'stage': 'flow'}) + config = {'device': 'cpu', 'training': settings} + optimizer = make_optimizer(model, settings) + ema = TrainableEMA(model, settings['ema_decay']) + for p in model.parameters(): + if p.requires_grad: + p.grad = torch.ones_like(p) + optimizer.step() + ema.update(model) + path = tmp_path / f'{stage}.pt' + save(path, model, optimizer, step=1, config=config, protocol={}, provenance={}, ema=ema) + raw = {name: p.detach().clone() for name, p in model.named_parameters() if p.requires_grad} + assert any(not torch.equal(value, ema.parameters[name]) for name, value in raw.items()) + for selection in ('auto', 'ema', 'raw'): + other = network(stage) + restored = restore(path, other, weights=selection) + assert restored['checkpoint_weights'] == ('raw' if selection == 'raw' else 'ema') + for name, p in other.named_parameters(): + if p.requires_grad: + expected = raw[name] if selection == 'raw' else ema.parameters[name] + torch.testing.assert_close(p, expected, rtol=0, atol=0) + other = network(stage) + other_ema = TrainableEMA(other, ema.decay) + restored = restore(path, other, optimizer=make_optimizer(other, settings), ema=other_ema) + assert restored['checkpoint_weights'] == 'raw' + assert other_ema.num_updates == 1 + for name, p in other.named_parameters(): + if p.requires_grad: + torch.testing.assert_close(p, raw[name], rtol=0, atol=0) + torch.testing.assert_close(other_ema.parameters[name], ema.parameters[name], rtol=0, atol=0) + historical = tmp_path / f'{stage}_historical.pt' + save(historical, model, optimizer, step=1, config={'device': 'cpu', 'training': {'stage': 'flow'}}, + protocol={}, provenance={}) + assert restore(historical, other, weights='auto')['checkpoint_weights'] == 'raw' + with pytest.raises(ValueError, match='no EMA state'): + restore(historical, other, weights='ema')