[ICML'26] PointDiT: Pixel-Space Diffusion for Monocular Geometry Estimation
Python
Initial release of PointDiT (ICML 2026)
Michael Niemeyera70b72766c6b
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..81d7ccb--- /dev/null+++ b/.gitignore@@ -0,0 +1,176 @@+# Byte-compiled / optimized / DLL files+__pycache__/+*.py[cod]+*$py.class++# C extensions+*.so++# Distribution / packaging+.Python+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+wheels/+share/python-wheels/+*.egg-info/+.installed.cfg+*.egg+MANIFEST++# PyInstaller+# Usually these files are written by a python script from a template+# before PyInstaller builds the exe, so as to inject date/other infos into it.+*.manifest+*.spec++# Installer logs+pip-log.txt+pip-delete-this-directory.txt++# Unit test / coverage reports+htmlcov/+.tox/+.nox/+.coverage+.coverage.*+.cache+nosetests.xml+coverage.xml+*.cover+*.py,cover+.hypothesis/+.pytest_cache/+cover/++# Translations+*.mo+*.pot++# Django stuff:+*.log+local_settings.py+db.sqlite3+db.sqlite3-journal++# Flask stuff:+instance/+.webassets-cache++# Scrapy stuff:+.scrapy++# Sphinx documentation+docs/_build/++# PyBuilder+.pybuilder/+target/++# Jupyter Notebook+.ipynb_checkpoints++# IPython+profile_default/+ipython_config.py++# pyenv+# For a library or package, you might want to ignore these files since the code is+# intended to run in multiple environments; otherwise, check them in:+# .python-version++# pipenv+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.+# However, in case of collaboration, if having platform-specific dependencies or dependencies+# having no cross-platform support, pipenv may install dependencies that don't work, or not+# install all needed dependencies.+#Pipfile.lock++# poetry+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.+# This is especially recommended for binary packages to ensure reproducibility, and is more+# commonly ignored for libraries.+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control+#poetry.lock++# pdm+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.+#pdm.lock+# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it+# in version control.+# https://pdm.fming.dev/latest/usage/project/#working-with-version-control+.pdm.toml+.pdm-python+.pdm-build/++# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm+__pypackages__/++# Celery stuff+celerybeat-schedule+celerybeat.pid++# SageMath parsed files+*.sage.py++# Environments+.env+.venv+env/+venv/+ENV/+env.bak/+venv.bak/++# Spyder project settings+.spyderproject+.spyproject++# Rope project settings+.ropeproject++# mkdocs documentation+/site++# mypy+.mypy_cache/+.dmypy.json+dmypy.json++# Pyre type checker+.pyre/++# pytype static type analyzer+.pytype/++# Cython debug symbols+cython_debug/++# PyCharm+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore+# and can be added to the global gitignore or merged into this file. For a more nuclear+# option (not recommended) you can uncomment the following to ignore the entire idea folder.+#.idea/++# data / weights / run artifacts (symlinks or local dirs, never committed)+datasets+datasets/+pretrained+pretrained/+outputs/+output_dir/+checkpoints/+generation/+results/+logs/+tmp/+third_party/diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..b16bd94--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,33 @@+# How to contribute++We'd love to accept your patches and contributions to this project.++## Before you begin++### Sign our Contributor License Agreement++Contributions to this project must be accompanied by a+[Contributor License Agreement](https://cla.developers.google.com/about) (CLA).+You (or your employer) retain the copyright to your contribution; this simply+gives us permission to use and redistribute your contributions as part of the+project.++If you or your current employer have already signed the Google CLA (even if it+was for a different project), you probably don't need to do it again.++Visit <https://cla.developers.google.com/> to see your current agreements or to+sign a new one.++### Review our community guidelines++This project follows+[Google's Open Source Community Guidelines](https://opensource.google/conduct/).++## Contribution process++### Code reviews++All submissions, including submissions by project members, require review. We+use GitHub pull requests for this purpose. Consult+[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more+information on using pull requests.diff --git a/DATASETS.md b/DATASETS.mdnew file mode 100644index 0000000..f663f89--- /dev/null+++ b/DATASETS.md@@ -0,0 +1,495 @@+# Dataset Preparation++This document describes the exact on-disk layout every dataset loader in this+codebase expects, so you can prepare the data for training and evaluation.++Training is **two-stage**:++- **Stage 1, pre-training** at `256×256` on a single dataset (**SceneNet-RGBD**).+ Driver scripts: `scripts/train_stage1_256_{b,l,h}.sh`.+- **Stage 2, fine-tuning** at `512×512` on an **11-dataset mixture**.+ Driver scripts: `scripts/train_stage2_512_{b,l,h}.sh`,+ which use the mixture config `dataloader/configs/res512mix.yaml`.++Evaluation is **zero-shot** on **7 real-captured datasets** (disjoint from training).++All paths below are relative to the repository root. In this repo `datasets/` is a+symlink to bulk storage; when releasing, replace it with a real directory (or your+own symlink) and place the data underneath as shown.++---++## Contents++- [Common conventions](#common-conventions)+- [Training datasets (12)](#training-datasets-12)+ - [Stage 1: SceneNet-RGBD](#1-scenenet-rgbd-stage-1)+ - [Stage 2 mixture (11 datasets)](#stage-2-mixture-11-datasets)+- [Evaluation datasets (7)](#evaluation-datasets-7)+- [Dataset mixture config format](#dataset-mixture-config-format)++---++## Common conventions++These hold across most datasets; per-dataset exceptions are called out below.++**Point clouds are computed on the fly.** No dataset stores point clouds. The+loader back-projects a depth map with camera intrinsics `K` into a camera-frame+point map at load time. So each sample needs three things: an **RGB image**, a+**depth map**, and **intrinsics**.++**Depth semantics, two flavors (do not mix them up):**+- **z-depth** (planar depth along the optical axis). Back-projected as+ `X=(u-cx)/fx·Z, Y=(v-cy)/fy·Z, Z=depth`. This is the common case.+- **ray-depth** (Euclidean distance along the pixel ray). Only **SceneNet-RGBD**+ uses this; it is back-projected with per-pixel unit rays.++**Depth storage, two families:**+- **Preprocessed `.npy`** float32, already in **meters**, z-depth. Used by most+ Stage-2 synthetic datasets (hypersim, urbansyn, synscapes, tartanair, eden,+ irs, dynamic_replica, mvssynth). You must convert the dataset's native depth+ (EXR / disparity / etc.) offline into per-frame `.npy` meters. Non-finite+ values are tolerated (zeroed at load).+- **Encoded `.png`** decoded at load time with a per-dataset scale/format:+ SceneNet (uint16 mm), VKITTI2 (uint16 cm), OmniWorld-Game (uint16 nonlinear+ disparity), TartanAirV2 (RGBA-packed float32), eval (MoGe log-16bit).++**Intrinsics, three sources:**+- **Per-frame `.npz`** with a 3×3 matrix under the key **`intrinsics`**+ (hypersim, urbansyn, synscapes, eden, irs, dynamic_replica, mvssynth).+- **Hardcoded constant** derived from a fixed camera model+ (SceneNet FOV; TartanAir `fx=fy=320,cx=320,cy=240` @640×480;+ TartanAirV2 `fx=fy=cx=cy=320` @640×640).+- **Per-sequence / per-split text or json** (VKITTI2 `intrinsic.txt`;+ OmniWorld-Game `camera/split_*.json`).++**No camera poses / extrinsics are ever read.** Everything is done in the camera+frame. Files like VKITTI2 `extrinsic.txt` or TartanAir pose files may exist but+are ignored.++**No sky-mask files.** Sky/far regions are handled numerically from depth+(thresholding + optional sky-dome), configured per dataset in the mixture YAML+(`handle_sky`, `use_sky_dome`, `sky_far_plane_value`). No segmentation file is+loaded (a `segmentation.png` present in some eval datasets is ignored).++**Discovery is cached.** The loader pickles the discovered file list per+`(dataset, split, subsample)` config. If you change files on disk, clear the+cache to force re-discovery.++**Train/test splits.** No curated holdout lists ship with the code. Every+mixture entry sets `num_test_scenes: 0` in its config, and the training scripts+pass `--split all`, so **all data is used for training**. To hold scenes out,+give a loader a `test_scenes_file` (one scene or sequence name per line, path+resolved relative to `dataloader/`) and run with `--split train`. Splitting is by+scene/sequence, never by frame except where noted.++---++## Training datasets (12)++Reproducing the paper's Table 4. **Note: the paper's "TartanGround" is named+`tartanairv2` in the code and configs.** Weights are the Stage-2 sampling+probabilities (independent of corpus size).++| # | Dataset (code name) | Domain | #Samples | Weight | `data_path` (config) |+|---|---|---|---:|---:|---|+| 1 | SceneNet-RGBD (`scenenet`) | indoor | 5,359,500 | 1.00¹ | `datasets/train/scenenet-rgbd` |+| 2 | Hypersim (`hypersim`) | indoor | 70,647 | 0.12 | `datasets/train/hypersim` |+| 3 | Virtual KITTI 2 (`vkitti2`) | driving | 42,520 | 0.14 | `datasets/train/vkitti2` |+| 4 | UrbanSyn (`urbansyn`) | urban driving | 7,539 | 0.05 | `datasets/train/urbansyn` |+| 5 | Synscapes (`synscapes`) | urban driving | 25,000 | 0.09 | `datasets/train/synscapes` |+| 6 | TartanAir (`tartanair`) | diverse | 306,637 | 0.10 | `datasets/train/tartanair` |+| 7 | OmniWorld-Game (`omniworldgame`) | diverse (game) | 1,024,252 | 0.19 | `datasets/train/omniworldgame` |+| 8 | EDEN (`eden`) | garden/outdoor | 368,663 | 0.05 | `datasets/train/eden` |+| 9 | IRS (`irs`) | indoor | 39,342 | 0.02 | `datasets/train/irs` |+| 10 | Dynamic Replica (`dynamic_replica`) | indoor | 150,900 | 0.03 | `datasets/train/dynamic_replica` |+| 11 | MVS-Synth (`mvssynth`) | urban | 12,000 | 0.06 | `datasets/train/mvssynth` |+| 12 | TartanGround (`tartanairv2`) | diverse | 4,170,178 | 0.15 | `datasets/train/tartanairv2` |++¹ SceneNet is Stage-1 only (single-dataset pre-training, weight 1.00). Datasets+2 to 12 form the Stage-2 mixture (weights sum to 1.00).++All 12 sources are **synthetic** and provide dense depth with known intrinsics.++---++### 1. SceneNet-RGBD (Stage 1)++- **Root:** `datasets/train/scenenet-rgbd`+- **Depth:** 16-bit PNG in **millimeters**, **ray-depth** (÷1000 → meters).+- **Intrinsics:** hardcoded from fixed FOV (hfov=60°, vfov=45°); no calib file.+- **Split:** directory-based (`train/` vs `val/`); no split file.++```+scenenet-rgbd/+├── train/+│ └── {scene}/ # e.g. 0, 1, ...+│ └── {trajectory}/ # e.g. 123+│ ├── photo/ # literal, required+│ │ └── {frame}.jpg # stem = frame id (0, 25, 50, ...)+│ └── depth/ # literal, required+│ └── {frame}.png # same stem; uint16 PNG, mm+└── val/+ └── {scene}/{trajectory}/{photo,depth}/...+```++- A trajectory is skipped unless **both** `photo/` and `depth/` exist and there+ is a matching `depth/{stem}.png` for each `photo/{stem}.jpg`.+- `split=all` scans both `train/` and `val/`. The Stage-1 script uses+ `--split all --dataset_name scenenet`.+- Native resolution 320×240. The SceneNet protobufs / `instances/` dirs are+ ignored, and only the `photo/` and `depth/` image folders matter.++---++### Stage 2 mixture (11 datasets)++Two structural sub-families recur; scan them once, then the per-dataset trees:++- **Flat "triplet" layout** (`rgb/`, `depth/`, `cam/` matched by filename stem):+ UrbanSyn, Synscapes, EDEN, IRS, MVS-Synth, and (per-camera) Dynamic Replica.+ RGB `.png`/`.jpg` + depth `.npy` (meters) + intrinsics `.npz` (`intrinsics`+ key). A frame is used **only if all three files exist**.+- **Sequence trees with fixed/text intrinsics:** TartanAir, TartanAirV2,+ VKITTI2, Hypersim, OmniWorld-Game.++---++#### 2. Hypersim++- **Root:** `datasets/train/hypersim`+- **Depth:** `.npy` float32 z-depth, **meters** (native ray-distance already+ converted during preprocessing).+- **Intrinsics:** per-frame `.npz`, key `intrinsics` (3×3). Variable per frame.+- **Split:** by top-level scene, if a `test_scenes_file` of scene names+ (e.g. `ai_001_004`) is supplied. None ships, so all scenes are used.++```+hypersim/+└── {scene}/ # ai_XXX_YYY, e.g. ai_001_001+ └── {cam}/ # cam_00, cam_01, ...+ ├── {frame:06d}_rgb.png+ ├── {frame:06d}_depth.npy # z-depth, meters+ └── {frame:06d}_cam.npz # key 'intrinsics' = 3x3 K+```++- Exactly two directory levels (scene → cam) before frame files. A frame is kept+ only if all three `_rgb.png` / `_depth.npy` / `_cam.npz` exist.+- Expects **preprocessed** data in the layout above, not raw Hypersim `.hdf5`. The+ conversion (tone-mapped RGB, OpenGL projection matrix → pinhole `K`, distance →+ planar z-depth) has to be reproduced from the official Hypersim release; the+ conversion scripts are not part of this release.++---++#### 3. Virtual KITTI 2 (`vkitti2`)++- **Root:** `datasets/train/vkitti2` (official tars already+ extracted and merged: rgb + depth + textgt).+- **Depth:** 16-bit PNG in **centimeters**, z-depth (÷100 → meters), read with+ `cv2.IMREAD_ANYDEPTH`. Sky encoded as 65535 cm (655.35 m), removed by+ `max_depth`.+- **Intrinsics:** per `(scene, variation)` `intrinsic.txt` (header ++ `frame cameraID fx fy cx cy` rows).+- **Split:** camera-sequence level, if a `test_scenes_file` of+ `{scene}/{variation}/{camera}` names is supplied. None ships, so all are used.++```+vkitti2/+└── Scene{NN}/ # Scene01, Scene02, Scene06, Scene18, Scene20+ └── {variation}/ # clone, fog, rain, morning, sunset, overcast,+ │ # 15-deg-left/right, 30-deg-left/right+ ├── intrinsic.txt # per-frame per-camera K table+ ├── extrinsic.txt # present but UNUSED+ └── frames/+ ├── rgb/Camera_{0,1}/rgb_{frame:05d}.jpg+ └── depth/Camera_{0,1}/depth_{frame:05d}.png # uint16, cm+```++- Scene dirs must start with `Scene`. The depth path is derived from the RGB+ path by swapping `/rgb/`→`/depth/`, so the depth tree must **mirror** the rgb+ tree exactly (same `Camera_{id}` folders and frame ids).++---++#### 4. UrbanSyn++- **Root:** `datasets/train/urbansyn` (preprocessed to 512×1024).+- **Depth:** `.npy` float32 z-depth, **meters** (already scaled).+- **Intrinsics:** per-frame `.npz`, key `intrinsics`.+- **Split:** frame-level uniform sampling (`num_test_scenes` = #test frames).++```+urbansyn/+├── rgb/ rgb_{frame:04d}.png+├── depth/ rgb_{frame:04d}.npy # z-depth, meters+└── cam/ rgb_{frame:04d}.npz # key 'intrinsics'+```++- **Filename coupling:** depth/cam reuse the **full** rgb stem including the+ `rgb_` prefix (`rgb_0001.png` → `rgb_0001.npy` → `rgb_0001.npz`).+- The runtime loader reads only the precomputed `.npz`, and the+ the intrinsics are baked into the per-frame `.npz` by the preprocessing script.++---++#### 5. Synscapes++- **Root:** `datasets/train/synscapes`+- **Depth:** `.npy` float32 z-depth, **meters** (preprocessed from EXR).+- **Intrinsics:** per-frame `.npz`, key `intrinsics`.+- **Split:** frame-level (uniform sampling, or a text list of frame ids).++```+synscapes/+├── rgb/ {frame}.png # bare stem, e.g. 1.png ... 25000.png+├── depth/ {frame}.npy # z-depth, meters+└── cam/ {frame}.npz # key 'intrinsics'+```++- Flat triplet layout; stems must match exactly across `rgb/`, `depth/`, `cam/`.+ Only `.png` RGB is discovered.++---++#### 6. TartanAir++- **Root:** `datasets/train/tartanair` (already unzipped).+- **Depth:** `.npy` float32 z-depth, **meters**.+- **Intrinsics:** **hardcoded** `fx=fy=320, cx=320, cy=240` for 640×480.+- **Split:** sequence level, if a `test_scenes_file` of+ `{env}/{difficulty}/{trajectory}` names is supplied. None ships, so all are used.++```+tartanair/+└── {scene}/ # abandonedfactory, amusement, ...+ └── {difficulty}/ # Easy, Hard+ └── {sequence}/ # P000, P001, ...+ ├── image_left/{frame:06d}_left.png+ └── depth_left/{frame:06d}_left_depth.npy # z-depth, meters+```++- Strictly 3 directory levels (scene → difficulty → sequence). Only the **left**+ camera is used; `image_right/`/`depth_right/` are ignored. Every RGB frame must+ have its `_left_depth.npy` twin.++---++#### 7. OmniWorld-Game (`omniworldgame`)++- **Root:** `datasets/train/omniworldgame`+- **Depth:** 16-bit PNG, **nonlinear disparity-like** encoding decoded to metric+ z-depth (near=1.0, far=1000.0; see `load_omniworldgame_depth`). Not a plain+ uint16/1000 map.+- **Intrinsics:** per-split json (`camera/split_{idx}.json`) with a per-frame+ `focals` list plus scalar `cx`, `cy` (fx=fy=focals[i]).+- **Split:** scene level (manual list, or uniform sampling).++```+omniworldgame/+├── videos/OmniWorld-Game/ # literal "OmniWorld-Game" (case + hyphen)+│ └── {scene}/color/{frame:06d}.png # RGB+└── annotations/OmniWorld-Game/+ └── {scene}/+ ├── split_info.json # REQUIRED: {'split_num': N, 'split': [[frame ids], ...]}+ ├── depth/{frame:06d}.png # uint16 nonlinear disparity+ └── camera/split_{idx}.json # {'focals': [...], 'cx': ..., 'cy': ...}+```++- RGB lives under `videos/`, everything else under `annotations/`. The inner+ literal segment `OmniWorld-Game` is required. Frame filenames are the integer+ indices listed in `split_info.json`, formatted `%06d`, shared by color and depth.++---++#### 8. EDEN++- **Root:** `datasets/train/eden`+- **Depth:** `.npy` float32 z-depth, **meters**.+- **Intrinsics:** per-frame `.npz`, key `intrinsics`.+- **Split:** sequence level (a "sequence" = one `{scene_id}_{lighting}` dir).++```+eden/+└── {scene_id}_{lighting}/ # lighting ∈ {clear, cloudy, overcast, sunset, twilight}+ ├── rgb/ {frame}.png # e.g. A_0001.png+ ├── depth/ {frame}.npy # z-depth, meters+ └── cam/ {frame}.npz # key 'intrinsics'+```++- Each lighting variant is its own sequence. A dir is recognized only if all of+ `rgb/`, `depth/`, `cam/` exist; stems must match across the three.++---++#### 9. IRS++- **Root:** `datasets/train/irs`+- **Depth:** `.npy` float32 z-depth, **meters** (preprocessed from disparity EXR;+ depth-edge pixels pre-filtered, hence `filterdepthedge`).+- **Intrinsics:** per-frame `.npz`, key `intrinsics` (`fx=fy=480`, principal+ point at image center).+- **Split:** sequence level; default config uses all sequences (`num_test_scenes: 0`).++```+irs/+└── {sequence}/ # e.g. ArchVizInterior03Data, ConvenienceStore+ ├── rgb/ {frame:05d}.png # 5-digit ids, e.g. 00000.png+ ├── depth/ {frame:05d}.npy # z-depth, meters+ └── cam/ {frame:05d}.npz # key 'intrinsics'+```++- Expects **preprocessed** IRS (not the raw disparity EXR release).++---++#### 10. Dynamic Replica (`dynamic_replica`)++- **Root:** `datasets/train/dynamic_replica` (CUT3R-style processed data).+- **Depth:** `.npy` float32 z-depth, **meters**.+- **Intrinsics:** per-frame `.npz`, key `intrinsics` (≈`fx=fy=700, cx=640,+ cy=360` @1280×720).+- **Split:** by top-level `train`/`valid`/`test` subdir.++```+dynamic_replica/+└── {split}/ # train | valid | test+ └── {sequence}/+ └── left/ # only 'left' is used ('right' ignored)+ ├── rgb/ {frame_id}.png # frame_id = float timestamp, e.g. 0.0, 0.03333...+ ├── depth/ {frame_id}.npy # z-depth, meters+ └── cam/ {frame_id}.npz # key 'intrinsics'+```++- Frame ids are **float-timestamp strings** (sorted numerically). Only `left/` is+ consumed. A frame is kept only if depth `.npy` and cam `.npz` both exist.++---++#### 11. MVS-Synth (`mvssynth`)++- **Root:** `datasets/train/mvssynth` (the former `GTAV_720`+ contents sit directly under this root)+- **Depth:** `.npy` float32 z-depth in **centimeters** (÷100 → meters).+ *(Note: unlike the other `.npy` datasets, this one is in cm, not meters.)*+- **Intrinsics:** per-frame `.npz`, key `intrinsics`.+- **Split:** sequence level (manual list or uniform sampling).++```+mvssynth/+└── {sequence}/ # e.g. 0000, 0001, ...+ ├── rgb/ {frame}.jpg # RGB is .jpg here+ ├── depth/ {frame}.npy # z-depth, CENTIMETERS+ └── cam/ {frame}.npz # key 'intrinsics'+```++- RGB glob is literal `*.jpg`. Preprocessed from MVS-Synth EXR into per-frame+ cm-depth `.npy` + intrinsics `.npz`.++---++#### 12. TartanGround / TartanAirV2 (`tartanairv2`)++- **Root:** `datasets/train/tartanairv2` (already unzipped).+- **Depth:** **4-channel RGBA 8-bit PNG whose 4 bytes per pixel are a packed+ little-endian float32** (meters), z-depth. Decode with+ `cv2.imread(..., IMREAD_UNCHANGED).view("<f4")`. Standard uint16 readers will+ **not** work.+- **Intrinsics:** **hardcoded** `fx=fy=cx=cy=320` for 640×640.+- **Split:** `(trajectory, camera)` level; default config uses all data+ (`num_test_scenes: 0`).++```+tartanairv2/+└── {environment}/ # e.g. AbandonedFactory+ └── Data_{difficulty}/ # Data_easy, Data_hard+ └── {trajectory}/ # P000, P001, ...+ ├── image_{cam}/{frame:06d}_{cam}.png+ └── depth_{cam}/{frame:06d}_{cam}_depth.png # RGBA-packed float32, meters+```++- 12 camera views `{cam}`: `lcam_{front,back,left,right,top,bottom}` and+ `rcam_{front,back,left,right,top,bottom}`.+- A `(trajectory, camera)` is enumerated only if both `image_{cam}/` and+ `depth_{cam}/` exist. Depth is matched by string construction, so every RGB+ frame must have its exact `{frame}_{cam}_depth.png` twin.++---++## Evaluation datasets (7)++Reproducing the paper's Table 5. All are **real-captured** and disjoint from+training. "Boundary" = scale-invariant boundary-F1 additionally reported.++| Dataset | Domain | #Samples | Boundary |+|---|---|---:|:---:|+| DIODE | indoor + outdoor | 771 | |+| KITTI | outdoor (driving) | 652 | |+| NYUv2 | indoor | 654 | |+| ETH3D | indoor + outdoor | 454 | |+| HAMMER | indoor (multi-modal) | 775 | ✓ |+| iBims-1 | indoor | 100 | ✓ |+| Booster | indoor (transparent/specular) | 38 | ✓ |+| **Total** | | **3,444** | |++**All 7 sets are available pre-processed**, one zip per dataset, 2.7 GB total:++> **[PointDiT evaluation sets (Google Drive)](https://drive.google.com/drive/folders/1RklLC1VFCBtFra_y29mp_m3eVvy7C9bg?usp=sharing)**++Nothing needs converting. Download the zips into `datasets/eval/` and unpack:++```bash+mkdir -p datasets/eval+# download Booster.zip DIODE.zip ETH3D.zip HAMMER.zip iBims-1.zip KITTI.zip+# NYUv2.zip into datasets/eval/ from the link above, then:+cd datasets/eval && unzip '*.zip' # one zip per dataset+```++---++## Dataset mixture config format++The Stage-2 mixture is a YAML file (`dataloader/configs/res512mix.yaml`)+passed via `--dataset_config`. Each entry configures one dataset:++```yaml+finetune_highres_mode: true+finetune_target_height: 512+finetune_target_crop: 512+img_size: 512++datasets:+ - name: hypersim # selects the loader (must match a code name above)+ data_path: datasets/train/hypersim+ max_depth: 30.0 # depth validity threshold (meters)+ weight: 0.12 # sampling probability in the mixture+ handle_sky: false # sky handling (outdoor scenes set true)+ use_sky_dome: false+ sky_loss_weight: 0.0+ sky_far_plane_value: 3.0 # (sky datasets) far-plane depth for sky dome+ remove_outliers: true # geometric outlier removal+ outlier_threshold: 3.0+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false+ clamp_max_depth: null+ num_test_scenes: 0 # 0 = use all data for training+ # ... one block per dataset+```++- **`name`** must match one of the code names in the tables above; it selects the+ `_find_and_split_data_<name>` discovery routine.+- **`data_path`** points at that dataset's root (the trees documented above).+- **`weight`** is the mixture sampling probability (weights across datasets should+ sum to ~1.0). **`max_depth`**, sky handling, and outlier removal are training+ filters, not on-disk requirements.++For single-dataset Stage-1 (SceneNet) the script uses the CLI flags+`--dataset_name scenenet --data_path ... --split all` instead of a mixture YAML+(see `dataloader/configs/scenenet.yaml` for the equivalent single-entry config).++Note that the per-dataset keys in a mixture YAML take precedence: the matching CLI+flags (`--max_depth`, `--handle_sky`, `--remove_outliers`,+`--compute_scale_factor_only_valid`, …) are ignored whenever `--dataset_config` is+passed. `sky_loss_weight` is the one key that is parsed but not forwarded to the+loader. Set the sky loss from the CLI with `--sky_loss_weight`.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/MODELS.md b/MODELS.mdnew file mode 100644index 0000000..0f53a25--- /dev/null+++ b/MODELS.md@@ -0,0 +1,22 @@+# Model Zoo++Six checkpoints: each of PointDiT-B / L / H at 256x256 and 512x512 resolutions.++[Download the weights (Google Drive)](https://drive.google.com/drive/folders/1ctCGxi-WN1P5GpiteK41SXwLgQ1z5fEc?usp=drive_link) and symlink (or move) them under `pretrained/`:++```bash+ln -s YOUR_MODEL_PATH pretrained+```++The launch scripts expect the checkpoints directly in `pretrained/`, under these exact+filenames:++```+pretrained/+├── pointditb-256-scenenet.pth # PointDiT-B, 256, Stage 1+├── pointditl-256-scenenet.pth # PointDiT-L, 256, Stage 1+├── pointdith-256-scenenet.pth # PointDiT-H, 256, Stage 1+├── pointditb-512.pth # PointDiT-B, 512, Stage 2+├── pointditl-512.pth # PointDiT-L, 512, Stage 2+└── pointdith-512.pth # PointDiT-H, 512, Stage 2+```diff --git a/README.md b/README.mdnew file mode 100644index 0000000..ed6ffa2--- /dev/null+++ b/README.md@@ -0,0 +1,151 @@+<p align="center">+ <h1 align="center">PointDiT: Pixel-Space Diffusion for Monocular Geometry Estimation</h1>+ <p align="center">+ <a href="https://haofeixu.github.io/">Haofei Xu</a><sup>1,2,3</sup> ·+ <a href="https://rundiwu.github.io/">Rundi Wu</a><sup>1</sup> ·+ <a href="https://henzler.github.io/">Philipp Henzler</a><sup>1</sup> ·+ <a href="https://scholar.google.com/citations?user=XwzlnZoAAAAJ">Nikolai Kalischek</a><sup>1</sup> ·+ <a href="https://scholar.google.com/citations?user=vMcsUNAAAAAJ">Michael Oechsle</a><sup>1</sup>+ <br>+ <a href="https://scholar.google.com/citations?user=bERItx8AAAAJ">Fabian Manhardt</a><sup>1</sup> ·+ <a href="https://people.inf.ethz.ch/marc.pollefeys/">Marc Pollefeys</a><sup>2,4</sup> ·+ <a href="http://www.cvlibs.net/">Andreas Geiger</a><sup>3,5</sup> ·+ <a href="https://federicotombari.github.io/">Federico Tombari</a><sup>1,6</sup> ·+ <a href="https://m-niemeyer.github.io/">Michael Niemeyer</a><sup>1</sup>+ </p>+ <p align="center">+ <sup>1</sup>Google <sup>2</sup>ETH Zurich <sup>3</sup>University of Tübingen, Tübingen AI Center <sup>4</sup>Microsoft <sup>5</sup>KE:SAI <sup>6</sup>TUM+ </p>+ <h3 align="center">ICML 2026</h3>+ <h3 align="center">+ <a href="https://arxiv.org/abs/2607.02515">Paper</a> | <a href="https://haofeixu.github.io/pointdit/">Project Page</a> | <a href="MODELS.md">Models</a>+ </h3>+</p>++<p align="center">+ <a href="https://haofeixu.github.io/assets/pointdit.mp4">+ <img src="assets/teaser.gif" alt="PointDiT teaser" width="100%">+ </a>+</p>++PointDiT is a minimalist pixel-space Diffusion Transformer for monocular geometry estimation. It is a plain ViT that denoises raw 3D point map patches directly, conditioned on image tokens from a frozen pre-trained DINOv3: no point map tokenizer, no latent diffusion, no hybrid architecture, and no intricate loss formulation.++## Installation++This codebase is developed with Python 3.12, PyTorch 2.7.0, and CUDA 12.8.++We recommend setting up a virtual environment (e.g., [conda](https://docs.anaconda.com/miniconda/) or [venv](https://docs.python.org/3/library/venv.html)) before installation:++```bash+# conda+conda create -y -n pointdit python=3.12+conda activate pointdit++# or venv+# python -m venv /path/to/venv/pointdit+# source /path/to/venv/pointdit/bin/activate++# torch 2.7.0, cuda 12.8+pip install torch==2.7.0 torchvision==0.22.0 --index-url https://download.pytorch.org/whl/cu128++pip install -r requirements.txt++# DINOv3 encoder code (not vendored; built with torch.hub from a local checkout)+git clone https://github.com/facebookresearch/dinov3.git third_party/dinov3+```++All commands are run from the repository root, and the launch scripts in [scripts/](scripts). To check the installation:++```bash+bash run.sh # CPU-only smoke test: no GPU, checkpoint or dataset needed+```++The DINOv3 weights are gated and needed only for training; the released checkpoints already+carry the encoder. To train, request access on the+[official DINOv3 repository](https://github.com/facebookresearch/dinov3) and place the weights+under `pretrained/dinov3/` with their exact upstream filenames.++## Model Zoo++Pre-trained models are available in the [Model Zoo](MODELS.md), at `256×256` and `512×512` for+each of PointDiT-B / L / H.++Download the weights and place (or symlink) them in the `pretrained` directory:++```bash+ln -s YOUR_MODEL_PATH pretrained+```++## Demo++Check [scripts/demo_l_512.sh](scripts/demo_l_512.sh) for running our pre-trained models on your own images, with no ground truth and no camera intrinsics required. Set `IMAGE_DIR` at the top of the script and run it:++```bash+bash scripts/demo_l_512.sh+```++Any `.jpg`/`.png` files work, and nested folders are fine, since the loader globs recursively. Results are written to `generation/`.+++## Dataset Preparation++See [DATASETS.md](DATASETS.md) for detailed instructions on preparing the 12 training datasets and the 7 zero-shot evaluation datasets. We have provided the download link for the 7 evaluation datasets in [DATASETS.md](DATASETS.md).++Symlink the prepared datasets to the `datasets` directory:++```bash+ln -s YOUR_DATASET_PATH datasets+```++Point clouds are never stored on disk: the training loader reads `(RGB, depth, intrinsics)` and back-projects on the fly.+++## Evaluation++Evaluation scripts are also provided in [scripts/](scripts) for reproducing the results in our paper:++```bash+bash scripts/eval_l_512.sh+```++Swap `l` for `b` or `h`, and `512` for `256`. Each script's header comment lists the numbers it should reproduce.++## Training++PointDiT is trained in two stages: (1) `256×256` pre-training on SceneNet-RGBD and (2) `512×512` fine-tuning on the 11-dataset mixture.++```bash+bash scripts/train_stage1_256_b.sh+bash scripts/train_stage2_512_b.sh+```++The training scripts in [scripts/](scripts) contain the exact commands and hyperparameters used for the experiments in our paper. Please refer to them for detailed configurations. Before training, you need to download the DINOv3 weights (see [Installation](#installation)) and prepare the datasets per [DATASETS.md](DATASETS.md).+++## License++This is not an officially supported Google product. This project is not+eligible for the [Google Open Source Software Vulnerability Rewards+Program](https://bughunters.google.com/open-source-security).++This codebase is released under the Apache License 2.0 (see the `LICENSE` file at the root of+the repository). It also contains code derived from other open-source projects, which+remains under its original licenses; see [THIRD_PARTY_NOTICES](THIRD_PARTY_NOTICES) for the+full list and notices.++## Citation++If you find this work useful, please consider citing:++```bibtex+@inproceedings{xu2026pointdit,+ title={PointDiT: Pixel-Space Diffusion for Monocular Geometry Estimation},+ author={Xu, Haofei and Wu, Rundi and Henzler, Philipp and Kalischek, Nikolai and Oechsle, Michael and Manhardt, Fabian and Pollefeys, Marc and Geiger, Andreas and Tombari, Federico and Niemeyer, Michael},+ booktitle={ICML},+ year={2026}+}+```++## Acknowledgements++Our codebase builds upon several excellent open-source projects: [JiT](https://github.com/LTH14/JiT), [DINOv3](https://github.com/facebookresearch/dinov3), [MoGe](https://github.com/microsoft/MoGe), [Depth Pro](https://github.com/apple/ml-depth-pro) and [utils3d](https://github.com/EasternJournalist/utils3d). We thank all the authors for their great work.diff --git a/THIRD_PARTY_NOTICES b/THIRD_PARTY_NOTICESnew file mode 100644index 0000000..990dcf0--- /dev/null+++ b/THIRD_PARTY_NOTICES@@ -0,0 +1,124 @@+PointDiT: Pixel-Space Diffusion for Monocular Geometry Estimation+=================================================================++This directory is released under the Apache License 2.0 of the enclosing+repository (see the LICENSE file at the repository root).++It also contains code derived from the third-party projects listed below, which+remain subject to their own licences. The notices reproduced here satisfy those+licences' attribution requirements.+++-----------------------------------------------------------------------+1. JiT -- https://github.com/LTH14/JiT+ MIT License, Copyright (c) 2025 Tianhong Li+-----------------------------------------------------------------------++This project began as a fork of JiT, which contributed the pixel-space diffusion+transformer backbone, the training loop and the command-line interface. Files+substantially derived from it: main.py, engine.py, model.py,+denoiser.py, util/misc.py, util/lr_sched.py, util/model_util.py.++ Permission is hereby granted, free of charge, to any person obtaining a copy+ of this software and associated documentation files (the "Software"), to deal+ in the Software without restriction, including without limitation the rights+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+ copies of the Software, and to permit persons to whom the Software is+ furnished to do so, subject to the following conditions:++ The above copyright notice and this permission notice shall be included in all+ copies or substantial portions of the Software.++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+ SOFTWARE.+++-----------------------------------------------------------------------+2. MoGe -- https://github.com/microsoft/MoGe+ MIT License, Copyright (c) Microsoft Corporation+-----------------------------------------------------------------------++The evaluation protocol and the affine alignment code are adapted from MoGe:+metrics/alignment.py, metrics/compute_metrics.py, and the depth I/O helper+`read_depth` in dataloader/eval_depth.py. The pre-processed evaluation datasets+are also distributed by the MoGe authors. MIT terms as reproduced in section 1+above, with copyright held by Microsoft Corporation.+++-----------------------------------------------------------------------+3. utils3d -- https://github.com/EasternJournalist/utils3d+ MIT License, Copyright (c) Ruicheng Wang+-----------------------------------------------------------------------++The mask-aware resizing and tensor helpers used by the metrics are adapted from+utils3d: metrics/masked_resize.py, metrics/utils.py, metrics/helpers.py. MIT+terms as reproduced in section 1 above.+++-----------------------------------------------------------------------+4. Depth Pro -- https://github.com/apple/ml-depth-pro+ Copyright (C) 2024 Apple Inc. All Rights Reserved.+-----------------------------------------------------------------------++metrics/boundary_metrics.py implements the scale-invariant boundary F1 metric and+is vendored from Depth Pro.++ Redistribution and use in source and binary forms, with or without+ modification, are permitted provided that the following conditions are met:++ 1. Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++ 2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++ 3. Neither the name of the copyright holder nor the names of its contributors+ may be used to endorse or promote products derived from this software+ without specific prior written permission.++ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+++-----------------------------------------------------------------------+5. MMDetection -- https://github.com/open-mmlab/mmdetection+ Apache License 2.0, Copyright (c) OpenMMLab+-----------------------------------------------------------------------++publish_model.py is adapted from MMDetection's+tools/model_converters/publish_model.py and retains its OpenMMLab header.+Apache 2.0, the same licence as this repository.+++-----------------------------------------------------------------------+6. SiT and Lightning-DiT+ https://github.com/willisma/SiT (MIT), https://github.com/hustvl/LightningDiT+-----------------------------------------------------------------------++Transformer design details in model.py follow SiT and Lightning-DiT, as+recorded in that file's header. Reached via the JiT fork in section 1.+++-----------------------------------------------------------------------+Note on DINOv3+-----------------------------------------------------------------------++PointDiT conditions on a frozen DINOv3 encoder. No DINOv3 code or weights are+vendored in this directory: the encoder is loaded from a user-supplied local+checkout of https://github.com/facebookresearch/dinov3, and its LVD-1689M+weights are access-gated by Meta and must be obtained separately under the+DINOv3 License Agreement. See README.md for setup.diff --git a/assets/demo/sample.png b/assets/demo/sample.pngnew file mode 100644index 0000000..693d3efBinary files /dev/null and b/assets/demo/sample.png differdiff --git a/assets/teaser.gif b/assets/teaser.gifnew file mode 100644index 0000000..2437c0aBinary files /dev/null and b/assets/teaser.gif differdiff --git a/dataloader/configs/res512mix.yaml b/dataloader/configs/res512mix.yamlnew file mode 100644index 0000000..06112db--- /dev/null+++ b/dataloader/configs/res512mix.yaml@@ -0,0 +1,261 @@+# PointDiT Stage 2: 512x512 fine-tuning mixture (the released 512 checkpoints).+#+# 11 synthetic datasets. `weight` is a sampling probability, independent of corpus+# size; the weights below sum to 1.00. NOTE: `tartanairv2` is the dataset the paper+# calls TartanGround. Each `data_path` is datasets/train/<name>; see ../../DATASETS.md+# for the layout each loader expects under that root.+#+# Domain balance:+# outdoor ground-level 58% (vkitti2 + urbansyn + synscapes + omniworldgame + eden + mvssynth)+# aerial 25% (tartanair + tartanairv2)+# indoor 17% (hypersim + irs + dynamic_replica)+#+# `sky_loss_weight` below is parsed but not forwarded to the loader -- set the sky+# loss from the CLI with --sky_loss_weight.++finetune_highres_mode: true+finetune_target_height: 512+finetune_target_crop: 512+img_size: 512++datasets:+ - name: hypersim+ data_path: datasets/train/hypersim+ max_depth: 30.0+ weight: 0.12++ # Sky handling (mostly indoor scenes)+ handle_sky: false+ use_sky_dome: false+ sky_loss_weight: 0.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0++ - name: vkitti2+ data_path: datasets/train/vkitti2+ max_depth: 100.0+ weight: 0.14++ # Sky handling for outdoor scenes+ handle_sky: true+ use_sky_dome: true+ sky_loss_weight: 0.01+ sky_far_plane_value: 3.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0++ - name: urbansyn+ data_path: datasets/train/urbansyn+ max_depth: 100.0+ weight: 0.05++ # Sky handling for outdoor urban scenes+ handle_sky: true+ use_sky_dome: true+ sky_loss_weight: 0.01+ sky_far_plane_value: 3.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0++ - name: synscapes+ data_path: datasets/train/synscapes+ max_depth: 100.0+ weight: 0.09++ # Sky handling for outdoor/urban driving scenes+ handle_sky: true+ use_sky_dome: true+ sky_loss_weight: 0.01+ sky_far_plane_value: 3.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0++ - name: tartanair+ data_path: datasets/train/tartanair+ max_depth: 100.0+ weight: 0.10++ # Sky handling (outdoor scenes with sky)+ handle_sky: true+ use_sky_dome: true+ sky_loss_weight: 0.01+ sky_far_plane_value: 3.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0++ - name: omniworldgame+ data_path: datasets/train/omniworldgame+ max_depth: 100.0+ weight: 0.19++ # Sky handling for outdoor game environments+ handle_sky: true+ use_sky_dome: true+ sky_loss_weight: 0.01+ sky_far_plane_value: 3.0++ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0++ - name: eden+ data_path: datasets/train/eden+ max_depth: 100.0+ weight: 0.05++ # Sky handling for outdoor scenes+ handle_sky: true+ use_sky_dome: true+ sky_loss_weight: 0.01+ sky_far_plane_value: 3.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0++ - name: irs+ data_path: datasets/train/irs+ max_depth: 30.0+ weight: 0.02++ # Sky handling: DISABLED (indoor synthetic scenes)+ handle_sky: false+ use_sky_dome: false+ sky_loss_weight: 0.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation (synthetic data)+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ # Depth clamping+ clamp_max_depth: null++ # No train/test split - use all data for training+ num_test_scenes: 0++ - name: dynamic_replica+ data_path: datasets/train/dynamic_replica+ max_depth: 10.0+ weight: 0.03++ # Sky handling: DISABLED (indoor synthetic scenes)+ handle_sky: false+ use_sky_dome: false+ sky_loss_weight: 0.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation (synthetic data)+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ # Depth clamping+ clamp_max_depth: null++ - name: mvssynth+ data_path: datasets/train/mvssynth+ max_depth: 100.0+ weight: 0.06++ # Sky handling for outdoor/urban scenes (GTAV-based synthetic)+ handle_sky: true+ use_sky_dome: true+ sky_loss_weight: 0.01+ sky_far_plane_value: 3.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0++ - name: tartanairv2+ data_path: datasets/train/tartanairv2+ max_depth: 100.0+ weight: 0.15++ # Sky handling (outdoor scenes with sky)+ handle_sky: true+ use_sky_dome: true+ sky_loss_weight: 0.01+ sky_far_plane_value: 3.0++ # Outlier removal+ remove_outliers: true+ outlier_threshold: 3.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++ clamp_max_depth: null+ num_test_scenes: 0diff --git a/dataloader/configs/scenenet.yaml b/dataloader/configs/scenenet.yamlnew file mode 100644index 0000000..3f57b28--- /dev/null+++ b/dataloader/configs/scenenet.yaml@@ -0,0 +1,21 @@+# SceneNet-RGBD Single Dataset Configuration+# For indoor scenes without sky++datasets:+ - name: scenenet+ data_path: datasets/pointcloud-raw/scenenet-rgbd/+ max_depth: 10.0+ weight: 1.0++ # Sky handling (not needed for indoor scenes)+ handle_sky: false+ use_sky_dome: false+ sky_loss_weight: 0.0++ # Scale factor computation+ compute_scale_factor_only_valid: true+ compute_scale_factor_use_std: false++# Shared training settings+img_size: 256+resize_height: 256diff --git a/dataloader/eval_depth.py b/dataloader/eval_depth.pynew file mode 100644index 0000000..f56bae1--- /dev/null+++ b/dataloader/eval_depth.py@@ -0,0 +1,431 @@+# coding=utf-8++"""+Evaluation dataloader for depth data in MoGe format.++Reads logarithmic 16-bit PNG depth images with near/far metadata,+and returns raw (unnormalized) pointmaps for evaluation.+"""++import io+import json+import os+from pathlib import Path+from typing import Union, List++import numpy as np+import torch+from PIL import Image+from torch.utils.data import Dataset+++def read_depth(path: Union[str, os.PathLike, io.IOBase]) -> np.ndarray:+ """+ Read a depth image in MoGe logarithmic 16-bit PNG format.++ The depth is stored in logarithmic scale:+ - 0: NaN (unknown/invalid)+ - 1-65534: logarithmically encoded depth values+ - 65535: Infinity++ Returns:+ float32 depth array of shape (H, W) in meters.+ """+ if isinstance(path, (str, os.PathLike)):+ data = Path(path).read_bytes()+ else:+ data = path.read()++ pil_image = Image.open(io.BytesIO(data))+ near = float(pil_image.info.get('near'))+ far = float(pil_image.info.get('far'))+ depth = np.array(pil_image)++ # Mark special values+ mask_nan, mask_inf = depth == 0, depth == 65535++ # Decode logarithmic scale: depth = near^(1-t) * far^t+ t = (depth.astype(np.float32) - 1) / 65533+ depth = near ** (1 - t) * far ** t++ # Legacy support for depth units+ if 'unit' in pil_image.info:+ unit = float(pil_image.info.get('unit'))+ depth = depth * unit++ # Apply special value masks+ depth[mask_nan] = np.nan+ depth[mask_inf] = np.inf++ return depth+++def depth_to_pointmap(depth: np.ndarray, intrinsics: np.ndarray) -> np.ndarray:+ """+ Convert depth map to 3D point map using pinhole camera model.++ Args:+ depth: (H, W) depth values in meters+ intrinsics: (3, 3) camera intrinsic matrix [[fx, 0, cx], [0, fy, cy], [0, 0, 1]]++ Returns:+ (H, W, 3) point map with (X, Y, Z) coordinates+ """+ H, W = depth.shape+ fx, fy = intrinsics[0, 0], intrinsics[1, 1]+ cx, cy = intrinsics[0, 2], intrinsics[1, 2]++ # Create pixel coordinate grids+ u = np.arange(W, dtype=np.float32)+ v = np.arange(H, dtype=np.float32)+ u, v = np.meshgrid(u, v)++ # Initialize output arrays with nan+ X = np.full_like(depth, np.nan, dtype=np.float32)+ Y = np.full_like(depth, np.nan, dtype=np.float32)+ Z = depth.copy()++ # Create mask for finite depth values to avoid RuntimeWarning on nan/inf+ finite_mask = np.isfinite(depth)++ # Backproject to 3D (only compute on finite values to avoid warnings)+ X[finite_mask] = (u[finite_mask] - cx) * depth[finite_mask] / fx+ Y[finite_mask] = (v[finite_mask] - cy) * depth[finite_mask] / fy++ pointmap = np.stack([X, Y, Z], axis=-1)+ return pointmap+++class EvalDepthDataset(Dataset):+ """+ Evaluation dataset for depth prediction.++ Reads images and ground truth depth in MoGe format:+ - depth.png: 16-bit PNG with logarithmic encoding and near/far metadata+ - image.jpg: RGB image+ - meta.json: {"intrinsics": [[fx, 0, cx], [0, fy, cy], [0, 0, 1]]}++ Uses index.txt for sample discovery, or glob fallback.++ Args:+ data_root: Root directory containing eval datasets+ dataset_name: Name of dataset (e.g., "NYUv2", "KITTI")+ crop_size: Optional crop size (int or tuple). If provided, applies center crop.++ Returns dict with:+ - image: (3, H, W) float tensor, normalized to [0, 1]+ - pointcloud: (3, H, W) raw metric coordinates+ - valid_mask: (H, W) bool tensor, True where depth is finite+ - intrinsics: (3, 3) camera matrix (adjusted for crop if applied)+ - sample_id: string identifier+ """++ def __init__(+ self,+ data_root: str,+ dataset_name: str,+ crop_size: int = None,+ max_samples: int = None,+ resize_height: int = None,+ ):+ self.data_root = Path(data_root)+ self.dataset_name = dataset_name+ self.dataset_path = self.data_root / dataset_name++ # Resize settings (applied before crop)+ self.resize_height = resize_height+ if resize_height is not None:+ print(f"[EvalDepthDataset] Will resize shortest side to {resize_height}")++ # Center crop settings+ if crop_size is not None:+ if isinstance(crop_size, int):+ self.crop_size = (crop_size, crop_size)+ else:+ self.crop_size = crop_size+ print(f"[EvalDepthDataset] Using center crop of size {self.crop_size}")+ else:+ self.crop_size = None++ # Try to read sample IDs from index.txt, fallback to glob discovery+ index_file = self.dataset_path / "index.txt"+ if index_file.exists():+ with open(index_file, 'r') as f:+ self.sample_ids = [line.strip() for line in f if line.strip()]+ print(f"[EvalDepthDataset] Loaded {len(self.sample_ids)} samples from {dataset_name}/index.txt")+ else:+ # Glob for directories containing depth.png+ self.sample_ids = []+ for depth_file in sorted(self.dataset_path.rglob("depth.png")):+ # Get relative path from dataset_path to the sample directory+ sample_dir = depth_file.parent+ sample_id = str(sample_dir.relative_to(self.dataset_path))+ self.sample_ids.append(sample_id)++ if len(self.sample_ids) == 0:+ raise FileNotFoundError(+ f"No samples found in {self.dataset_path}. "+ f"Expected either index.txt or directories with depth.png"+ )+ print(f"[EvalDepthDataset] Discovered {len(self.sample_ids)} samples from {dataset_name} via glob")++ # Subsample if max_samples is specified+ if max_samples is not None and max_samples > 0 and len(self.sample_ids) > max_samples:+ # Uniformly subsample+ stride = len(self.sample_ids) // max_samples+ self.sample_ids = self.sample_ids[::stride][:max_samples]+ print(f"[EvalDepthDataset] Subsampled to {len(self.sample_ids)} samples (max_samples={max_samples})")++ def __len__(self) -> int:+ return len(self.sample_ids)++ def __getitem__(self, idx: int) -> dict:+ sample_id = self.sample_ids[idx]+ sample_dir = self.dataset_path / sample_id++ # Load image+ image_path = sample_dir / "image.jpg"+ if not image_path.exists():+ image_path = sample_dir / "image.png"+ image_pil = Image.open(image_path).convert("RGB")+ W, H = image_pil.size++ # Load depth+ depth_path = sample_dir / "depth.png"+ depth = read_depth(depth_path) # (H, W)++ # Load intrinsics from meta.json+ meta_path = sample_dir / "meta.json"+ with open(meta_path, 'r') as f:+ meta = json.load(f)+ intrinsics = np.array(meta["intrinsics"], dtype=np.float32) # (3, 3)++ # normalized and scale by image dimensions+ intrinsics[0, 0] *= W # fx+ intrinsics[1, 1] *= H # fy+ intrinsics[0, 2] *= W # cx+ intrinsics[1, 2] *= H # cy++ # Apply resize if specified (before crop)+ if self.resize_height is not None:+ # Resize shortest side to resize_height, maintain aspect ratio+ if H < W:+ # Height is shorter+ new_h = self.resize_height+ new_w = int(W * (new_h / H))+ else:+ # Width is shorter or equal+ new_w = self.resize_height+ new_h = int(H * (new_w / W))++ # Resize image with BILINEAR interpolation+ image_pil = image_pil.resize((new_w, new_h), Image.BILINEAR)++ # Resize depth with NEAREST interpolation to preserve depth values+ depth_pil = Image.fromarray(depth.astype(np.float32))+ depth_pil = depth_pil.resize((new_w, new_h), Image.NEAREST)+ depth = np.array(depth_pil)++ # Scale intrinsics+ scale_w = new_w / W+ scale_h = new_h / H+ intrinsics[0, 0] *= scale_w # fx+ intrinsics[1, 1] *= scale_h # fy+ intrinsics[0, 2] *= scale_w # cx+ intrinsics[1, 2] *= scale_h # cy++ W, H = new_w, new_h++ # Apply center crop if specified+ if self.crop_size is not None:+ target_h, target_w = self.crop_size++ if W >= target_w and H >= target_h:+ # Calculate crop offsets+ i = (H - target_h) // 2 # top+ j = (W - target_w) // 2 # left++ # Crop image+ image_pil = image_pil.crop((j, i, j + target_w, i + target_h))++ # Crop depth+ depth = depth[i:i + target_h, j:j + target_w]++ # Adjust intrinsics (cx, cy shift by crop offset)+ intrinsics[0, 2] -= j # cx+ intrinsics[1, 2] -= i # cy++ W, H = target_w, target_h+ else:+ print(f"Warning: Image size ({H}, {W}) smaller than crop size {self.crop_size}. No crop applied.")++ # Convert image to numpy+ image = np.array(image_pil, dtype=np.float32) / 255.0 # (H, W, 3)++ # Convert depth to pointmap+ pointmap = depth_to_pointmap(depth, intrinsics) # (H, W, 3)++ # Create valid mask (finite depth values)+ valid_mask = np.isfinite(depth)++ # Convert to tensors+ image_tensor = torch.from_numpy(image).permute(2, 0, 1) # (3, H, W)+ pointcloud_tensor = torch.from_numpy(pointmap).permute(2, 0, 1) # (3, H, W)+ valid_mask_tensor = torch.from_numpy(valid_mask) # (H, W)+ intrinsics_tensor = torch.from_numpy(intrinsics) # (3, 3)++ return {+ 'image': image_tensor,+ 'pointcloud': pointcloud_tensor,+ 'valid_mask': valid_mask_tensor,+ 'intrinsics': intrinsics_tensor,+ 'sample_id': sample_id,+ 'dataset_name': self.dataset_name,+ }+++class MultiEvalDepthDataset(Dataset):+ """+ Wrapper that combines multiple EvalDepthDataset instances.++ This allows evaluating on multiple datasets sequentially while tracking+ which dataset each sample comes from.++ Args:+ data_root: Root directory containing eval datasets+ dataset_names: List of dataset names (e.g., ["NYUv2", "KITTI"])+ crop_size: Optional crop size (passed to each dataset)+ max_samples: Optional max samples per dataset+ """++ def __init__(+ self,+ data_root: str,+ dataset_names: List[str],+ crop_size: int = None,+ max_samples: int = None,+ resize_height: int = None,+ ):+ self.datasets = []+ self.dataset_names = dataset_names+ self.cumulative_sizes = [0]++ for name in dataset_names:+ try:+ dataset = EvalDepthDataset(+ data_root=data_root,+ dataset_name=name,+ crop_size=crop_size,+ max_samples=max_samples,+ resize_height=resize_height,+ )+ self.datasets.append(dataset)+ self.cumulative_sizes.append(self.cumulative_sizes[-1] + len(dataset))+ print(f"[MultiEvalDepthDataset] Loaded {name}: {len(dataset)} samples")+ except Exception as e:+ print(f"[MultiEvalDepthDataset] Failed to load {name}: {e}")++ if len(self.datasets) == 0:+ raise ValueError(f"No datasets could be loaded from {dataset_names}")++ print(f"[MultiEvalDepthDataset] Total: {self.cumulative_sizes[-1]} samples across {len(self.datasets)} datasets")++ def __len__(self) -> int:+ return self.cumulative_sizes[-1]++ def __getitem__(self, idx: int) -> dict:+ # Find which dataset this index belongs to+ dataset_idx = 0+ for i, cumsum in enumerate(self.cumulative_sizes[1:]):+ if idx < cumsum:+ dataset_idx = i+ break++ # Get the local index within that dataset+ local_idx = idx - self.cumulative_sizes[dataset_idx]++ # Get the sample (already includes 'dataset_name' from EvalDepthDataset)+ return self.datasets[dataset_idx][local_idx]+++class WildImagesDataset(Dataset):+ """+ Inference-only dataset for arbitrary images without ground truth depth.+ Loads images from a flat or nested directory. Returns only image tensors.+ """+ IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG'}++ def __init__(+ self,+ images_dir: str,+ dataset_name: str = 'wild',+ crop_size=None,+ resize_height: int = None,+ max_samples: int = None,+ ):+ self.images_dir = Path(images_dir)+ self.dataset_name = dataset_name+ self.resize_height = resize_height++ if crop_size is not None:+ self.crop_size = (crop_size, crop_size) if isinstance(crop_size, int) else tuple(crop_size)+ else:+ self.crop_size = None++ # Discover all images+ image_paths = []+ for ext in self.IMAGE_EXTENSIONS:+ image_paths.extend(self.images_dir.rglob(f'*{ext}'))+ self.image_paths = sorted(set(image_paths))++ if len(self.image_paths) == 0:+ raise FileNotFoundError(f"No images found in {self.images_dir}")+ print(f"[WildImagesDataset] Found {len(self.image_paths)} images in {images_dir}")++ if max_samples is not None and max_samples > 0 and len(self.image_paths) > max_samples:+ stride = len(self.image_paths) // max_samples+ self.image_paths = self.image_paths[::stride][:max_samples]+ print(f"[WildImagesDataset] Subsampled to {len(self.image_paths)} samples")++ def __len__(self):+ return len(self.image_paths)++ def __repr__(self):+ return f"WildImagesDataset({self.dataset_name}, {len(self.image_paths)} images)"++ def __getitem__(self, idx: int) -> dict:+ image_path = self.image_paths[idx]+ image_pil = Image.open(image_path).convert("RGB")++ # Resize shortest side+ if self.resize_height is not None:+ W, H = image_pil.size+ if H <= W:+ new_H = self.resize_height+ new_W = int(round(W * new_H / H))+ else:+ new_W = self.resize_height+ new_H = int(round(H * new_W / W))+ image_pil = image_pil.resize((new_W, new_H), Image.BILINEAR)++ # Center crop+ if self.crop_size is not None:+ W, H = image_pil.size+ crop_h, crop_w = self.crop_size+ left = (W - crop_w) // 2+ top = (H - crop_h) // 2+ image_pil = image_pil.crop((left, top, left + crop_w, top + crop_h))++ image = torch.from_numpy(np.array(image_pil, dtype=np.float32) / 255.0).permute(2, 0, 1) # [3, H, W]++ try:+ sample_id = str(image_path.relative_to(self.images_dir))+ except ValueError:+ sample_id = image_path.name++ return {+ 'image': image,+ 'sample_id': sample_id,+ 'dataset_name': self.dataset_name,+ }+diff --git a/dataloader/img_depth_intrinsics.py b/dataloader/img_depth_intrinsics.pynew file mode 100644index 0000000..16455c0--- /dev/null+++ b/dataloader/img_depth_intrinsics.py@@ -0,0 +1,4026 @@+# coding=utf-8++"""+ImageDepthIntrinsicsDataset - Optimized dataloader for depth-to-pointcloud conversion.++Performance Optimizations (vs original version):+1. **Cached Ray/Grid Computation**: Pre-compute and cache all ray arrays and backprojection+ grids. With resize_height, common sizes are pre-cached in __init__. Eliminates expensive+ per-sample recomputation.++2. **GPU-Accelerated Conversion**: All depth->pointcloud operations use vectorized torch ops+ instead of numpy loops. Optional GPU mode (use_gpu_conversion=True) for even faster processing.++3. **Fast Resizing**: Replace PIL resize with torch.nn.functional.interpolate (3-5x faster).++4. **Smart Caching**: VKitti2 backprojection grids cached by intrinsics tuple (many frames+ share the same camera parameters after rounding).++Expected speedup: 10-50x depending on dataset, resize settings, and GPU usage.++Usage:+ # CPU mode (still much faster than before)+ dataset = ImageDepthIntrinsicsDataset(..., use_gpu_conversion=False)++ # GPU mode (fastest, requires CUDA)+ dataset = ImageDepthIntrinsicsDataset(..., use_gpu_conversion=True)+"""++import os+import glob+import numpy as np+from PIL import Image, UnidentifiedImageError+import torch+from torch.utils.data import Dataset+import torchvision.transforms.functional as TF+import torchvision+import random+from torchvision.transforms import v2+import pickle+import math++import time+import bisect # For binary search++os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1"++# Paired crop classes and helper functions+from dataloader.point_transforms import (+ RandomCropPaired,+ CenterCropPaired,+ RandomCropPairedWithOffset,+ CenterCropPairedWithOffset,+ compute_distance_statistic,+)+++# --- SceneNet-RGBD Helper Functions ---++def compute_scenenet_intrinsics(width=320, height=240):+ """+ Compute intrinsics for SceneNet from its fixed FOV values.++ SceneNet uses hfov=60°, vfov=45°.+ fx = width / (2 * tan(hfov/2))+ fy = height / (2 * tan(vfov/2))+ cx = width / 2+ cy = height / 2++ Returns: (fx, fy, cx, cy)+ """+ hfov = 60.0+ vfov = 45.0+ fx = width / (2.0 * math.tan(math.radians(hfov / 2.0)))+ fy = height / (2.0 * math.tan(math.radians(vfov / 2.0)))+ cx = width / 2.0+ cy = height / 2.0+ return fx, fy, cx, cy+++def scenenet_ray_directions(width=320, height=240, device='cpu'):+ """+ Unit ray direction per pixel under the SceneNet-RGBD camera model.++ SceneNet-RGBD stores Euclidean ray-depth rather than planar z-depth, so+ recovering points needs the direction of each pixel's ray. Directions come+ straight from the pinhole model of compute_scenenet_intrinsics() above:+ un-project the pixel centre (u, v) = (x + 0.5, y + 0.5) to+ ((u - cx) / fx, (v - cy) / fy, 1) and normalise to unit length.++ Args:+ width, height: Image dimensions+ device: 'cpu' or 'cuda'++ Returns: (H, W, 3) tensor of unit rays+ """+ fx, fy, cx, cy = compute_scenenet_intrinsics(width=width, height=height)++ x = torch.arange(width, dtype=torch.float32, device=device)+ y = torch.arange(height, dtype=torch.float32, device=device)+ yy, xx = torch.meshgrid(y, x, indexing='ij') # (H, W)++ # Pixel centres, un-projected onto the z = 1 plane.+ x_vect = (xx + 0.5 - cx) / fx+ y_vect = (yy + 0.5 - cy) / fy+ z_vect = torch.ones_like(x_vect)++ rays = torch.stack([x_vect, y_vect, z_vect], dim=-1) # (H, W, 3)+ return rays / torch.norm(rays, dim=-1, keepdim=True)+++def raydepth_to_points(depth_map, ray_directions):+ """+ Convert Euclidean ray-depth to 3D camera-frame points.++ Args:+ depth_map: (H, W) torch tensor of ray-depth values in meters+ ray_directions: (H, W, 3) torch tensor of unit ray directions++ Returns:+ (H, W, 3) torch tensor of 3D points in camera coordinates+ """+ return ray_directions * depth_map.unsqueeze(-1)+++# --- TartanAir and VKitti2 Helper Functions ---++def compute_backprojection_grid(width, height, fx, fy, cx, cy, device='cpu'):+ """+ Computes a grid of normalized coordinates for back-projection (GPU-accelerated).+ Used for z-depth to 3D conversion (TartanAir, VKitti2).++ Args:+ width, height: Image dimensions+ fx, fy, cx, cy: Camera intrinsics+ device: 'cpu' or 'cuda'++ Returns: (H, W, 3) tensor where:+ grid[:,:,0] = (u - cx) / fx+ grid[:,:,1] = (v - cy) / fy+ grid[:,:,2] = 1.0+ """+ u = torch.arange(width, dtype=torch.float32, device=device)+ v = torch.arange(height, dtype=torch.float32, device=device)+ vv, uu = torch.meshgrid(v, u, indexing='ij') # (H, W)++ x_norm = (uu - cx) / fx+ y_norm = (vv - cy) / fy+ ones = torch.ones_like(x_norm)++ grid = torch.stack([x_norm, y_norm, ones], dim=-1) # (H, W, 3)+ return grid+++def points_in_camera_coords_zdepth(depth_map, backprojection_grid):+ """+ Convert z-depth map to 3D point cloud using pre-computed grid (GPU-accelerated).++ Args:+ depth_map: (H, W) torch tensor of z-depth values in meters+ backprojection_grid: (H, W, 3) torch tensor of normalized coordinates++ Returns:+ (H, W, 3) torch tensor of 3D points in camera coordinates+ """+ return backprojection_grid * depth_map.unsqueeze(-1)+++# --- VKitti2 Intrinsics Parsing ---++def load_vkitti_intrinsics(intrinsic_path):+ """+ Parse Virtual KITTI 2 intrinsic.txt file.++ Returns: dict mapping (frame_idx, camera_id) -> (fx, fy, cx, cy)+ """+ intrinsics = {}+ if not os.path.exists(intrinsic_path):+ return intrinsics++ with open(intrinsic_path, 'r') as f:+ lines = f.readlines()+ # Skip header: frame cameraID K[0,0] K[1,1] K[0,2] K[1,2]+ for line in lines[1:]:+ parts = line.strip().split()+ if len(parts) < 6:+ continue++ frame_idx = int(parts[0])+ camera_id = int(parts[1])+ fx = float(parts[2]) # K[0,0]+ fy = float(parts[3]) # K[1,1]+ cx = float(parts[4]) # K[0,2]+ cy = float(parts[5]) # K[1,2]++ intrinsics[(frame_idx, camera_id)] = (fx, fy, cx, cy)++ return intrinsics+++# --- TartanAir V2 Depth Decoding ---++def read_decode_tartanairv2_depth(depthpath):+ """+ Decode TartanAir V2 depth image from RGBA PNG to float32.++ TartanAir V2 stores float32 depth values in 4-channel 8-bit RGBA PNGs.+ Each pixel's 4 bytes represent a single float32 value.++ Args:+ depthpath: Path to depth PNG file++ Returns:+ (H, W) numpy array of float32 depth values in meters+ """+ import cv2+ depth_rgba = cv2.imread(depthpath, cv2.IMREAD_UNCHANGED)+ depth = depth_rgba.view("<f4")+ return np.squeeze(depth, axis=-1)+++# --- OmniWorld-Game Depth Decoding ---++def load_omniworldgame_depth(depthpath):+ """+ Load and decode OmniWorld-Game depth from 16-bit PNG.++ OmniWorld-Game stores depth as 16-bit unsigned integers in [0, 65535].+ Values 0-100 are invalid (too close), 65500-65535 are sky/far.+ The depth values use a disparity-like encoding that needs conversion.++ Args:+ depthpath: Path to depth PNG file++ Returns:+ depthmap: (H, W) float32 array with z-depth in meters+ valid: (H, W) bool array, True for reliable pixels+ """+ import imageio.v2++ # Load 16-bit depth+ depthmap = imageio.v2.imread(depthpath).astype(np.float32) / 65535.0++ # Identify invalid regions+ near_mask = depthmap < 0.0015 # too close+ far_mask = depthmap > (65500.0 / 65535.0) # sky/too far++ # Convert from disparity-like encoding to z-depth+ # Formula: depth_z = depth_normalized / (far - depth_normalized * (far - near)) / scale+ near, far = 1.0, 1000.0+ depthmap = depthmap / (far - depthmap * (far - near)) / 0.004++ # Mark invalid pixels+ # valid = ~(near_mask | far_mask)+ # only remove near for now, since we want to keep sky points for sky dome handling+ valid = ~near_mask+ depthmap[~valid] = 0.0++ return depthmap, valid+++# --- Dataset Class ---++class ImageDepthIntrinsicsDataset(Dataset):+ """+ PyTorch Dataset for paired RGB and Depth data with on-the-fly pointcloud conversion.++ Supports multiple datasets with different raw file structures:+ - SceneNet-RGBD: ray-depth in .png files+ - TartanAir: z-depth in .npy files+ - TartanAir V2: z-depth in RGBA-encoded .png files (float32)+ - VKitti2: z-depth in .png files with per-frame intrinsics+ - Hypersim: z-depth in .npy files with per-frame intrinsics in .npz+ - UrbanSyn: z-depth in .npy files (preprocessed) with per-frame intrinsics in .npz+ - MVSSynth: z-depth in .npy files (preprocessed from EXR) with per-frame intrinsics in .npz+ - Synscapes: z-depth in .npy files (preprocessed from EXR) with per-frame intrinsics in .npz+ - OmniWorld-Game: z-depth in 16-bit .png files with per-split intrinsics in .json+ - IRS: z-depth in .npy files (preprocessed from disparity EXR) with per-frame intrinsics in .npz+ - Dynamic Replica: z-depth in .npy files with per-frame intrinsics in .npz+ - EDEN: z-depth in .npy files with per-frame intrinsics in .npz++ Converts (image, depth, intrinsics) -> (image, pointcloud).++ Features:+ - Scene-level splitting (Manual via .txt or Auto via uniform sampling)+ - Uniform subsampling of K frames per scene+ - Optional resize before crop (with intrinsics scaling)+ - Paired cropping (Random for Train, Center for Test)+ - Paired image/point-map augmentations+ - Same normalization pipeline++ Resize Pipeline:+ - Image: BILINEAR interpolation+ - Depth: NEAREST interpolation (preserves depth values)+ - Intrinsics: Scaled proportionally to new dimensions+ - Applied before augmentations and crop+ """++ def __init__(+ self,+ root_dir,+ dataset_name, # 'scenenet', 'tartanair', 'tartanairv2', 'vkitti2', 'hypersim', 'urbansyn', 'mvssynth', 'synscapes', 'omniworldgame', 'irs', 'dynamic_replica', 'eden'+ split='train',+ num_test_scenes=2,+ test_scenes_file=None,+ samples_per_scene=None,+ crop_size=None,+ resize_height=None, # NEW: Resize before crop (int or dict)+ resize_width=None, # NEW: Resize to fixed width before crop (int or dict)+ center_shift=False,+ normalize_by_mean=False,+ num_overfit_samples=None,+ num_dataset_duplicates=None,+ max_depth=10.,+ subsample_scenes=None,+ center_shift_z_only=False,+ more_img_aug=False,+ stronger_img_aug=False,+ compute_scale_factor_only_valid=False,+ compute_scale_factor_use_std=False,+ compute_scale_factor_use_percentile=False,+ clamp_max_depth=None,+ handle_sky=False,+ use_sky_dome=False,+ sky_far_plane_value=3.0,+ debug_timing=False,+ use_gpu_conversion=False, # NEW: Use GPU for depth->pointcloud conversion+ remove_outliers=False, # NEW: Remove points with extreme normalized coordinates+ outlier_threshold=3.0, # NEW: Threshold for outlier removal (absolute value)+ min_height=None, # NEW: Filter out samples below this height+ min_width=None, # NEW: Filter out samples below this width+ scale_factor_augment=False,+ scale_factor_augment_range=(0.8, 1.2),+ no_scale_factor=False,+ # High-res finetuning mode parameters+ finetune_highres_mode=False, # Enable adaptive resize for high-res finetuning+ finetune_target_height=512, # Target height for finetuning+ finetune_target_width=None, # Target width for finetuning (None = height-only mode)+ finetune_target_crop=512, # Crop size for finetuning (int for square, [h,w] for rectangular)+ ):+ """+ Args:+ root_dir (str): Root directory of the dataset+ dataset_name (str): One of 'scenenet', 'tartanair', 'tartanairv2', 'vkitti2', 'hypersim', 'urbansyn', 'mvssynth', 'synscapes', 'omniworldgame', 'irs', 'dynamic_replica', 'eden'+ split (str): 'train', 'test', or 'all'+ resize_height (int or dict, optional): Resize height before crop.+ If int: applies to all datasets. If dict: per-dataset values.+ Example: 512 or {'scenenet': 256, 'tartanair': 512}+ use_gpu_conversion (bool): If True, perform depth->pointcloud conversion on GPU.+ Significantly faster but requires CUDA. Default: False+ ... (see the constructor signature below for the remaining args)++ Performance Optimizations:+ - Ray arrays and backprojection grids are cached (no recomputation)+ - Resizing uses torch.nn.functional.interpolate (faster than PIL)+ - Depth->pointcloud conversion uses vectorized torch ops (no loops)+ - Optional GPU acceleration for all conversion operations+ """+ self.root_dir = root_dir+ self.dataset_name = dataset_name.lower()+ self.crop_size = crop_size+ self.split = split.lower()+ self.num_test_scenes = num_test_scenes+ self.test_scenes_file = test_scenes_file+ self.samples_per_scene = samples_per_scene+ self.center_shift = center_shift+ self.center_shift_z_only = center_shift_z_only+ self.normalize_by_mean = normalize_by_mean+ self.max_depth = max_depth++ self.subsample_scenes = subsample_scenes+ self.more_img_aug = more_img_aug+ self.stronger_img_aug = stronger_img_aug+ self.compute_scale_factor_only_valid = compute_scale_factor_only_valid+ self.compute_scale_factor_use_std = compute_scale_factor_use_std+ self.compute_scale_factor_use_percentile = compute_scale_factor_use_percentile+ self.clamp_max_depth = clamp_max_depth+ self.handle_sky = handle_sky+ self.use_sky_dome = use_sky_dome+ self.sky_far_plane_value = sky_far_plane_value+ self.remove_outliers = remove_outliers+ self.outlier_threshold = outlier_threshold+ self.debug_timing = debug_timing+ self.min_height = min_height+ self.min_width = min_width+ self.scale_factor_augment = scale_factor_augment+ self.scale_factor_augment_range = scale_factor_augment_range+ self.no_scale_factor = no_scale_factor++ # High-res finetuning mode+ self.finetune_highres_mode = finetune_highres_mode+ self.finetune_target_height = finetune_target_height+ self.finetune_target_width = finetune_target_width+ self.finetune_target_crop = finetune_target_crop+ if self.finetune_highres_mode:+ print(f"[{self.dataset_name.upper()}] High-res finetuning mode: target_height={finetune_target_height}, target_width={finetune_target_width}, crop={finetune_target_crop}")++ self._timing_count = 0+ self._timing_accum = {'file_read': 0, 'depth_convert': 0, 'augment': 0, 'total': 0}++ # Resolve resize_height for this dataset+ if resize_height is not None:+ if isinstance(resize_height, dict):+ self.resize_height = resize_height.get(self.dataset_name, None)+ else:+ self.resize_height = resize_height+ else:+ self.resize_height = None++ if self.resize_height is not None:+ print(f"[{self.dataset_name.upper()}] Will resize height to {self.resize_height} before crop")++ # Resolve resize_width for this dataset+ if resize_width is not None:+ if isinstance(resize_width, dict):+ self.resize_width = resize_width.get(self.dataset_name, None)+ else:+ self.resize_width = resize_width+ else:+ self.resize_width = None++ if self.resize_width is not None:+ print(f"[{self.dataset_name.upper()}] Will resize width to {self.resize_width} before crop")++ # NEW: Setup device for conversion+ self.use_gpu_conversion = use_gpu_conversion+ if use_gpu_conversion and not torch.cuda.is_available():+ print(f"[WARNING] GPU conversion requested but CUDA not available, falling back to CPU")+ self.use_gpu_conversion = False+ self.conversion_device = torch.device('cuda' if self.use_gpu_conversion else 'cpu')+ if self.use_gpu_conversion:+ print(f"[{self.dataset_name.upper()}] Using GPU for depth->pointcloud conversion")++ # NEW: Caches for ray arrays and backprojection grids+ self._ray_cache = {} # Key: (width, height)+ self._backproj_cache = {} # Key: (width, height, fx, fy, cx, cy) - rounded++ # Datasets with per-frame intrinsics should NOT cache backprojection grids+ # to avoid unbounded memory growth+ variable_intrinsics_datasets = {'hypersim', 'urbansyn', 'synscapes', 'irs', 'omniworldgame', 'mvssynth', 'dynamic_replica', 'eden'}+ self._use_backproj_cache = self.dataset_name not in variable_intrinsics_datasets+ # Also disable camera intrinsics file caching for variable-intrinsics datasets+ self._use_cam_cache = self.dataset_name not in variable_intrinsics_datasets+ if not self._use_backproj_cache:+ print(f"[{self.dataset_name.upper()}] Backprojection and camera caching DISABLED (variable intrinsics)")++ # Precompute ray array for SceneNet (constant across all images)+ if self.dataset_name == 'scenenet':+ # Pre-cache for default size+ self._ray_cache[(320, 240)] = scenenet_ray_directions(width=320, height=240, device=self.conversion_device)++ # Pre-cache for resized size if applicable+ if self.resize_height is not None:+ # Compute target width maintaining aspect ratio (320/240 = 4/3)+ scale = self.resize_height / 240+ target_width = int(320 * scale)+ self._ray_cache[(target_width, self.resize_height)] = scenenet_ray_directions(+ width=target_width, height=self.resize_height, device=self.conversion_device+ )+ print(f"[SceneNet] Pre-cached ray array for size ({target_width}, {self.resize_height})")++ # Precompute backprojection grid for TartanAir (fixed intrinsics)+ if self.dataset_name == 'tartanair':+ fx, fy, cx, cy = 320.0, 320.0, 320.0, 240.0++ # Pre-cache for default size+ cache_key = (640, 480, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ self._backproj_cache[cache_key] = compute_backprojection_grid(640, 480, fx, fy, cx, cy, device=self.conversion_device)++ # Pre-cache for resized size if applicable+ if self.resize_height is not None:+ scale = self.resize_height / 480+ new_w = int(640 * scale)+ new_h = self.resize_height+ fx_scaled = fx * scale+ fy_scaled = fy * scale+ cx_scaled = cx * scale+ cy_scaled = cy * scale++ cache_key = (new_w, new_h, round(fx_scaled, 2), round(fy_scaled, 2), round(cx_scaled, 2), round(cy_scaled, 2))+ self._backproj_cache[cache_key] = compute_backprojection_grid(+ new_w, new_h, fx_scaled, fy_scaled, cx_scaled, cy_scaled, device=self.conversion_device+ )+ print(f"[TartanAir] Pre-cached backproj grid for size ({new_w}, {new_h})")++ # Precompute backprojection grid for TartanAir V2 (fixed intrinsics, 640x640)+ if self.dataset_name == 'tartanairv2':+ # TartanAir V2 intrinsics: fx=320, fy=320, cx=320, cy=320 for 640x640 images+ fx, fy, cx, cy = 320.0, 320.0, 320.0, 320.0++ # Pre-cache for default size (640x640)+ cache_key = (640, 640, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ self._backproj_cache[cache_key] = compute_backprojection_grid(640, 640, fx, fy, cx, cy, device=self.conversion_device)++ # Pre-cache for resized size if applicable+ if self.resize_height is not None:+ scale = self.resize_height / 640+ new_w = int(640 * scale)+ new_h = self.resize_height+ fx_scaled = fx * scale+ fy_scaled = fy * scale+ cx_scaled = cx * scale+ cy_scaled = cy * scale++ cache_key = (new_w, new_h, round(fx_scaled, 2), round(fy_scaled, 2), round(cx_scaled, 2), round(cy_scaled, 2))+ self._backproj_cache[cache_key] = compute_backprojection_grid(+ new_w, new_h, fx_scaled, fy_scaled, cx_scaled, cy_scaled, device=self.conversion_device+ )+ print(f"[TartanAirV2] Pre-cached backproj grid for size ({new_w}, {new_h})")++ # Cache for VKitti2 intrinsics (loaded per-sequence) and grids+ if self.dataset_name == 'vkitti2':+ self.vkitti2_intrinsics_cache = {}++ # Cache for Hypersim camera files (per-frame .npz files)+ if self.dataset_name == 'hypersim':+ self.hypersim_cam_cache = {}++ # Cache for UrbanSyn camera files (per-frame .npz files, similar to Hypersim)+ if self.dataset_name == 'urbansyn':+ self.urbansyn_cam_cache = {}++ # Cache for MVSSynth camera files (per-frame .npz files, similar to Hypersim)+ if self.dataset_name == 'mvssynth':+ self.mvssynth_cam_cache = {}++ # Cache for Synscapes camera files (per-frame .npz files, similar to Hypersim)+ if self.dataset_name == 'synscapes':+ self.synscapes_cam_cache = {}++ # Cache for IRS camera files (per-frame .npz files, similar to Hypersim)+ if self.dataset_name == 'irs':+ self.irs_cam_cache = {}++ # Cache for Dynamic Replica camera files (per-frame .npz files, fixed intrinsics so caching is efficient)+ if self.dataset_name == 'dynamic_replica':+ self.dynamic_replica_cam_cache = {}++ # 1. Discover and Split Scenes+ if self.dataset_name == 'scenenet':+ self.all_data_paths = self._find_and_split_data_scenenet()+ elif self.dataset_name == 'tartanair':+ self.all_data_paths = self._find_and_split_data_tartanair()+ elif self.dataset_name == 'tartanairv2':+ self.all_data_paths = self._find_and_split_data_tartanairv2()+ elif self.dataset_name == 'vkitti2':+ self.all_data_paths = self._find_and_split_data_vkitti2()+ elif self.dataset_name == 'hypersim':+ self.all_data_paths = self._find_and_split_data_hypersim()+ elif self.dataset_name == 'urbansyn':+ self.all_data_paths = self._find_and_split_data_urbansyn()+ elif self.dataset_name == 'mvssynth':+ self.all_data_paths = self._find_and_split_data_mvssynth()+ elif self.dataset_name == 'synscapes':+ self.all_data_paths = self._find_and_split_data_synscapes()+ elif self.dataset_name == 'omniworldgame':+ self.all_data_paths = self._find_and_split_data_omniworldgame()+ elif self.dataset_name == 'irs':+ self.all_data_paths = self._find_and_split_data_irs()+ elif self.dataset_name == 'dynamic_replica':+ self.all_data_paths = self._find_and_split_data_dynamic_replica()+ elif self.dataset_name == 'eden':+ self.all_data_paths = self._find_and_split_data_eden()+ else:+ raise ValueError(f"Unknown dataset_name: {dataset_name}. Supported: 'scenenet', 'tartanair', 'tartanairv2', 'vkitti2', 'hypersim', 'urbansyn', 'mvssynth', 'synscapes', 'omniworldgame', 'irs', 'dynamic_replica', 'eden'")++ if num_overfit_samples is not None:+ self.all_data_paths = self.all_data_paths[:num_overfit_samples]++ if num_dataset_duplicates is not None:+ self.all_data_paths = self.all_data_paths * num_dataset_duplicates++ # Compute cumulative indices for fast O(log n) lookup in __getitem__+ self._compute_cumulative_indices()++ # 2. Setup the crop transformation+ # Determine effective crop size (finetune mode overrides crop_size)+ effective_crop_size = self.finetune_target_crop if self.finetune_highres_mode else self.crop_size++ if effective_crop_size is not None:+ if self.finetune_highres_mode:+ # High-res finetuning mode: use crop classes that return offsets for intrinsics adjustment+ if self.split in ['test', 'val'] or num_overfit_samples is not None:+ print(f"[{self.split.upper()}] High-res mode: Using CenterCropPairedWithOffset of size {effective_crop_size}.")+ self.cropper = CenterCropPairedWithOffset(size=effective_crop_size)+ else:+ print(f"[{self.split.upper()}] High-res mode: Using RandomCropPairedWithOffset of size {effective_crop_size}.")+ self.cropper = RandomCropPairedWithOffset(size=effective_crop_size)+ else:+ # Standard mode: use original crop classes+ if self.split in ['test', 'val'] or num_overfit_samples is not None:+ print(f"[{self.split.upper()}] Using fixed CenterCropPaired of size {effective_crop_size}.")+ self.cropper = CenterCropPaired(size=effective_crop_size)+ else:+ print(f"[{self.split.upper()}] Using random RandomCropPaired of size {effective_crop_size}.")+ self.cropper = RandomCropPaired(size=effective_crop_size)+ else:+ self.cropper = None++ # Standard Image Transforms+ self.image_to_tensor = TF.to_tensor++ if self.split in ['train', 'all']:+ # Color jitting+ self.color_jitter = torchvision.transforms.ColorJitter(+ brightness=0.1, contrast=0.1, saturation=0.1, hue=0.05+ )++ if self.more_img_aug:+ aug_prob = 0.2 if self.stronger_img_aug else 0.1+ self.appearance_aug = v2.Compose([+ v2.RandomApply([v2.GaussianBlur(kernel_size=5, sigma=(0.1, 2.0))], p=aug_prob),+ v2.RandomAutocontrast(p=aug_prob),+ v2.RandomEqualize(p=aug_prob),+ v2.RandomApply([v2.RandomChannelPermutation()], p=aug_prob),+ v2.RandomApply([v2.JPEG(quality=(40, 100))], p=aug_prob),+ v2.RandomGrayscale(p=aug_prob),+ ])++ def _compute_highres_resize_params(self, orig_h, orig_w):+ """+ Compute resize parameters for high-res finetuning mode.++ Logic (when target_width is None - height-only mode):+ - If native height < target: always resize to target (upscale)+ - If native height > target: 50/50 random choice between resize or not+ - If native height == target: no resize needed++ Logic (when target_width is specified - rectangular mode):+ - If both dimensions >= target: 50/50 random choice to resize or direct crop+ - If either dimension is smaller than target: must resize+ - Scale is computed to ensure both dimensions >= target after resize++ Returns:+ (do_resize, scale, new_h, new_w) or (False, None, None, None) if no resize needed+ """+ if not self.finetune_highres_mode:+ return False, None, None, None++ target_h = self.finetune_target_height+ target_w = self.finetune_target_width++ # Rectangular mode: check both dimensions+ if target_w is not None:+ height_ok = orig_h >= target_h+ width_ok = orig_w >= target_w++ if height_ok and width_ok:+ # Image is large enough in both dimensions: 50/50 choice+ do_resize = random.random() < 0.5+ else:+ # Image too small in at least one dimension: must resize+ do_resize = True++ if do_resize:+ # Compute scale to ensure both dims >= target+ scale_h = target_h / orig_h+ scale_w = target_w / orig_w+ scale = max(scale_h, scale_w)+ new_h = round(orig_h * scale)+ new_w = round(orig_w * scale)+ return True, scale, new_h, new_w+ else:+ return False, None, None, None+ else:+ # Height-only mode (original behavior)+ if orig_h < target_h:+ # Low-res: always upscale+ do_resize = True+ elif orig_h > target_h:+ # High-res: 50/50 random choice+ do_resize = random.random() < 0.5+ else:+ # Already at target height+ do_resize = False++ if do_resize:+ scale = target_h / orig_h+ new_h = target_h+ new_w = round(orig_w * scale)+ else:+ scale = 1.0+ new_h, new_w = orig_h, orig_w++ # Ensure both dimensions are at least as large as crop size+ # (handles portrait images where width < crop after height-based resize)+ crop_size = self.finetune_target_crop+ if crop_size is not None:+ crop_h, crop_w = (crop_size, crop_size) if isinstance(crop_size, int) else crop_size+ if new_h < crop_h or new_w < crop_w:+ do_resize = True+ scale = max(crop_h / orig_h, crop_w / orig_w)+ new_h = round(orig_h * scale)+ new_w = round(orig_w * scale)++ if do_resize:+ return True, scale, new_h, new_w+ else:+ return False, None, None, None++ def _get_cache_path(self):+ """Generate cache file path based on dataset parameters."""+ cache_dir = os.path.join(self.root_dir, '.cache')++ subsample_str = f"subsample{self.subsample_scenes}" if self.subsample_scenes is not None else "nosubsample"+ samples_str = f"samples{self.samples_per_scene}" if self.samples_per_scene is not None else "allsamples"++ # Only add minsize suffix if filtering is enabled (backwards compatible with existing caches)+ if self.min_height is not None or self.min_width is not None:+ minsize_str = f"_minh{self.min_height}_minw{self.min_width}"+ else:+ minsize_str = ""++ cache_filename = f"{self.dataset_name}_{self.split}_{subsample_str}_{samples_str}{minsize_str}.pkl"++ return os.path.join(cache_dir, cache_filename)++ def _get_cache_path_for_split(self, split):+ """Generate cache file path for a specific split (used when loading train+val for 'all')."""+ cache_dir = os.path.join(self.root_dir, '.cache')+ subsample_str = f"subsample{self.subsample_scenes}" if self.subsample_scenes is not None else "nosubsample"+ samples_str = f"samples{self.samples_per_scene}" if self.samples_per_scene is not None else "allsamples"++ # Only add minsize suffix if filtering is enabled (backwards compatible with existing caches)+ if self.min_height is not None or self.min_width is not None:+ minsize_str = f"_minh{self.min_height}_minw{self.min_width}"+ else:+ minsize_str = ""++ cache_filename = f"{self.dataset_name}_{split}_{subsample_str}_{samples_str}{minsize_str}.pkl"+ return os.path.join(cache_dir, cache_filename)++ def _load_cache_from_path(self, cache_path):+ """Load cache from a specific path and return just the data (no validation)."""+ if not os.path.exists(cache_path):+ return None++ try:+ with open(cache_path, 'rb') as f:+ cache_data = pickle.load(f)+ return cache_data.get('all_data')+ except Exception as e:+ print(f"Failed to load cache from {cache_path}: {e}")+ return None++ def _load_cache(self):+ """Load cached data if it exists and is valid."""+ cache_path = self._get_cache_path()++ if not os.path.exists(cache_path):+ return None++ try:+ with open(cache_path, 'rb') as f:+ cache_data = pickle.load(f)++ # Debug: Check each parameter+ # Normalize paths for comparison (handles symlinks and relative vs absolute paths)+ cached_root = os.path.abspath(os.path.realpath(cache_data.get('root_dir', '')))+ current_root = os.path.abspath(os.path.realpath(self.root_dir))+ root_match = cached_root == current_root++ split_match = cache_data.get('split') == self.split+ dataset_match = cache_data.get('dataset_name') == self.dataset_name+ subsample_match = cache_data.get('subsample_scenes') == self.subsample_scenes+ samples_match = cache_data.get('samples_per_scene') == self.samples_per_scene++ if (root_match and split_match and dataset_match and subsample_match and samples_match):+ print(f"[{self.split.upper()}] Loading data from cache: {cache_path}")+ return cache_data.get('all_data')+ else:+ print(f"[{self.split.upper()}] Cache invalidated due to parameter mismatch:")+ if not root_match:+ print(f" ✗ root_dir: cached='{cache_data.get('root_dir')}' != current='{self.root_dir}'")+ if not split_match:+ print(f" ✗ split: cached='{cache_data.get('split')}' != current='{self.split}'")+ if not dataset_match:+ print(f" ✗ dataset_name: cached='{cache_data.get('dataset_name')}' != current='{self.dataset_name}'")+ if not subsample_match:+ print(f" ✗ subsample_scenes: cached={cache_data.get('subsample_scenes')} != current={self.subsample_scenes}")+ if not samples_match:+ print(f" ✗ samples_per_scene: cached={cache_data.get('samples_per_scene')} != current={self.samples_per_scene}")+ return None++ except Exception as e:+ print(f"[{self.split.upper()}] Failed to load cache: {e}")+ return None++ def _save_cache(self, all_data):+ """Save all_data to cache file."""+ cache_path = self._get_cache_path()+ cache_dir = os.path.dirname(cache_path)++ os.makedirs(cache_dir, exist_ok=True)++ try:+ cache_data = {+ 'root_dir': self.root_dir,+ 'split': self.split,+ 'dataset_name': self.dataset_name,+ 'subsample_scenes': self.subsample_scenes,+ 'samples_per_scene': self.samples_per_scene,+ 'all_data': all_data+ }++ with open(cache_path, 'wb') as f:+ pickle.dump(cache_data, f, protocol=pickle.HIGHEST_PROTOCOL)++ print(f"[{self.split.upper()}] Saved data to cache: {cache_path}")++ except Exception as e:+ print(f"[{self.split.upper()}] Failed to save cache: {e}")++ def _find_and_split_data_scenenet(self):+ """+ Find and split SceneNet-RGBD data.++ Structure: root/train/{scene}/{trajectory}/photo/{frame}.jpg+ /depth/{frame}.png+ """+ # Special handling for split='all': try to load train+val caches+ if self.split == 'all':+ # Try to load both train and val caches+ train_cache_path = self._get_cache_path_for_split('train')+ val_cache_path = self._get_cache_path_for_split('val')++ train_cached = self._load_cache_from_path(train_cache_path)+ val_cached = self._load_cache_from_path(val_cache_path)++ if train_cached is not None and val_cached is not None:+ print(f"[ALL] Loaded {len(train_cached)} train samples from cache")+ print(f"[ALL] Loaded {len(val_cached)} val samples from cache")+ all_data = train_cached + val_cached+ print(f"[SceneNet-ALL] Total: {len(all_data)} samples (from cached train+val)")+ return all_data+ else:+ print(f"[ALL] Could not load both train and val caches, will rescan files...")++ # Try to load from cache first+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ # Get split-specific root (train or val)+ if self.split == 'train':+ split_dirs = ['train']+ elif self.split == 'test':+ split_dirs = ['val']+ elif self.split == 'all':+ split_dirs = ['train', 'val']+ else:+ split_dirs = [self.split]++ for split_dir in split_dirs:+ split_path = os.path.join(self.root_dir, split_dir)+ if not os.path.exists(split_path):+ continue++ # Get all scene directories+ scene_dirs = sorted([d for d in glob.glob(os.path.join(split_path, '*')) if os.path.isdir(d)])++ if self.subsample_scenes is not None:+ scene_dirs = scene_dirs[::self.subsample_scenes]++ print(f"[SceneNet-{self.split.upper()}] Found {len(scene_dirs)} scenes in {split_dir}/")++ for scene_dir in scene_dirs:+ scene_name = os.path.basename(scene_dir)++ # Get all trajectory directories+ traj_dirs = sorted([d for d in glob.glob(os.path.join(scene_dir, '*')) if os.path.isdir(d)])++ for traj_dir in traj_dirs:+ traj_name = os.path.basename(traj_dir)++ photo_dir = os.path.join(traj_dir, 'photo')+ depth_dir = os.path.join(traj_dir, 'depth')++ if not os.path.isdir(photo_dir) or not os.path.isdir(depth_dir):+ continue++ # Extract frame IDs from RGB filenames (lazy loading)+ rgb_filenames = [f for f in os.listdir(photo_dir) if f.endswith('.jpg')]+ if not rgb_filenames:+ continue++ frame_ids = sorted([os.path.splitext(f)[0] for f in rgb_filenames])++ # Verify at least one depth file exists (spot check)+ if not os.path.exists(os.path.join(depth_dir, f"{frame_ids[0]}.png")):+ continue++ # Apply subsampling if requested+ num_available = len(frame_ids)+ if self.samples_per_scene is not None and num_available > self.samples_per_scene:+ indices = np.linspace(0, num_available - 1, self.samples_per_scene, dtype=int)+ frame_ids = [frame_ids[i] for i in indices]++ # Store trajectory metadata (lazy loading)+ all_data.append({+ 'traj_dir': traj_dir,+ 'scene_name': scene_name,+ 'traj_name': traj_name,+ 'frame_ids': frame_ids,+ 'intrinsics': 'scenenet_fov',+ 'dataset': 'scenenet',+ 'lazy_load': True+ })++ # Count total frames across all trajectories+ total_frames = sum(len(entry['frame_ids']) for entry in all_data)+ print(f"[SceneNet-{self.split.upper()}] Found {len(all_data)} trajectories with {total_frames} valid paired samples.")++ # Save to cache+ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_tartanair(self):+ """+ Find and split TartanAir data.++ Structure: root/{scene}/{difficulty}/{sequence}/image_left/{frame}_left.png+ /depth_left/{frame}_left_depth.npy+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ # Discover all sequences+ all_sequences = []++ scene_dirs = sorted([d for d in glob.glob(os.path.join(self.root_dir, '*')) if os.path.isdir(d)])++ for scene_dir in scene_dirs:+ scene_name = os.path.basename(scene_dir)++ diff_dirs = sorted([d for d in glob.glob(os.path.join(scene_dir, '*')) if os.path.isdir(d)])++ for diff_dir in diff_dirs:+ diff_name = os.path.basename(diff_dir)++ seq_dirs = sorted([d for d in glob.glob(os.path.join(diff_dir, '*')) if os.path.isdir(d)])++ for seq_dir in seq_dirs:+ seq_name = os.path.basename(seq_dir)+ rel_path = f"{scene_name}/{diff_name}/{seq_name}"+ all_sequences.append((seq_dir, rel_path))++ total_sequences = len(all_sequences)++ if self.subsample_scenes is not None:+ all_sequences = all_sequences[::self.subsample_scenes]++ if total_sequences == 0:+ return []++ # Load test split if provided+ manual_test_seqs = set()+ use_manual_split = False++ if self.test_scenes_file:+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading TartanAir test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ manual_test_seqs = {line.strip().replace('\\', '/') for line in f if line.strip()}+ use_manual_split = True+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Filter sequences+ target_sequences = []++ auto_test_indices = set()+ if not use_manual_split and self.num_test_scenes is not None and self.num_test_scenes > 0:+ rng = np.linspace(0, total_sequences - 1, self.num_test_scenes, dtype=int)+ auto_test_indices = set(rng)++ for i, (seq_dir, rel_path) in enumerate(all_sequences):+ is_test = False++ if use_manual_split:+ if rel_path in manual_test_seqs:+ is_test = True+ else:+ if i in auto_test_indices:+ is_test = True++ # Apply split filter+ if self.split == 'train' and not is_test:+ target_sequences.append(seq_dir)+ elif self.split == 'test' and is_test:+ target_sequences.append(seq_dir)+ elif self.split == 'all':+ target_sequences.append(seq_dir)++ print(f"[TartanAir-{self.split.upper()}] Selected {len(target_sequences)} sequences out of {total_sequences}.")++ # MEMORY OPTIMIZATION: Gather data using lazy loading (store only sequence metadata + frame IDs)+ total_frames = 0+ for seq_dir in target_sequences:+ rgb_dir = os.path.join(seq_dir, 'image_left')+ depth_dir = os.path.join(seq_dir, 'depth_left')++ if not os.path.isdir(rgb_dir) or not os.path.isdir(depth_dir):+ continue++ # Extract frame IDs from filenames without storing full paths+ rgb_filenames = [f for f in os.listdir(rgb_dir) if f.endswith('_left.png')]+ frame_ids = sorted([f.replace('.png', '') for f in rgb_filenames])++ # Validate depth files exist+ valid_frame_ids = [fid for fid in frame_ids if os.path.exists(os.path.join(depth_dir, f'{fid}_depth.npy'))]++ del rgb_filenames # Free memory++ # Apply samples_per_scene subsampling+ if self.samples_per_scene is not None and len(valid_frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(valid_frame_ids) - 1, self.samples_per_scene, dtype=int)+ valid_frame_ids = [valid_frame_ids[i] for i in indices]++ if valid_frame_ids:+ all_data.append({+ 'seq_dir': seq_dir,+ 'frame_ids': valid_frame_ids,+ 'intrinsics': 'tartanair_fixed',+ 'dataset': 'tartanair',+ 'lazy_load': True+ })+ total_frames += len(valid_frame_ids)++ print(f"[TartanAir-{self.split.upper()}] Found {len(all_data)} sequences with {total_frames} total frames (lazy loading).")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_tartanairv2(self):+ """+ Find and split TartanAir V2 data with OPTIMIZED LAZY FRAME ENUMERATION.++ Memory-optimized version that stores only trajectory metadata instead of all file paths.+ This reduces memory from ~2GB to ~10MB for the full 4.5M sample dataset.++ Structure: root/{environment}/Data_{difficulty}/{trajectory}/image_{cam}/{frame:06d}_{cam}.png+ /depth_{cam}/{frame:06d}_{cam}_depth.png++ Cameras: lcam_front, lcam_back, lcam_left, lcam_right, lcam_top, lcam_bottom,+ rcam_front, rcam_back, rcam_left, rcam_right, rcam_top, rcam_bottom+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ print(f"[TartanAirV2-{self.split.upper()}] Using OPTIMIZED lazy frame enumeration (low memory mode)")++ # Discover all trajectories across all environments+ all_trajectories = []++ # List of all 12 camera views+ camera_views = [+ 'lcam_front', 'lcam_back', 'lcam_left', 'lcam_right', 'lcam_top', 'lcam_bottom',+ 'rcam_front', 'rcam_back', 'rcam_left', 'rcam_right', 'rcam_top', 'rcam_bottom'+ ]++ env_dirs = sorted([d for d in glob.glob(os.path.join(self.root_dir, '*')) if os.path.isdir(d)])++ for env_dir in env_dirs:+ env_name = os.path.basename(env_dir)++ # Find all difficulty levels (Data_easy, Data_hard, etc.)+ diff_dirs = sorted([d for d in glob.glob(os.path.join(env_dir, 'Data_*')) if os.path.isdir(d)])++ for diff_dir in diff_dirs:+ diff_name = os.path.basename(diff_dir)++ # Find all trajectory folders (P000, P001, etc.)+ traj_dirs = sorted([d for d in glob.glob(os.path.join(diff_dir, 'P*')) if os.path.isdir(d)])++ for traj_dir in traj_dirs:+ traj_name = os.path.basename(traj_dir)+ rel_path = f"{env_name}/{diff_name}/{traj_name}"++ # Each trajectory contains 12 camera views+ for cam in camera_views:+ cam_path = f"{rel_path}/{cam}"+ all_trajectories.append((traj_dir, cam, cam_path))++ total_trajectories = len(all_trajectories)++ if self.subsample_scenes is not None:+ all_trajectories = all_trajectories[::self.subsample_scenes]++ if total_trajectories == 0:+ return []++ # Load test split if provided+ manual_test_trajs = set()+ use_manual_split = False++ if self.test_scenes_file:+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading TartanAir V2 test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ manual_test_trajs = {line.strip().replace('\\', '/') for line in f if line.strip()}+ use_manual_split = True+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Filter trajectories+ target_trajectories = []++ auto_test_indices = set()+ if not use_manual_split and self.num_test_scenes is not None and self.num_test_scenes > 0:+ rng = np.linspace(0, total_trajectories - 1, self.num_test_scenes, dtype=int)+ auto_test_indices = set(rng)++ for i, (traj_dir, cam, cam_path) in enumerate(all_trajectories):+ is_test = False++ if use_manual_split:+ if cam_path in manual_test_trajs:+ is_test = True+ else:+ if i in auto_test_indices:+ is_test = True++ # Apply split filter+ if self.split == 'train' and not is_test:+ target_trajectories.append((traj_dir, cam))+ elif self.split == 'test' and is_test:+ target_trajectories.append((traj_dir, cam))+ elif self.split == 'all':+ target_trajectories.append((traj_dir, cam))++ print(f"[TartanAirV2-{self.split.upper()}] Selected {len(target_trajectories)} camera trajectories out of {total_trajectories}.")++ # OPTIMIZATION: Store only trajectory metadata + frame IDs (not full paths)+ # This reduces memory from ~2GB to ~10MB for full dataset+ total_frames = 0+ for traj_dir, cam in target_trajectories:+ rgb_dir = os.path.join(traj_dir, f'image_{cam}')+ depth_dir = os.path.join(traj_dir, f'depth_{cam}')++ if not os.path.isdir(rgb_dir) or not os.path.isdir(depth_dir):+ continue++ # MEMORY OPTIMIZATION: Find frame IDs without storing full paths+ # Use os.listdir() instead of glob to reduce memory+ try:+ rgb_filenames = [f for f in os.listdir(rgb_dir) if f.endswith(f'_{cam}.png')]+ frame_ids = sorted([f.split('_')[0] for f in rgb_filenames])++ # Verify at least one depth file exists+ if not frame_ids:+ continue++ # Free memory immediately+ del rgb_filenames++ # Apply samples_per_scene subsampling if requested+ if self.samples_per_scene is not None and len(frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(frame_ids) - 1, self.samples_per_scene, dtype=int)+ frame_ids = [frame_ids[i] for i in indices]++ # Store compact metadata: trajectory directory, camera, and frame ID list+ # This entry will be expanded to full paths in __getitem__()+ all_data.append({+ 'traj_dir': traj_dir,+ 'camera': cam,+ 'frame_ids': frame_ids, # List of frame IDs (e.g., ['000000', '000001', ...])+ 'intrinsics': 'tartanairv2_fixed',+ 'dataset': 'tartanairv2',+ 'lazy_load': True # Flag to indicate this needs path construction+ })++ total_frames += len(frame_ids)++ except Exception as e:+ print(f"Warning: Failed to process {traj_dir}/{cam}: {e}")+ continue++ print(f"[TartanAirV2-{self.split.upper()}] Found {len(all_data)} trajectories with {total_frames:,} total frames.")+ print(f"[TartanAirV2-{self.split.upper()}] Memory footprint: ~{len(all_data) * 0.01:.1f} MB (vs ~{total_frames * 0.0002:.0f} MB if storing all paths)")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_vkitti2(self):+ """+ Find and split VKitti2 data.++ Structure: root/{scene}/{variation}/frames/rgb/Camera_{id}/rgb_{frame}.jpg+ /depth/Camera_{id}/depth_{frame}.png+ /intrinsic.txt+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ # Discover all camera sequences+ all_sequences = []++ scene_dirs = sorted([d for d in glob.glob(os.path.join(self.root_dir, 'Scene*')) if os.path.isdir(d)])++ for scene_dir in scene_dirs:+ scene_name = os.path.basename(scene_dir)++ var_dirs = sorted([d for d in glob.glob(os.path.join(scene_dir, '*')) if os.path.isdir(d)])++ for var_dir in var_dirs:+ var_name = os.path.basename(var_dir)++ # Check for camera directories+ rgb_base = os.path.join(var_dir, 'frames', 'rgb')+ if not os.path.exists(rgb_base):+ continue++ cam_dirs = sorted([d for d in glob.glob(os.path.join(rgb_base, 'Camera_*')) if os.path.isdir(d)])++ for cam_dir in cam_dirs:+ cam_name = os.path.basename(cam_dir)+ rel_path = f"{scene_name}/{var_name}/{cam_name}"++ # Store intrinsic file path for this sequence+ intrinsic_file = os.path.join(var_dir, 'intrinsic.txt')++ all_sequences.append((cam_dir, rel_path, var_dir, intrinsic_file))++ total_sequences = len(all_sequences)++ if self.subsample_scenes is not None:+ all_sequences = all_sequences[::self.subsample_scenes]++ if total_sequences == 0:+ return []++ # Load test split if provided+ manual_test_seqs = set()+ use_manual_split = False++ if self.test_scenes_file:+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading VKitti2 test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ manual_test_seqs = {line.strip().replace('\\', '/') for line in f if line.strip()}+ use_manual_split = True+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Filter sequences+ target_sequences = []++ auto_test_indices = set()+ if not use_manual_split and self.num_test_scenes is not None and self.num_test_scenes > 0:+ rng = np.linspace(0, total_sequences - 1, self.num_test_scenes, dtype=int)+ auto_test_indices = set(rng)++ for i, (cam_dir, rel_path, var_dir, intrinsic_file) in enumerate(all_sequences):+ is_test = False++ if use_manual_split:+ if rel_path in manual_test_seqs:+ is_test = True+ else:+ if i in auto_test_indices:+ is_test = True++ # Apply split filter+ if self.split == 'train' and not is_test:+ target_sequences.append((cam_dir, var_dir, intrinsic_file))+ elif self.split == 'test' and is_test:+ target_sequences.append((cam_dir, var_dir, intrinsic_file))+ elif self.split == 'all':+ target_sequences.append((cam_dir, var_dir, intrinsic_file))++ print(f"[VKitti2-{self.split.upper()}] Selected {len(target_sequences)} camera sequences out of {total_sequences}.")++ # Gather data from selected sequences using lazy loading+ total_frames = 0+ for cam_dir, var_dir, intrinsic_file in target_sequences:+ rgb_files = sorted(glob.glob(os.path.join(cam_dir, 'rgb_*.jpg')))++ # Get camera ID from directory name+ cam_name = os.path.basename(cam_dir)+ cam_id = int(cam_name.split('_')[-1])++ # Construct depth directory+ depth_dir = cam_dir.replace('/rgb/', '/depth/')++ if not os.path.isdir(depth_dir):+ continue++ # Extract frame IDs and validate+ valid_frame_ids = []+ for rgb_path in rgb_files:+ filename = os.path.basename(rgb_path)+ frame_str = filename.split('_')[1].split('.')[0] # e.g., '00226'++ depth_filename = f"depth_{frame_str}.png"+ depth_path = os.path.join(depth_dir, depth_filename)++ if os.path.exists(depth_path):+ valid_frame_ids.append(frame_str)++ if not valid_frame_ids:+ continue++ # Subsample frames if requested+ if self.samples_per_scene is not None and len(valid_frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(valid_frame_ids) - 1, self.samples_per_scene, dtype=int)+ valid_frame_ids = [valid_frame_ids[i] for i in indices]++ total_frames += len(valid_frame_ids)++ # Store sequence metadata with lazy loading+ all_data.append({+ 'rgb_dir': cam_dir,+ 'depth_dir': depth_dir,+ 'intrinsics': intrinsic_file,+ 'camera_id': cam_id,+ 'frame_ids': valid_frame_ids,+ 'dataset': 'vkitti2',+ 'lazy_load': True+ })++ print(f"[VKitti2-{self.split.upper()}] Found {len(all_data)} sequences with {total_frames} total frames (lazy loading).")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_hypersim(self):+ """+ Find and split Hypersim data.++ Structure: root/{scene}/{subscene}/{frame:06d}_rgb.png+ /{frame:06d}_depth.npy+ /{frame:06d}_cam.npz+ Example: hypersim_rgbdepth/ai_013_002/cam_00/000000_rgb.png+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ # Discover all subscene directories+ all_subscenes = []++ scene_dirs = sorted([d for d in glob.glob(os.path.join(self.root_dir, '*')) if os.path.isdir(d)])++ for scene_dir in scene_dirs:+ scene_name = os.path.basename(scene_dir)++ subscene_dirs = sorted([d for d in glob.glob(os.path.join(scene_dir, '*')) if os.path.isdir(d)])++ for subscene_dir in subscene_dirs:+ subscene_name = os.path.basename(subscene_dir)+ rel_path = f"{scene_name}/{subscene_name}"+ all_subscenes.append((subscene_dir, rel_path, scene_name))++ total_subscenes = len(all_subscenes)++ if self.subsample_scenes is not None:+ all_subscenes = all_subscenes[::self.subsample_scenes]++ if total_subscenes == 0:+ return []++ # Load test split if provided+ manual_test_scenes = set()+ use_manual_split = False++ if self.test_scenes_file:+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading Hypersim test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ manual_test_scenes = {line.strip() for line in f if line.strip()}+ use_manual_split = True+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Filter subscenes based on split+ target_subscenes = []++ auto_test_indices = set()+ if not use_manual_split and self.num_test_scenes is not None and self.num_test_scenes > 0:+ rng = np.linspace(0, total_subscenes - 1, self.num_test_scenes, dtype=int)+ auto_test_indices = set(rng)++ for i, (subscene_dir, rel_path, scene_name) in enumerate(all_subscenes):+ is_test = False++ if use_manual_split:+ # Check if scene name is in test set+ if scene_name in manual_test_scenes:+ is_test = True+ else:+ if i in auto_test_indices:+ is_test = True++ # Apply split filter+ if self.split == 'train' and not is_test:+ target_subscenes.append(subscene_dir)+ elif self.split == 'test' and is_test:+ target_subscenes.append(subscene_dir)+ elif self.split == 'all':+ target_subscenes.append(subscene_dir)++ print(f"[Hypersim-{self.split.upper()}] Selected {len(target_subscenes)} subscenes out of {total_subscenes}.")++ # Gather data from selected subscenes using lazy loading+ total_frames = 0+ for subscene_dir in target_subscenes:+ rgb_files = sorted(glob.glob(os.path.join(subscene_dir, '*_rgb.png')))++ # Extract frame IDs and validate+ valid_frame_ids = []+ for rgb_path in rgb_files:+ filename = os.path.basename(rgb_path)+ # Extract frame ID from filename like "000000_rgb.png"+ frame_str = filename.split('_')[0]++ depth_path = os.path.join(subscene_dir, f"{frame_str}_depth.npy")+ cam_path = os.path.join(subscene_dir, f"{frame_str}_cam.npz")++ if os.path.exists(depth_path) and os.path.exists(cam_path):+ valid_frame_ids.append(frame_str)++ if not valid_frame_ids:+ continue++ # Subsample frames if requested+ if self.samples_per_scene is not None and len(valid_frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(valid_frame_ids) - 1, self.samples_per_scene, dtype=int)+ valid_frame_ids = [valid_frame_ids[i] for i in indices]++ total_frames += len(valid_frame_ids)++ # Store subscene metadata with lazy loading+ all_data.append({+ 'subscene_dir': subscene_dir,+ 'frame_ids': valid_frame_ids,+ 'dataset': 'hypersim',+ 'lazy_load': True+ })++ print(f"[Hypersim-{self.split.upper()}] Found {len(all_data)} subscenes with {total_frames} total frames (lazy loading).")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_urbansyn(self):+ """+ Find and split UrbanSyn data.++ Structure: root/rgb/rgb_{frame:04d}.png+ /depth/rgb_{frame:04d}.npy (preprocessed, already scaled)+ /cam/rgb_{frame:04d}.npz (per-frame intrinsics)++ Note: Sky pixels are detected based on depth > max_depth threshold,+ no separate sky mask file is needed.+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ rgb_dir = os.path.join(self.root_dir, 'rgb')+ depth_dir = os.path.join(self.root_dir, 'depth')+ cam_dir = os.path.join(self.root_dir, 'cam')++ if not os.path.isdir(rgb_dir) or not os.path.isdir(depth_dir):+ print(f"Error: rgb/ or depth/ directory not found in {self.root_dir}")+ return []++ # Find all RGB files and extract valid frame IDs+ rgb_files = sorted(glob.glob(os.path.join(rgb_dir, 'rgb_*.png')))++ if len(rgb_files) == 0:+ print(f"Error: No RGB files found in {rgb_dir}")+ return []++ # Extract frame IDs and validate+ all_valid_frame_ids = []+ for rgb_path in rgb_files:+ filename = os.path.basename(rgb_path)+ # Extract basename like "rgb_0001"+ basename = filename.replace('.png', '')++ depth_path = os.path.join(depth_dir, f"{basename}.npy")+ cam_path = os.path.join(cam_dir, f"{basename}.npz")++ if os.path.exists(depth_path) and os.path.exists(cam_path):+ all_valid_frame_ids.append(basename)++ total_frames = len(all_valid_frame_ids)++ if total_frames == 0:+ print(f"Error: No matching RGB-depth-cam triplets found")+ return []++ # Apply subsampling if requested+ if self.subsample_scenes is not None:+ all_valid_frame_ids = all_valid_frame_ids[::self.subsample_scenes]+ print(f"[UrbanSyn] Subsampled from {total_frames} to {len(all_valid_frame_ids)} frames")++ # Split into train/test+ # Since this is a single "scene", we use frame-level splitting+ if self.num_test_scenes is not None and self.num_test_scenes > 0:+ # Use uniform sampling for test frames+ num_test_frames = min(self.num_test_scenes, len(all_valid_frame_ids))+ test_indices = set(np.linspace(0, len(all_valid_frame_ids) - 1, num_test_frames, dtype=int))+ else:+ test_indices = set()++ # Filter frame IDs based on split+ if self.split == 'train':+ selected_frame_ids = [all_valid_frame_ids[i] for i in range(len(all_valid_frame_ids)) if i not in test_indices]+ elif self.split == 'test':+ selected_frame_ids = [all_valid_frame_ids[i] for i in sorted(test_indices)]+ elif self.split == 'all':+ selected_frame_ids = all_valid_frame_ids+ else:+ selected_frame_ids = all_valid_frame_ids++ # Apply samples_per_scene subsampling (frame subsampling in this case)+ if self.samples_per_scene is not None and len(selected_frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(selected_frame_ids) - 1, self.samples_per_scene, dtype=int)+ selected_frame_ids = [selected_frame_ids[i] for i in indices]++ # Store as single lazy loading entry+ all_data = [{+ 'rgb_dir': rgb_dir,+ 'depth_dir': depth_dir,+ 'cam_dir': cam_dir,+ 'frame_ids': selected_frame_ids,+ 'dataset': 'urbansyn',+ 'lazy_load': True+ }]++ print(f"[UrbanSyn-{self.split.upper()}] Found {len(selected_frame_ids)} frames (lazy loading, total {total_frames} frames).")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_mvssynth(self):+ """+ Find and split MVSSynth data.++ Structure: root/{sequence}/rgb/{frame}.jpg+ /depth/{frame}.npy+ /cam/{frame}.npz+ Example: mvssynth/GTAV_720/0000/rgb/0000.jpg+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ # Discover all sequence directories+ all_sequences = []++ seq_dirs = sorted([d for d in glob.glob(os.path.join(self.root_dir, '*')) if os.path.isdir(d)])++ for seq_dir in seq_dirs:+ seq_name = os.path.basename(seq_dir)+ all_sequences.append((seq_dir, seq_name))++ total_sequences = len(all_sequences)++ if self.subsample_scenes is not None:+ all_sequences = all_sequences[::self.subsample_scenes]++ if total_sequences == 0:+ return []++ # Load test split if provided (sequence-level)+ manual_test_seqs = set()+ use_manual_split = False++ if self.test_scenes_file:+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading MVSSynth test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ manual_test_seqs = {line.strip() for line in f if line.strip()}+ use_manual_split = True+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Filter sequences based on split+ target_sequences = []++ auto_test_indices = set()+ if not use_manual_split and self.num_test_scenes is not None and self.num_test_scenes > 0:+ rng = np.linspace(0, total_sequences - 1, self.num_test_scenes, dtype=int)+ auto_test_indices = set(rng)++ for i, (seq_dir, seq_name) in enumerate(all_sequences):+ is_test = False++ if use_manual_split:+ # Check if sequence name is in test set+ if seq_name in manual_test_seqs:+ is_test = True+ else:+ if i in auto_test_indices:+ is_test = True++ # Apply split filter+ if self.split == 'train' and not is_test:+ target_sequences.append(seq_dir)+ elif self.split == 'test' and is_test:+ target_sequences.append(seq_dir)+ elif self.split == 'all':+ target_sequences.append(seq_dir)++ print(f"[MVSSynth-{self.split.upper()}] Selected {len(target_sequences)} sequences out of {total_sequences}.")++ # Gather data from selected sequences+ for seq_dir in target_sequences:+ rgb_dir = os.path.join(seq_dir, 'rgb')+ depth_dir = os.path.join(seq_dir, 'depth')+ cam_dir = os.path.join(seq_dir, 'cam')++ if not os.path.isdir(rgb_dir) or not os.path.isdir(depth_dir) or not os.path.isdir(cam_dir):+ continue++ rgb_files = sorted(glob.glob(os.path.join(rgb_dir, '*.jpg')))++ seq_valid_triplets = []++ for rgb_path in rgb_files:+ filename = os.path.basename(rgb_path)+ # Extract frame ID from filename like "0000.jpg"+ frame_str = os.path.splitext(filename)[0]++ depth_path = os.path.join(depth_dir, f"{frame_str}.npy")+ cam_path = os.path.join(cam_dir, f"{frame_str}.npz")++ if os.path.exists(depth_path) and os.path.exists(cam_path):+ seq_valid_triplets.append({+ 'image': rgb_path,+ 'depth': depth_path,+ 'cam_file': cam_path,+ 'dataset': 'mvssynth'+ })++ # Subsample frames if requested+ if self.samples_per_scene is not None and len(seq_valid_triplets) > self.samples_per_scene:+ indices = np.linspace(0, len(seq_valid_triplets) - 1, self.samples_per_scene, dtype=int)+ selected = [seq_valid_triplets[i] for i in indices]+ all_data.extend(selected)+ else:+ all_data.extend(seq_valid_triplets)++ print(f"[MVSSynth-{self.split.upper()}] Found {len(all_data)} valid paired samples.")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_synscapes(self):+ """+ Find and split Synscapes data.++ Structure: root/rgb/{frame}.png+ /depth/{frame}.npy+ /cam/{frame}.npz++ Note: Synscapes is a single flat dataset (no sequences/scenes subdivision).+ We treat all frames as one "scene" for splitting purposes.+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ rgb_dir = os.path.join(self.root_dir, 'rgb')+ depth_dir = os.path.join(self.root_dir, 'depth')+ cam_dir = os.path.join(self.root_dir, 'cam')++ if not os.path.isdir(rgb_dir) or not os.path.isdir(depth_dir) or not os.path.isdir(cam_dir):+ print(f"Error: Synscapes dataset missing required directories (rgb, depth, cam).")+ return []++ # Get all RGB files and extract valid frame IDs+ rgb_files = sorted(glob.glob(os.path.join(rgb_dir, '*.png')))++ if len(rgb_files) == 0:+ print(f"Error: No RGB images found in {rgb_dir}")+ return []++ # Extract frame IDs and validate+ all_valid_frame_ids = []+ for rgb_path in rgb_files:+ filename = os.path.basename(rgb_path)+ frame_str = os.path.splitext(filename)[0]++ depth_path = os.path.join(depth_dir, f"{frame_str}.npy")+ cam_path = os.path.join(cam_dir, f"{frame_str}.npz")++ if os.path.exists(depth_path) and os.path.exists(cam_path):+ all_valid_frame_ids.append(frame_str)++ total_frames = len(all_valid_frame_ids)++ if total_frames == 0:+ print(f"Error: No valid triplets found in {self.root_dir}")+ return []++ # Apply subsampling at the full dataset level if requested+ if self.subsample_scenes is not None:+ all_valid_frame_ids = all_valid_frame_ids[::self.subsample_scenes]++ # Split into train/test+ # For Synscapes (flat dataset), we use uniform sampling for test set+ test_indices = set()++ if self.test_scenes_file:+ # Manual split: load frame indices/names from file+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading Synscapes test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ test_frames = {line.strip() for line in f if line.strip()}++ # Mark test indices based on frame IDs in file+ for i, frame_id in enumerate(all_valid_frame_ids):+ if frame_id in test_frames:+ test_indices.add(i)+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Auto split if no manual split+ if len(test_indices) == 0 and self.num_test_scenes is not None and self.num_test_scenes > 0:+ # Interpret num_test_scenes as number of test frames for flat datasets+ rng = np.linspace(0, len(all_valid_frame_ids) - 1, self.num_test_scenes, dtype=int)+ test_indices = set(rng)++ # Filter frame IDs based on split+ if self.split == 'train':+ selected_frame_ids = [all_valid_frame_ids[i] for i in range(len(all_valid_frame_ids)) if i not in test_indices]+ elif self.split == 'test':+ selected_frame_ids = [all_valid_frame_ids[i] for i in sorted(test_indices)]+ elif self.split == 'all':+ selected_frame_ids = all_valid_frame_ids+ else:+ selected_frame_ids = all_valid_frame_ids++ # Apply per-scene sampling (though Synscapes is one "scene")+ if self.samples_per_scene is not None and len(selected_frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(selected_frame_ids) - 1, self.samples_per_scene, dtype=int)+ selected_frame_ids = [selected_frame_ids[i] for i in indices]++ # Store as single lazy loading entry+ all_data = [{+ 'rgb_dir': rgb_dir,+ 'depth_dir': depth_dir,+ 'cam_dir': cam_dir,+ 'frame_ids': selected_frame_ids,+ 'dataset': 'synscapes',+ 'lazy_load': True+ }]++ print(f"[Synscapes-{self.split.upper()}] Found {len(selected_frame_ids)} frames (lazy loading, total {total_frames}).")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_omniworldgame(self):+ """+ Find and split OmniWorld-Game data.++ Structure: root/videos/OmniWorld-Game/{scene}/color/{frame}.png+ /annotations/OmniWorld-Game/{scene}/depth/{frame}.png+ /annotations/OmniWorld-Game/{scene}/camera/split_{idx}.json+ /annotations/OmniWorld-Game/{scene}/split_info.json++ Each scene contains multiple "splits" with separate camera calibrations.+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ # Discover all scene directories+ videos_dir = os.path.join(self.root_dir, 'videos', 'OmniWorld-Game')+ annotations_dir = os.path.join(self.root_dir, 'annotations', 'OmniWorld-Game')++ if not os.path.isdir(videos_dir) or not os.path.isdir(annotations_dir):+ print(f"Error: OmniWorld-Game dataset missing required directories.")+ print(f"Expected: {videos_dir} and {annotations_dir}")+ return []++ scene_dirs = sorted([d for d in glob.glob(os.path.join(videos_dir, '*')) if os.path.isdir(d)])+ all_scenes = []++ for scene_dir in scene_dirs:+ scene_name = os.path.basename(scene_dir)+ annotation_scene_dir = os.path.join(annotations_dir, scene_name)++ # Check if annotation directory exists+ if not os.path.isdir(annotation_scene_dir):+ continue++ # Check if split_info.json exists+ split_info_path = os.path.join(annotation_scene_dir, 'split_info.json')+ if not os.path.exists(split_info_path):+ continue++ all_scenes.append((scene_dir, annotation_scene_dir, scene_name))++ total_scenes = len(all_scenes)++ if total_scenes == 0:+ print(f"Error: No valid OmniWorld-Game scenes found in {videos_dir}")+ return []++ # Apply scene subsampling if requested+ if self.subsample_scenes is not None:+ all_scenes = all_scenes[::self.subsample_scenes]++ # Load test split if provided (scene-level)+ manual_test_scenes = set()+ use_manual_split = False++ if self.test_scenes_file:+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading OmniWorld-Game test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ manual_test_scenes = {line.strip() for line in f if line.strip()}+ use_manual_split = True+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Filter scenes based on split+ target_scenes = []++ auto_test_indices = set()+ if not use_manual_split and self.num_test_scenes is not None and self.num_test_scenes > 0:+ rng = np.linspace(0, total_scenes - 1, self.num_test_scenes, dtype=int)+ auto_test_indices = set(rng)++ for i, (scene_dir, annotation_scene_dir, scene_name) in enumerate(all_scenes):+ is_test = False++ if use_manual_split:+ if scene_name in manual_test_scenes:+ is_test = True+ else:+ if i in auto_test_indices:+ is_test = True++ # Apply split filter+ if self.split == 'train' and not is_test:+ target_scenes.append((scene_dir, annotation_scene_dir, scene_name))+ elif self.split == 'test' and is_test:+ target_scenes.append((scene_dir, annotation_scene_dir, scene_name))+ elif self.split == 'all':+ target_scenes.append((scene_dir, annotation_scene_dir, scene_name))++ print(f"[OmniWorld-Game-{self.split.upper()}] Selected {len(target_scenes)} scenes out of {total_scenes}.")++ print(f"[OmniWorld-Game-{self.split.upper()}] Using OPTIMIZED lazy loading (low memory mode)")++ # OPTIMIZATION: Store scene metadata instead of individual frame paths+ # This reduces memory from ~530MB to ~27MB for full dataset+ import json+ total_frames = 0++ for scene_dir, annotation_scene_dir, scene_name in target_scenes:+ # Load split_info.json+ split_info_path = os.path.join(annotation_scene_dir, 'split_info.json')+ try:+ with open(split_info_path, 'r', encoding='utf-8') as f:+ split_info = json.load(f)+ except Exception as e:+ print(f"Warning: Failed to load split_info for scene {scene_name}: {e}")+ continue++ color_dir = os.path.join(scene_dir, 'color')+ depth_dir = os.path.join(annotation_scene_dir, 'depth')+ camera_dir = os.path.join(annotation_scene_dir, 'camera')++ if not os.path.isdir(color_dir) or not os.path.isdir(depth_dir) or not os.path.isdir(camera_dir):+ continue++ # Verify camera files exist for all splits+ split_num = split_info['split_num']+ valid_splits = []+ for split_idx in range(split_num):+ cam_file = os.path.join(camera_dir, f'split_{split_idx}.json')+ if os.path.exists(cam_file):+ valid_splits.append(split_idx)++ if not valid_splits:+ continue++ # Store compact scene metadata with frame indices from split_info.json+ # Paths will be constructed on-demand in __getitem__()+ all_data.append({+ 'scene_name': scene_name,+ 'color_dir': color_dir,+ 'depth_dir': depth_dir,+ 'camera_dir': camera_dir,+ 'split_info': split_info, # Contains 'split_num' and 'split' (list of frame indices per split)+ 'valid_splits': valid_splits, # Only splits with existing camera files+ 'dataset': 'omniworldgame',+ 'lazy_load': True # Flag for lazy loading+ })++ # Count total frames for this scene+ scene_frames = sum(len(split_info['split'][i]) for i in valid_splits)+ total_frames += scene_frames++ print(f"[OmniWorld-Game-{self.split.upper()}] Found {len(all_data)} scenes with {total_frames:,} total frames.")+ print(f"[OmniWorld-Game-{self.split.upper()}] Memory footprint: ~{len(all_data) * 0.1:.1f} MB (vs ~{total_frames * 0.00025:.0f} MB if storing all paths)")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_irs(self):+ """+ Find and split IRS data with OPTIMIZED LAZY FRAME ENUMERATION.++ Memory-optimized version that stores only sequence metadata instead of all file paths.+ This reduces memory usage significantly for datasets with many frames.++ Structure: root/{sequence}/rgb/{frame:05d}.png+ /depth/{frame:05d}.npy+ /cam/{frame:05d}.npz++ Example sequences: ArchVizInterior03Data, ModernClassicInterior, ConvenienceStore, etc.+ Depth is z-depth in meters (preprocessed from disparity EXR).+ Intrinsics are per-frame 3x3 matrices (fx=fy=480, cx=width/2, cy=height/2).+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ print(f"[IRS-{self.split.upper()}] Using OPTIMIZED lazy frame enumeration (low memory mode)")++ # Discover all sequence directories+ all_sequences = []+ seq_dirs = sorted([d for d in glob.glob(os.path.join(self.root_dir, '*')) if os.path.isdir(d)])++ for seq_dir in seq_dirs:+ seq_name = os.path.basename(seq_dir)+ # Check if sequence has the expected structure+ rgb_dir = os.path.join(seq_dir, 'rgb')+ depth_dir = os.path.join(seq_dir, 'depth')+ cam_dir = os.path.join(seq_dir, 'cam')++ if os.path.isdir(rgb_dir) and os.path.isdir(depth_dir) and os.path.isdir(cam_dir):+ all_sequences.append((seq_dir, seq_name))++ total_sequences = len(all_sequences)++ if self.subsample_scenes is not None:+ all_sequences = all_sequences[::self.subsample_scenes]++ if total_sequences == 0:+ print(f"Error: No valid IRS sequences found in {self.root_dir}")+ return []++ # Load test split if provided+ manual_test_seqs = set()+ use_manual_split = False++ if self.test_scenes_file:+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading IRS test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ manual_test_seqs = {line.strip() for line in f if line.strip()}+ use_manual_split = True+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Filter sequences based on split+ target_sequences = []++ auto_test_indices = set()+ if not use_manual_split and self.num_test_scenes is not None and self.num_test_scenes > 0:+ rng = np.linspace(0, total_sequences - 1, self.num_test_scenes, dtype=int)+ auto_test_indices = set(rng)++ for i, (seq_dir, seq_name) in enumerate(all_sequences):+ is_test = False++ if use_manual_split:+ if seq_name in manual_test_seqs:+ is_test = True+ else:+ if i in auto_test_indices:+ is_test = True++ # Apply split filter+ if self.split == 'train' and not is_test:+ target_sequences.append((seq_dir, seq_name))+ elif self.split == 'test' and is_test:+ target_sequences.append((seq_dir, seq_name))+ elif self.split == 'all':+ target_sequences.append((seq_dir, seq_name))++ print(f"[IRS-{self.split.upper()}] Selected {len(target_sequences)} sequences out of {total_sequences}.")++ # OPTIMIZATION: Store only sequence metadata + frame IDs (not full paths)+ # This reduces memory usage significantly for large datasets+ total_frames = 0+ for seq_dir, seq_name in target_sequences:+ rgb_dir = os.path.join(seq_dir, 'rgb')+ depth_dir = os.path.join(seq_dir, 'depth')+ cam_dir = os.path.join(seq_dir, 'cam')++ # MEMORY OPTIMIZATION: Find frame IDs without storing full paths+ # Use os.listdir() instead of glob to reduce memory+ try:+ rgb_filenames = [f for f in os.listdir(rgb_dir) if f.endswith('.png')]+ # Extract frame IDs from filenames (e.g., "00001.png" -> "00001")+ all_frame_ids = sorted([f.replace('.png', '') for f in rgb_filenames])++ # Verify at least one frame exists+ if not all_frame_ids:+ continue++ # Free memory immediately+ del rgb_filenames++ # FILTER INCOMPLETE FILES: Only keep frames where RGB, depth, and cam all exist+ # This prevents FileNotFoundError when some files are missing+ frame_ids = []+ skipped_count = 0+ for frame_id in all_frame_ids:+ depth_file = os.path.join(depth_dir, f'{frame_id}.npy')+ cam_file = os.path.join(cam_dir, f'{frame_id}.npz')+ if os.path.exists(depth_file) and os.path.exists(cam_file):+ frame_ids.append(frame_id)+ else:+ skipped_count += 1++ if skipped_count > 0:+ print(f" Warning: Sequence {seq_name} has {skipped_count} incomplete frames (missing depth/cam files), skipping them.")++ # Verify at least one complete frame exists+ if not frame_ids:+ continue++ # Apply samples_per_scene subsampling if requested+ if self.samples_per_scene is not None and len(frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(frame_ids) - 1, self.samples_per_scene, dtype=int)+ frame_ids = [frame_ids[i] for i in indices]++ # Store compact metadata: sequence directory and frame ID list+ # This entry will be expanded to full paths in __getitem__()+ all_data.append({+ 'seq_dir': seq_dir,+ 'seq_name': seq_name,+ 'frame_ids': frame_ids, # List of frame IDs (e.g., ['00001', '00002', ...])+ 'dataset': 'irs',+ 'lazy_load': True # Flag to indicate this needs path construction+ })++ total_frames += len(frame_ids)++ except Exception as e:+ print(f"Warning: Failed to process {seq_dir}: {e}")+ continue++ print(f"[IRS-{self.split.upper()}] Found {len(all_data)} sequences with {total_frames:,} total frames.")+ print(f"[IRS-{self.split.upper()}] Memory footprint: ~{len(all_data) * 0.01:.1f} MB (vs ~{total_frames * 0.0002:.0f} MB if storing all paths)")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_dynamic_replica(self):+ """+ Find and split Dynamic Replica data with OPTIMIZED LAZY FRAME ENUMERATION.++ Memory-optimized version that stores only sequence metadata instead of all file paths.+ This reduces memory usage significantly for datasets with many frames.++ Structure: root/{split}/{sequence}/left/rgb/{timestamp}.png+ /depth/{timestamp}.npy+ /cam/{timestamp}.npz++ Note: Only 'left' camera has data (right directories are empty).+ Timestamps are float strings (e.g., '0.0', '0.03333333333333333').+ Depth is z-depth in meters (float32).+ Intrinsics are fixed: fx=fy=700, cx=640, cy=360 at 1280x720.+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ print(f"[DynamicReplica-{self.split.upper()}] Using OPTIMIZED lazy frame enumeration (low memory mode)")++ # Determine which splits to use+ if self.split == 'all':+ split_dirs = ['train', 'valid', 'test']+ elif self.split == 'train':+ split_dirs = ['train']+ elif self.split == 'val' or self.split == 'valid':+ split_dirs = ['valid']+ elif self.split == 'test':+ split_dirs = ['test']+ else:+ split_dirs = [self.split]++ # Discover all sequence directories across selected splits+ all_sequences = []+ for split_dir in split_dirs:+ split_path = os.path.join(self.root_dir, split_dir)+ if not os.path.exists(split_path):+ print(f"Warning: Split directory {split_path} does not exist, skipping.")+ continue++ seq_dirs = sorted([d for d in glob.glob(os.path.join(split_path, '*')) if os.path.isdir(d)])+ print(f"[DynamicReplica] Found {len(seq_dirs)} sequences in {split_dir}/")++ for seq_dir in seq_dirs:+ seq_name = os.path.basename(seq_dir)+ # Only use 'left' camera (right is empty in the preprocessed data)+ cam_path = os.path.join(seq_dir, 'left')+ rgb_dir = os.path.join(cam_path, 'rgb')+ depth_dir = os.path.join(cam_path, 'depth')+ cam_dir = os.path.join(cam_path, 'cam')++ if os.path.isdir(rgb_dir) and os.path.isdir(depth_dir) and os.path.isdir(cam_dir):+ all_sequences.append((seq_dir, seq_name, split_dir))++ total_sequences = len(all_sequences)++ if self.subsample_scenes is not None:+ all_sequences = all_sequences[::self.subsample_scenes]++ if total_sequences == 0:+ print(f"Error: No valid Dynamic Replica sequences found in {self.root_dir}")+ return []++ print(f"[DynamicReplica-{self.split.upper()}] Selected {len(all_sequences)} sequences out of {total_sequences}.")++ # OPTIMIZATION: Store only sequence metadata + frame IDs (not full paths)+ total_frames = 0+ for seq_dir, seq_name, orig_split in all_sequences:+ cam_path = os.path.join(seq_dir, 'left')+ rgb_dir = os.path.join(cam_path, 'rgb')+ depth_dir = os.path.join(cam_path, 'depth')+ cam_dir = os.path.join(cam_path, 'cam')++ # MEMORY OPTIMIZATION: Find frame IDs without storing full paths+ try:+ rgb_filenames = [f for f in os.listdir(rgb_dir) if f.endswith('.png')]+ # Extract timestamp IDs from filenames (e.g., "0.0.png" -> "0.0")+ # Sort by numeric value to ensure proper temporal ordering+ all_frame_ids = sorted([f.replace('.png', '') for f in rgb_filenames],+ key=lambda x: float(x))++ if not all_frame_ids:+ continue++ del rgb_filenames++ # FILTER INCOMPLETE FILES: Only keep frames where RGB, depth, and cam all exist+ frame_ids = []+ skipped_count = 0+ for frame_id in all_frame_ids:+ depth_file = os.path.join(depth_dir, f'{frame_id}.npy')+ cam_file = os.path.join(cam_dir, f'{frame_id}.npz')+ if os.path.exists(depth_file) and os.path.exists(cam_file):+ frame_ids.append(frame_id)+ else:+ skipped_count += 1++ if skipped_count > 0:+ print(f" Warning: Sequence {seq_name} has {skipped_count} incomplete frames, skipping them.")++ if not frame_ids:+ continue++ # Apply samples_per_scene subsampling if requested+ if self.samples_per_scene is not None and len(frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(frame_ids) - 1, self.samples_per_scene, dtype=int)+ frame_ids = [frame_ids[i] for i in indices]++ # Store compact metadata+ all_data.append({+ 'seq_dir': seq_dir,+ 'seq_name': seq_name,+ 'frame_ids': frame_ids,+ 'dataset': 'dynamic_replica',+ 'lazy_load': True+ })++ total_frames += len(frame_ids)++ except Exception as e:+ print(f"Warning: Failed to process {seq_dir}: {e}")+ continue++ print(f"[DynamicReplica-{self.split.upper()}] Found {len(all_data)} sequences with {total_frames:,} total frames.")+ print(f"[DynamicReplica-{self.split.upper()}] Memory footprint: ~{len(all_data) * 0.01:.1f} MB (vs ~{total_frames * 0.0002:.0f} MB if storing all paths)")++ self._save_cache(all_data)++ return all_data++ def _find_and_split_data_eden(self):+ """+ Find and split Eden data with LAZY LOADING.++ Structure: root/{scene_id}_{lighting_mode}/rgb/{basename}.png+ /depth/{basename}.npy+ /cam/{basename}.npz++ Example: eden/0001_clear/rgb/A_0001.png+ Lighting modes: clear, cloudy, overcast, sunset, twilight++ Depth is z-depth in meters (float32).+ Intrinsics are per-frame 3x3 matrices stored in .npz files.+ """+ cached_data = self._load_cache()+ if cached_data is not None:+ return cached_data++ all_data = []++ if not os.path.exists(self.root_dir):+ print(f"Error: Root directory {self.root_dir} does not exist.")+ return []++ # Discover all sequence directories (e.g., 0001_clear, 0001_cloudy)+ all_sequences = []+ for seq_name in sorted(os.listdir(self.root_dir)):+ seq_dir = os.path.join(self.root_dir, seq_name)+ if os.path.isdir(seq_dir):+ # Check if sequence has the expected structure (rgb/, depth/, cam/)+ rgb_dir = os.path.join(seq_dir, 'rgb')+ depth_dir = os.path.join(seq_dir, 'depth')+ cam_dir = os.path.join(seq_dir, 'cam')++ if os.path.isdir(rgb_dir) and os.path.isdir(depth_dir) and os.path.isdir(cam_dir):+ all_sequences.append((seq_dir, seq_name))++ total_sequences = len(all_sequences)++ if self.subsample_scenes is not None:+ all_sequences = all_sequences[::self.subsample_scenes]++ if total_sequences == 0:+ print(f"Error: No valid Eden sequences found in {self.root_dir}")+ return []++ # Load test split if provided+ manual_test_scenes = set()+ use_manual_split = False++ if self.test_scenes_file:+ resolved_path = self.test_scenes_file+ if not os.path.exists(resolved_path):+ script_dir = os.path.dirname(os.path.abspath(__file__))+ resolved_path = os.path.join(script_dir, self.test_scenes_file)++ if os.path.exists(resolved_path):+ print(f"Loading Eden test split from: {resolved_path}")+ with open(resolved_path, 'r') as f:+ manual_test_scenes = {line.strip() for line in f if line.strip()}+ use_manual_split = True+ else:+ print(f"Warning: File {self.test_scenes_file} not found.")++ # Filter sequences based on split+ target_sequences = []++ auto_test_indices = set()+ if not use_manual_split and self.num_test_scenes is not None and self.num_test_scenes > 0:+ rng = np.linspace(0, total_sequences - 1, self.num_test_scenes, dtype=int)+ auto_test_indices = set(rng)++ for i, (seq_dir, seq_name) in enumerate(all_sequences):+ is_test = False++ if use_manual_split:+ if seq_name in manual_test_scenes:+ is_test = True+ else:+ if i in auto_test_indices:+ is_test = True++ # Apply split filter+ if self.split == 'train' and not is_test:+ target_sequences.append((seq_dir, seq_name))+ elif self.split == 'test' and is_test:+ target_sequences.append((seq_dir, seq_name))+ elif self.split == 'all':+ target_sequences.append((seq_dir, seq_name))++ print(f"[Eden-{self.split.upper()}] Selected {len(target_sequences)} sequences out of {total_sequences}.")++ # Gather data from selected sequences using lazy loading+ total_frames = 0+ for seq_dir, seq_name in target_sequences:+ rgb_dir = os.path.join(seq_dir, 'rgb')+ depth_dir = os.path.join(seq_dir, 'depth')+ cam_dir = os.path.join(seq_dir, 'cam')++ # Find all RGB files and extract basenames+ rgb_filenames = [f for f in os.listdir(rgb_dir) if f.endswith('.png')]+ if not rgb_filenames:+ continue++ # Extract basenames (e.g., "A_0001.png" -> "A_0001")+ all_basenames = sorted([f.replace('.png', '') for f in rgb_filenames])++ # Validate that depth and cam files exist+ valid_frame_ids = []+ for basename in all_basenames:+ depth_path = os.path.join(depth_dir, f'{basename}.npy')+ cam_path = os.path.join(cam_dir, f'{basename}.npz')+ if os.path.exists(depth_path) and os.path.exists(cam_path):+ valid_frame_ids.append(basename)++ if not valid_frame_ids:+ continue++ # Apply samples_per_scene subsampling if requested+ if self.samples_per_scene is not None and len(valid_frame_ids) > self.samples_per_scene:+ indices = np.linspace(0, len(valid_frame_ids) - 1, self.samples_per_scene, dtype=int)+ valid_frame_ids = [valid_frame_ids[i] for i in indices]++ total_frames += len(valid_frame_ids)++ # Store sequence metadata with lazy loading+ all_data.append({+ 'seq_dir': seq_dir,+ 'seq_name': seq_name,+ 'frame_ids': valid_frame_ids,+ 'dataset': 'eden',+ 'lazy_load': True+ })++ print(f"[Eden-{self.split.upper()}] Found {len(all_data)} sequences with {total_frames} total frames (lazy loading).")++ self._save_cache(all_data)++ return all_data++ def __len__(self):+ # Calculate total length including lazy-loaded entries+ total_len = 0+ for entry in self.all_data_paths:+ if entry.get('lazy_load', False):+ dataset = entry.get('dataset', '')+ if dataset == 'tartanairv2':+ # TartanAirV2 lazy-loaded trajectory+ total_len += len(entry['frame_ids'])+ elif dataset == 'tartanair':+ # TartanAir lazy-loaded sequence+ total_len += len(entry['frame_ids'])+ elif dataset == 'scenenet':+ # SceneNet lazy-loaded trajectory+ total_len += len(entry['frame_ids'])+ elif dataset == 'omniworldgame':+ # OmniWorld-Game lazy-loaded scene+ # Count frames across all valid splits+ for split_idx in entry['valid_splits']:+ total_len += len(entry['split_info']['split'][split_idx])+ elif dataset == 'irs':+ # IRS lazy-loaded sequence+ total_len += len(entry['frame_ids'])+ elif dataset == 'dynamic_replica':+ # Dynamic Replica lazy-loaded sequence+ total_len += len(entry['frame_ids'])+ elif dataset == 'hypersim':+ # Hypersim lazy-loaded subscene+ total_len += len(entry['frame_ids'])+ elif dataset == 'vkitti2':+ # VKitti2 lazy-loaded sequence+ total_len += len(entry['frame_ids'])+ elif dataset == 'urbansyn':+ # UrbanSyn lazy-loaded dataset+ total_len += len(entry['frame_ids'])+ elif dataset == 'synscapes':+ # Synscapes lazy-loaded dataset+ total_len += len(entry['frame_ids'])+ elif dataset == 'eden':+ # Eden lazy-loaded sequence+ total_len += len(entry['frame_ids'])+ else:+ # Regular sample with explicit paths+ total_len += 1+ return total_len++ def _compute_cumulative_indices(self):+ """+ Pre-compute cumulative frame counts for O(log n) index lookup.++ Similar to PyTorch's ConcatDataset.cumulative_sizes pattern.+ This enables binary search instead of linear search in __getitem__.++ Creates self._cumulative_indices: list where each element is the cumulative+ count of frames up to that entry index. Used with bisect.bisect_right()+ to find which entry contains a given global index.+ """+ cumulative = [0]+ for entry in self.all_data_paths:+ if entry.get('lazy_load', False):+ dataset = entry.get('dataset', '')++ # Count frames based on dataset type+ if dataset == 'tartanairv2':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'tartanair':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'scenenet':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'omniworldgame':+ # Count frames across all valid splits+ num_frames = sum(len(entry['split_info']['split'][split_idx])+ for split_idx in entry['valid_splits'])+ elif dataset == 'irs':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'dynamic_replica':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'hypersim':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'vkitti2':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'urbansyn':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'synscapes':+ num_frames = len(entry['frame_ids'])+ elif dataset == 'eden':+ num_frames = len(entry['frame_ids'])+ else:+ # Unknown dataset - assume single frame+ num_frames = 1++ cumulative.append(cumulative[-1] + num_frames)+ else:+ # Regular entry with explicit paths+ cumulative.append(cumulative[-1] + 1)++ self._cumulative_indices = cumulative+ print(f"[{self.dataset_name.upper()}] Computed cumulative indices: {len(cumulative)} entries, {cumulative[-1]} total frames")++ def __getitem__(self, idx, _retry=0):+ _MAX_RETRIES = 10+ try:+ return self._getitem_impl(idx)+ except (UnidentifiedImageError, OSError, IOError, EOFError) as e:+ if _retry < _MAX_RETRIES:+ print(f"[WARNING] Skipping corrupted sample idx={idx}: {e}")+ new_idx = random.randint(0, len(self) - 1)+ return self.__getitem__(new_idx, _retry=_retry + 1)+ else:+ raise RuntimeError(f"Too many corrupted samples (>{_MAX_RETRIES} retries). Last error: {e}")++ def _getitem_impl(self, idx):++ t_start = time.perf_counter() if self.debug_timing else None++ # OPTIMIZATION: Use binary search for O(log n) lookup instead of O(n) linear search+ entry_idx = bisect.bisect_right(self._cumulative_indices, idx) - 1+ frame_idx = idx - self._cumulative_indices[entry_idx]++ entry = self.all_data_paths[entry_idx]++ # Handle lazy-loaded entries+ if entry.get('lazy_load', False):+ dataset = entry.get('dataset', '')++ if dataset == 'tartanairv2':+ # TartanAirV2 lazy-loaded trajectory+ traj_dir = entry['traj_dir']+ cam = entry['camera']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(traj_dir, f'image_{cam}', f'{frame_id}_{cam}.png'),+ 'depth': os.path.join(traj_dir, f'depth_{cam}', f'{frame_id}_{cam}_depth.png'),+ 'intrinsics': entry['intrinsics'],+ 'dataset': entry['dataset']+ }++ elif dataset == 'tartanair':+ # TartanAir lazy-loaded sequence+ seq_dir = entry['seq_dir']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(seq_dir, 'image_left', f'{frame_id}.png'),+ 'depth': os.path.join(seq_dir, 'depth_left', f'{frame_id}_depth.npy'),+ 'intrinsics': entry['intrinsics'],+ 'dataset': entry['dataset']+ }++ elif dataset == 'scenenet':+ # SceneNet lazy-loaded trajectory+ traj_dir = entry['traj_dir']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(traj_dir, 'photo', f'{frame_id}.jpg'),+ 'depth': os.path.join(traj_dir, 'depth', f'{frame_id}.png'),+ 'intrinsics': entry['intrinsics'],+ 'dataset': entry['dataset']+ }++ elif dataset == 'omniworldgame':+ # OmniWorld-Game lazy-loaded scene - map frame_idx to correct split+ current_idx = frame_idx+ for split_idx in entry['valid_splits']:+ frames_in_split = entry['split_info']['split'][split_idx]+ if current_idx < len(frames_in_split):+ # Found the correct split+ frame_idx_global = frames_in_split[current_idx]+ frame_str = f"{frame_idx_global:06d}"++ data_pair = {+ 'image': os.path.join(entry['color_dir'], f'{frame_str}.png'),+ 'depth': os.path.join(entry['depth_dir'], f'{frame_str}.png'),+ 'cam_file': os.path.join(entry['camera_dir'], f'split_{split_idx}.json'),+ 'split_idx': split_idx,+ 'frame_idx_in_split': current_idx,+ 'dataset': entry['dataset']+ }+ break+ else:+ current_idx -= len(frames_in_split)++ elif dataset == 'irs':+ # IRS lazy-loaded sequence+ seq_dir = entry['seq_dir']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(seq_dir, 'rgb', f'{frame_id}.png'),+ 'depth': os.path.join(seq_dir, 'depth', f'{frame_id}.npy'),+ 'cam_file': os.path.join(seq_dir, 'cam', f'{frame_id}.npz'),+ 'dataset': entry['dataset']+ }++ elif dataset == 'dynamic_replica':+ # Dynamic Replica lazy-loaded sequence+ seq_dir = entry['seq_dir']+ frame_id = entry['frame_ids'][frame_idx]++ # Only use 'left' camera (right is empty)+ cam_path = os.path.join(seq_dir, 'left')+ data_pair = {+ 'image': os.path.join(cam_path, 'rgb', f'{frame_id}.png'),+ 'depth': os.path.join(cam_path, 'depth', f'{frame_id}.npy'),+ 'cam_file': os.path.join(cam_path, 'cam', f'{frame_id}.npz'),+ 'dataset': entry['dataset']+ }++ elif dataset == 'hypersim':+ # Hypersim lazy-loaded subscene+ subscene_dir = entry['subscene_dir']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(subscene_dir, f'{frame_id}_rgb.png'),+ 'depth': os.path.join(subscene_dir, f'{frame_id}_depth.npy'),+ 'cam_file': os.path.join(subscene_dir, f'{frame_id}_cam.npz'),+ 'dataset': entry['dataset']+ }++ elif dataset == 'vkitti2':+ # VKitti2 lazy-loaded sequence+ rgb_dir = entry['rgb_dir']+ depth_dir = entry['depth_dir']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(rgb_dir, f'rgb_{frame_id}.jpg'),+ 'depth': os.path.join(depth_dir, f'depth_{frame_id}.png'),+ 'intrinsics': entry['intrinsics'],+ 'camera_id': entry['camera_id'],+ 'frame_idx': int(frame_id),+ 'dataset': entry['dataset']+ }++ elif dataset == 'urbansyn':+ # UrbanSyn lazy-loaded dataset+ rgb_dir = entry['rgb_dir']+ depth_dir = entry['depth_dir']+ cam_dir = entry['cam_dir']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(rgb_dir, f'{frame_id}.png'),+ 'depth': os.path.join(depth_dir, f'{frame_id}.npy'),+ 'cam_file': os.path.join(cam_dir, f'{frame_id}.npz'),+ 'dataset': entry['dataset']+ }++ elif dataset == 'synscapes':+ # Synscapes lazy-loaded dataset+ rgb_dir = entry['rgb_dir']+ depth_dir = entry['depth_dir']+ cam_dir = entry['cam_dir']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(rgb_dir, f'{frame_id}.png'),+ 'depth': os.path.join(depth_dir, f'{frame_id}.npy'),+ 'cam_file': os.path.join(cam_dir, f'{frame_id}.npz'),+ 'dataset': entry['dataset']+ }++ elif dataset == 'eden':+ # Eden lazy-loaded sequence+ seq_dir = entry['seq_dir']+ frame_id = entry['frame_ids'][frame_idx]++ data_pair = {+ 'image': os.path.join(seq_dir, 'rgb', f'{frame_id}.png'),+ 'depth': os.path.join(seq_dir, 'depth', f'{frame_id}.npy'),+ 'cam_file': os.path.join(seq_dir, 'cam', f'{frame_id}.npz'),+ 'dataset': entry['dataset']+ }++ else:+ raise ValueError(f"Unknown lazy-loaded dataset: {dataset}")+ else:+ # Regular entry with explicit paths+ data_pair = entry++ # 1. Load Image+ img_pil = Image.open(data_pair['image']).convert("RGB")++ # 2. Load Depth and Convert to Pointcloud+ if self.dataset_name == 'scenenet':+ # Load depth (16-bit PNG in mm)+ depth_img = Image.open(data_pair['depth'])+ depth_map_np = np.array(depth_img).astype(np.float32) * 0.001 # mm to meters++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Resize if requested (using torch for speed)+ if self.resize_height is not None or self.resize_width is not None:+ orig_w, orig_h = img_pil.size+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Get cached ray array (or compute if not cached)+ cache_key = (new_w, new_h)+ if cache_key not in self._ray_cache:+ self._ray_cache[cache_key] = scenenet_ray_directions(width=new_w, height=new_h, device=self.conversion_device)+ ray_array = self._ray_cache[cache_key]++ # Compute intrinsics for resized image+ fx, fy, cx, cy = compute_scenenet_intrinsics(new_w, new_h)+ else:+ # Use pre-cached default size ray array+ ray_array = self._ray_cache[(320, 240)]+ # Default intrinsics for 320x240+ fx, fy, cx, cy = compute_scenenet_intrinsics(320, 240)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert ray-depth to 3D points (GPU accelerated)+ pc_tensor = raydepth_to_points(depth_map, ray_array) # (H, W, 3)++ # Convert back to numpy for rest of pipeline (temporary, will optimize further later)+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'tartanair':+ # Load z-depth (NPY in meters)+ depth_map_np = np.load(data_pair['depth']).astype(np.float32)++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # TartanAir fixed intrinsics: fx=fy=320, cx=320, cy=240 for 640x480+ orig_fx, orig_fy, orig_cx, orig_cy = 320.0, 320.0, 320.0, 240.0+ orig_w, orig_h = img_pil.size++ # Resize logic+ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = orig_fx * scale+ fy = orig_fy * scale+ cx = orig_cx * scale+ cy = orig_cy * scale++ # Get backprojection grid+ cache_key = (new_w, new_h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(new_w, new_h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ fx, fy, cx, cy = orig_fx, orig_fy, orig_cx, orig_cy+ cache_key = (640, 480, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ backproj_grid = self._backproj_cache[cache_key]++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = orig_fx * scale+ fy = orig_fy * scale+ cx = orig_cx * scale+ cy = orig_cy * scale++ # Get cached backprojection grid (or compute if not cached)+ cache_key = (new_w, new_h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(new_w, new_h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ # Use pre-cached default size grid+ fx, fy, cx, cy = orig_fx, orig_fy, orig_cx, orig_cy+ cache_key = (640, 480, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ backproj_grid = self._backproj_cache[cache_key]++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'tartanairv2':+ # Load z-depth (RGBA PNG encoding float32)+ depth_map_np = read_decode_tartanairv2_depth(data_pair['depth'])++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # TartanAir V2 fixed intrinsics: fx=fy=cx=cy=320 for 640x640+ orig_fx, orig_fy, orig_cx, orig_cy = 320.0, 320.0, 320.0, 320.0+ orig_w, orig_h = img_pil.size++ # Resize logic+ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = orig_fx * scale+ fy = orig_fy * scale+ cx = orig_cx * scale+ cy = orig_cy * scale++ # Get backprojection grid+ cache_key = (new_w, new_h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(new_w, new_h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ fx, fy, cx, cy = orig_fx, orig_fy, orig_cx, orig_cy+ cache_key = (640, 640, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ backproj_grid = self._backproj_cache[cache_key]++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = orig_fx * scale+ fy = orig_fy * scale+ cx = orig_cx * scale+ cy = orig_cy * scale++ # Get cached backprojection grid (or compute if not cached)+ cache_key = (new_w, new_h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(new_w, new_h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ # Use pre-cached default size grid (640x640)+ fx, fy, cx, cy = orig_fx, orig_fy, orig_cx, orig_cy+ cache_key = (640, 640, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ backproj_grid = self._backproj_cache[cache_key]++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'vkitti2':+ # Load z-depth (16-bit PNG in cm)+ import cv2+ depth_raw = cv2.imread(data_pair['depth'], cv2.IMREAD_ANYDEPTH)+ depth_map_np = depth_raw.astype(np.float32) / 100.0 # cm to meters++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Get intrinsics for this frame+ intrinsic_file = data_pair['intrinsics']++ # Cache intrinsics file parsing+ if intrinsic_file not in self.vkitti2_intrinsics_cache:+ self.vkitti2_intrinsics_cache[intrinsic_file] = load_vkitti_intrinsics(intrinsic_file)++ intrinsics_map = self.vkitti2_intrinsics_cache[intrinsic_file]++ frame_idx = data_pair['frame_idx']+ camera_id = data_pair['camera_id']++ if (frame_idx, camera_id) not in intrinsics_map:+ raise ValueError(f"Intrinsics not found for frame {frame_idx}, camera {camera_id}")++ fx, fy, cx, cy = intrinsics_map[(frame_idx, camera_id)]++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Get cached backprojection grid (or compute if not cached)+ cache_key = (w, h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'hypersim':+ # Load z-depth (.npy in meters)+ depth_map_np = np.load(data_pair['depth']).astype(np.float32)++ # FIX: Filter invalid depth values to prevent NaN propagation+ depth_map_np[~np.isfinite(depth_map_np)] = 0.++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Load intrinsics from .npz file (conditionally cache to avoid OOM with per-frame intrinsics)+ cam_file = data_pair['cam_file']+ if self._use_cam_cache:+ if cam_file not in self.hypersim_cam_cache:+ self.hypersim_cam_cache[cam_file] = np.load(cam_file)+ cam_data = self.hypersim_cam_cache[cam_file]+ else:+ cam_data = np.load(cam_file)+ K = cam_data['intrinsics'] # [3, 3]+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]++ # FIX: Validate intrinsics - skip samples with invalid focal lengths+ if not (np.isfinite(fx) and np.isfinite(fy) and np.isfinite(cx) and np.isfinite(cy)):+ print(f"[WARNING] Hypersim sample has non-finite intrinsics: fx={fx}, fy={fy}, cx={cx}, cy={cy}")+ # Return a dummy sample with zeros+ dummy_img = torch.zeros(3, 256, 256)+ dummy_pc = torch.zeros(3, 256, 256)+ return {+ 'image': dummy_img,+ 'pointcloud': dummy_pc,+ 'scale_factor': torch.tensor(1.0),+ 'dataset_name': self.dataset_name,+ 'intrinsics': (fx, fy, cx, cy),+ 'valid_mask': torch.zeros(256, 256, dtype=torch.bool),+ 'sky_mask': torch.zeros(256, 256, dtype=torch.bool),+ }++ if fx <= 0 or fy <= 0:+ print(f"[WARNING] Hypersim sample has invalid focal lengths: fx={fx}, fy={fy}")+ # Return a dummy sample with zeros+ dummy_img = torch.zeros(3, 256, 256)+ dummy_pc = torch.zeros(3, 256, 256)+ return {+ 'image': dummy_img,+ 'pointcloud': dummy_pc,+ 'scale_factor': torch.tensor(1.0),+ 'dataset_name': self.dataset_name,+ 'intrinsics': (fx, fy, cx, cy),+ 'valid_mask': torch.zeros(256, 256, dtype=torch.bool),+ 'sky_mask': torch.zeros(256, 256, dtype=torch.bool),+ }++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Get backprojection grid - compute on-the-fly for variable intrinsics datasets+ # to avoid unbounded cache growth (Hypersim has per-frame intrinsics)+ if self._use_backproj_cache:+ cache_key = (w, h, round(fx, 6), round(fy, 6), round(cx, 6), round(cy, 6))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ backproj_grid = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'urbansyn':+ # Load z-depth (NPY in meters, preprocessed)+ depth_map_np = np.load(data_pair['depth']).astype(np.float32)++ # Filter invalid depth values to prevent NaN propagation+ depth_map_np[~np.isfinite(depth_map_np)] = 0.++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Load intrinsics from .npz file (conditionally cache to avoid OOM)+ cam_file = data_pair['cam_file']+ if self._use_cam_cache:+ if not hasattr(self, 'urbansyn_cam_cache'):+ self.urbansyn_cam_cache = {}+ if cam_file not in self.urbansyn_cam_cache:+ self.urbansyn_cam_cache[cam_file] = np.load(cam_file)+ cam_data = self.urbansyn_cam_cache[cam_file]+ else:+ cam_data = np.load(cam_file)+ K = cam_data['intrinsics'] # [3, 3]+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Get backprojection grid - compute on-the-fly for variable intrinsics datasets+ if self._use_backproj_cache:+ cache_key = (w, h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ backproj_grid = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'mvssynth':+ # Load z-depth (NPY in centimeters, preprocessed from EXR)+ depth_map_np = np.load(data_pair['depth']).astype(np.float32)++ # Filter invalid depth values to prevent NaN propagation+ depth_map_np[~np.isfinite(depth_map_np)] = 0.++ # Convert from centimeters to meters+ depth_map_np = depth_map_np / 100.0++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Load intrinsics from .npz file (conditionally cache to avoid OOM)+ cam_file = data_pair['cam_file']+ if self._use_cam_cache:+ if not hasattr(self, 'mvssynth_cam_cache'):+ self.mvssynth_cam_cache = {}+ if cam_file not in self.mvssynth_cam_cache:+ self.mvssynth_cam_cache[cam_file] = np.load(cam_file)+ cam_data = self.mvssynth_cam_cache[cam_file]+ else:+ cam_data = np.load(cam_file)+ K = cam_data['intrinsics'] # [3, 3]+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Get backprojection grid - compute on-the-fly for variable intrinsics datasets+ if self._use_backproj_cache:+ cache_key = (w, h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ backproj_grid = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'synscapes':+ # Load z-depth (NPY in meters, preprocessed from EXR)+ depth_map_np = np.load(data_pair['depth']).astype(np.float32)++ # Filter invalid depth values to prevent NaN propagation+ depth_map_np[~np.isfinite(depth_map_np)] = 0.++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Load intrinsics from .npz file (conditionally cache to avoid OOM)+ cam_file = data_pair['cam_file']+ if self._use_cam_cache:+ if not hasattr(self, 'synscapes_cam_cache'):+ self.synscapes_cam_cache = {}+ if cam_file not in self.synscapes_cam_cache:+ self.synscapes_cam_cache[cam_file] = np.load(cam_file)+ cam_data = self.synscapes_cam_cache[cam_file]+ else:+ cam_data = np.load(cam_file)+ K = cam_data['intrinsics'] # [3, 3]+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Get backprojection grid - compute on-the-fly for variable intrinsics datasets+ if self._use_backproj_cache:+ cache_key = (w, h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ backproj_grid = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'omniworldgame':+ # Load z-depth (16-bit PNG with special encoding)+ depth_map_np, valid_mask = load_omniworldgame_depth(data_pair['depth'])++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Load intrinsics from camera JSON file (conditionally cache to avoid OOM)+ cam_file = data_pair['cam_file']+ frame_idx_in_split = data_pair['frame_idx_in_split']++ if self._use_cam_cache:+ if not hasattr(self, 'omniworldgame_cam_cache'):+ self.omniworldgame_cam_cache = {}+ if cam_file not in self.omniworldgame_cam_cache:+ import json+ with open(cam_file, 'r', encoding='utf-8') as f:+ self.omniworldgame_cam_cache[cam_file] = json.load(f)+ cam_data = self.omniworldgame_cam_cache[cam_file]+ else:+ import json+ with open(cam_file, 'r', encoding='utf-8') as f:+ cam_data = json.load(f)++ # Extract intrinsics for this specific frame+ # OmniWorld-Game has per-frame focal length (list) but constant cx/cy (scalars)+ focal = cam_data['focals'][frame_idx_in_split]+ cx = cam_data['cx'] # Constant for the split+ cy = cam_data['cy'] # Constant for the split+ fx = fy = focal # Same focal length for x and y++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Get backprojection grid - compute on-the-fly for variable intrinsics datasets+ if self._use_backproj_cache:+ cache_key = (w, h, round(fx, 6), round(fy, 6), round(cx, 6), round(cy, 6))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ backproj_grid = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'irs':+ # Load z-depth (NPY in meters, preprocessed from disparity EXR)+ depth_map_np = np.load(data_pair['depth']).astype(np.float32)++ # Filter invalid depth values to prevent NaN propagation+ depth_map_np[~np.isfinite(depth_map_np)] = 0.++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Load intrinsics from .npz file (conditionally cache to avoid OOM)+ cam_file = data_pair['cam_file']+ if self._use_cam_cache:+ if not hasattr(self, 'irs_cam_cache'):+ self.irs_cam_cache = {}+ if cam_file not in self.irs_cam_cache:+ self.irs_cam_cache[cam_file] = np.load(cam_file)+ cam_data = self.irs_cam_cache[cam_file]+ else:+ cam_data = np.load(cam_file)+ K = cam_data['intrinsics'] # [3, 3]+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Get backprojection grid - compute on-the-fly for variable intrinsics datasets+ if self._use_backproj_cache:+ cache_key = (w, h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ backproj_grid = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'dynamic_replica':+ # Load z-depth (NPY in meters, float32)+ depth_map_np = np.load(data_pair['depth']).astype(np.float32)++ # Filter invalid depth values to prevent NaN propagation+ depth_map_np[~np.isfinite(depth_map_np)] = 0.++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Load intrinsics from .npz file (can cache since intrinsics are fixed at fx=fy=700, cx=640, cy=360)+ cam_file = data_pair['cam_file']+ if self._use_cam_cache:+ if not hasattr(self, 'dynamic_replica_cam_cache'):+ self.dynamic_replica_cam_cache = {}+ if cam_file not in self.dynamic_replica_cam_cache:+ self.dynamic_replica_cam_cache[cam_file] = np.load(cam_file)+ cam_data = self.dynamic_replica_cam_cache[cam_file]+ else:+ cam_data = np.load(cam_file)+ K = cam_data['intrinsics'] # [3, 3]+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Get backprojection grid - can cache since intrinsics are fixed+ if self._use_backproj_cache:+ cache_key = (w, h, round(fx, 2), round(fy, 2), round(cx, 2), round(cy, 2))+ if cache_key not in self._backproj_cache:+ self._backproj_cache[cache_key] = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)+ backproj_grid = self._backproj_cache[cache_key]+ else:+ backproj_grid = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ elif self.dataset_name == 'eden':+ # Load z-depth from NPY file (preprocessed, meters)+ depth_map_np = np.load(data_pair['depth']).astype(np.float32)++ # Filter invalid depth values to prevent NaN propagation+ depth_map_np[~np.isfinite(depth_map_np)] = 0.++ # Convert to tensor early for GPU operations+ depth_tensor = torch.from_numpy(depth_map_np).unsqueeze(0).unsqueeze(0).to(self.conversion_device) # (1, 1, H, W)++ # Load intrinsics from NPZ file+ cam_file = data_pair['cam_file']+ cam_data = np.load(cam_file)+ K = cam_data['intrinsics'] # [3, 3]+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]++ # Resize logic+ orig_w, orig_h = img_pil.size++ if self.finetune_highres_mode:+ # High-res finetuning mode: adaptive resize based on native resolution+ do_resize, scale, new_h, new_w = self._compute_highres_resize_params(orig_h, orig_w)+ if do_resize:+ # Resize image (bilinear)+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = orig_h, orig_w++ elif self.resize_height is not None or self.resize_width is not None:+ # Standard resize mode (for backward compatibility)+ scale_h = self.resize_height / orig_h if self.resize_height else 0+ scale_w = self.resize_width / orig_w if self.resize_width else 0+ scale = max(scale_h, scale_w) if (scale_h and scale_w) else (scale_h or scale_w)+ new_h = int(orig_h * scale)+ new_w = int(orig_w * scale)++ # OPTIMIZATION: Skip resize if dimensions already match+ if new_h != orig_h or new_w != orig_w:+ # Resize image (bilinear) - convert to tensor for faster resize+ img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # (1, 3, H, W)+ img_tensor = torch.nn.functional.interpolate(img_tensor, size=(new_h, new_w), mode='bilinear', align_corners=False)+ img_pil = TF.to_pil_image(img_tensor.squeeze(0))++ # Resize depth (nearest)+ depth_tensor = torch.nn.functional.interpolate(depth_tensor, size=(new_h, new_w), mode='nearest')++ # Scale intrinsics (uniform scale for aspect ratio preservation)+ fx = fx * scale+ fy = fy * scale+ cx = cx * scale+ cy = cy * scale++ h, w = new_h, new_w+ else:+ h, w = depth_tensor.shape[2], depth_tensor.shape[3]++ # Eden: Don't cache backprojection grids (per-frame intrinsics)+ backproj_grid = compute_backprojection_grid(w, h, fx, fy, cx, cy, device=self.conversion_device)++ # Convert to 2D tensor for pointcloud conversion+ depth_map = depth_tensor.squeeze(0).squeeze(0) # (H, W)++ # Convert z-depth to 3D points (GPU accelerated)+ pc_tensor = points_in_camera_coords_zdepth(depth_map, backproj_grid) # (H, W, 3)++ # Convert back to numpy for rest of pipeline+ pc_np = pc_tensor.cpu().numpy()++ t_depth_convert = time.perf_counter() if self.debug_timing else None++ # 3. Apply Augmentations++ # A. Color Jitter (Only applies to the Image)+ if self.split in ['train', 'all']:+ img_pil = self.color_jitter(img_pil)++ if self.more_img_aug:+ img_pil = self.appearance_aug(img_pil)++ # B. Random Horizontal Flip (Applies to BOTH)+ if self.split in ['train', 'all'] and random.random() < 0.5:+ img_pil = img_pil.transpose(Image.FLIP_LEFT_RIGHT)+ pc_np = np.flip(pc_np, axis=1).copy()+ pc_np[..., 0] = -pc_np[..., 0]++ # C. Filter invalid points+ pc_np[~np.isfinite(pc_np)] = 0.++ if self.clamp_max_depth is not None:+ pc_np[:, :, 2] = np.minimum(pc_np[:, :, 2], self.clamp_max_depth)++ if not self.handle_sky:+ depth_mask = pc_np[..., 2] > self.max_depth+ pc_np[depth_mask] = 0.++ # D. Sanity check dimensions+ width, height = img_pil.size+ if pc_np.shape[:2] != (height, width):+ raise ValueError(+ f"Dimension mismatch at index {idx}: "+ f"Image size ({height}, {width}) does not match PC shape {pc_np.shape[:2]}"+ )++ # E. Apply Paired Crop+ if self.cropper is not None:+ # Get dimensions before crop+ pre_crop_w, pre_crop_h = img_pil.size++ # Call cropper - may return 2 or 3 values depending on cropper type+ crop_result = self.cropper(img_pil, pc_np)++ if len(crop_result) == 3:+ # New crop classes that return exact offsets (for high-res finetuning mode)+ img_pil, pc_np, (crop_offset_x, crop_offset_y) = crop_result+ # Adjust intrinsics using exact offsets+ cx = cx - crop_offset_x+ cy = cy - crop_offset_y+ else:+ # Legacy crop classes - use center approximation+ img_pil, pc_np = crop_result++ # Compute crop offset (for center crop) or estimate (for random crop)+ # Note: Random crop offset is not deterministic, but we compute center offset as approximation+ if hasattr(self.cropper, 'size'):+ target_h, target_w = self.cropper.size+ # For CenterCropPaired, use exact center offset+ # For RandomCropPaired, this is an approximation+ crop_offset_x = (pre_crop_w - target_w) // 2+ crop_offset_y = (pre_crop_h - target_h) // 2+ # Adjust intrinsics for crop+ cx = cx - crop_offset_x+ cy = cy - crop_offset_y++ t_file_read = time.perf_counter() if self.debug_timing else None++ # 4. Convert to Tensor+ image_tensor = self.image_to_tensor(img_pil)++ # Add random Gaussian noise+ aug_prob = 0.2 if self.stronger_img_aug else 0.1+ if self.more_img_aug and self.split == 'train' and random.random() < aug_prob:+ noise = torch.randn_like(image_tensor) * 0.02+ image_tensor = image_tensor + noise+ image_tensor = torch.clamp(image_tensor, 0.0, 1.0)++ # Filter invalid RGB+ image_tensor[~torch.isfinite(image_tensor)] = 0.++ # Convert pointcloud to tensor+ pointcloud_tensor = torch.from_numpy(pc_np).permute(2, 0, 1).float()+ pointcloud_unnormalized = pointcloud_tensor.clone()++ valid_mask = pointcloud_tensor[2, :, :] > 1e-6++ if self.handle_sky:+ sky_mask = pointcloud_unnormalized[2, :, :] > self.max_depth+ pointcloud_tensor[2, sky_mask] = 0.+ valid_mask = pointcloud_tensor[2, :, :] > 1e-6++ has_valid_points = valid_mask.any()++ # 5. Normalization++ # Center shift+ if self.center_shift:+ if has_valid_points:+ center = pointcloud_tensor[:, valid_mask].mean(dim=1).view(3, 1, 1)+ else:+ center = torch.zeros((3, 1, 1), device=pointcloud_tensor.device)++ if self.center_shift_z_only:+ center[:2, :, :] = 0.++ pointcloud_tensor = pointcloud_tensor - center++ # Scale normalize+ if self.no_scale_factor:+ scale_factor = torch.tensor(1.0)+ else:+ scale_factor = compute_distance_statistic(+ pointcloud_tensor,+ valid_mask=valid_mask if self.compute_scale_factor_only_valid else None,+ use_mean=self.normalize_by_mean,+ use_std=self.compute_scale_factor_use_std,+ use_percentile=self.compute_scale_factor_use_percentile+ )++ # Apply scale factor augmentation (training only)+ if self.scale_factor_augment and self.split in ['train', 'all']:+ aug_factor = random.uniform(*self.scale_factor_augment_range)+ scale_factor = scale_factor * aug_factor++ if scale_factor < 1e-6:+ pointcloud_tensor.zero_()+ else:+ pointcloud_tensor = pointcloud_tensor / scale_factor++ # Remove outliers after normalization (for flow matching stability)+ if self.remove_outliers:+ # Find points where any coordinate exceeds the threshold+ outlier_mask = (torch.abs(pointcloud_tensor[0, :, :]) > self.outlier_threshold) | \+ (torch.abs(pointcloud_tensor[1, :, :]) > self.outlier_threshold) | \+ (torch.abs(pointcloud_tensor[2, :, :]) > self.outlier_threshold)+ # Zero out outlier points+ pointcloud_tensor[:, outlier_mask] = 0.0+ # Update valid mask to exclude outliers+ valid_mask = valid_mask & ~outlier_mask++ # Handle sky+ if self.handle_sky:+ FAR_PLANE_VAL = self.sky_far_plane_value++ if self.use_sky_dome:+ if sky_mask.any():+ raw_sky_vectors = pointcloud_unnormalized[:, sky_mask]+ raw_norms = torch.norm(raw_sky_vectors, dim=0, keepdim=True)+ sky_directions = raw_sky_vectors / (raw_norms + 1e-8)+ pointcloud_tensor[:, sky_mask] = sky_directions * FAR_PLANE_VAL+ else:+ pointcloud_tensor[0, sky_mask] = 0.0+ pointcloud_tensor[1, sky_mask] = 0.0+ pointcloud_tensor[2, sky_mask] = FAR_PLANE_VAL++ valid_mask = valid_mask | sky_mask++ # 6. Return the dictionary+ out_dict = {+ 'image': image_tensor,+ 'pointcloud': pointcloud_tensor,+ 'pointcloud_unnormalized': pointcloud_unnormalized, # For visualization+ 'scale_factor': scale_factor,+ 'dataset_name': self.dataset_name, # NEW: for multi-dataset training+ 'intrinsics': (fx, fy, cx, cy), # NEW: for variable resolution training+ }++ if self.center_shift:+ out_dict['center_shift'] = center+ out_dict['valid_mask'] = valid_mask++ if self.handle_sky:+ out_dict['sky_mask'] = sky_mask+ else:+ # Add dummy sky_mask for consistency in mixed dataset training+ # This ensures all samples have the same dict keys for PyTorch collation+ out_dict['sky_mask'] = torch.zeros_like(pointcloud_tensor[0, :, :], dtype=torch.bool)++ if self.split in ['val', 'test']:+ out_dict['pointcloud_unnormalized'] = pointcloud_unnormalized++ # Timing logging+ if self.debug_timing:+ t_end = time.perf_counter()+ self._timing_accum['file_read'] += t_depth_convert - t_start+ self._timing_accum['depth_convert'] += t_file_read - t_depth_convert+ self._timing_accum['augment'] += t_end - t_file_read+ self._timing_accum['total'] += t_end - t_start+ self._timing_count += 1++ if self._timing_count % 100 == 0:+ n = self._timing_count+ print(f"[File Timing] samples={n}, "+ f"file_read={self._timing_accum['file_read']/n*1000:.2f}ms, "+ f"depth_convert={self._timing_accum['depth_convert']/n*1000:.2f}ms, "+ f"augment={self._timing_accum['augment']/n*1000:.2f}ms, "+ f"total={self._timing_accum['total']/n*1000:.2f}ms")++ return out_dictdiff --git a/dataloader/mixed_dataset.py b/dataloader/mixed_dataset.pynew file mode 100644index 0000000..b695f2a--- /dev/null+++ b/dataloader/mixed_dataset.py@@ -0,0 +1,329 @@+# coding=utf-8++"""+MixedImageDepthIntrinsicsDataset - Multi-dataset wrapper for mixed training++Supports combining multiple datasets (SceneNet, TartanAir, etc.) with:+- Per-dataset configurations (max_depth, sky handling, etc.)+- Weighted sampling to control dataset mixing ratios+- YAML-based configuration files+- Unified preprocessing (resize, crop) while preserving dataset-specific features++Usage:+ from dataloader.mixed_dataset import MixedImageDepthIntrinsicsDataset++ dataset = MixedImageDepthIntrinsicsDataset(+ config_path='dataloader/configs/pretrain_scenenet_tartanair.yaml',+ split='train',+ crop_size=256,+ # ... other shared args+ )+"""++import os+import yaml+from torch.utils.data import ConcatDataset, WeightedRandomSampler+from dataloader.img_depth_intrinsics import ImageDepthIntrinsicsDataset+++def load_dataset_config(config_path):+ """+ Load dataset configuration from YAML file.++ Args:+ config_path (str): Path to YAML config file++ Returns:+ dict: Configuration dictionary+ """+ if not os.path.exists(config_path):+ raise FileNotFoundError(f"Dataset config file not found: {config_path}")++ with open(config_path, 'r') as f:+ config = yaml.safe_load(f)++ if 'datasets' not in config or not config['datasets']:+ raise ValueError(f"Config file must contain 'datasets' list: {config_path}")++ return config+++class MixedImageDepthIntrinsicsDataset(ConcatDataset):+ """+ Multi-dataset wrapper that combines multiple ImageDepthIntrinsicsDataset instances.++ Features:+ - Loads config from YAML file+ - Creates separate dataset instance for each dataset with its own config+ - Supports weighted sampling via WeightedRandomSampler+ - Preserves per-dataset settings (max_depth, sky handling, etc.)++ The config file should have structure:+ datasets:+ - name: scenenet+ data_path: path/to/scenenet+ max_depth: 10.0+ weight: 0.5+ handle_sky: false+ ...+ - name: tartanair+ data_path: path/to/tartanair+ max_depth: 100.0+ weight: 0.5+ handle_sky: true+ ...+ img_size: 256+ resize_height: 256+ """++ def __init__(+ self,+ config_path,+ split='train',+ crop_size=None,+ # Shared args (will be overridden by per-dataset config if specified)+ center_shift=False,+ normalize_by_mean=False,+ num_overfit_samples=None,+ num_dataset_duplicates=None,+ subsample_scenes=None,+ center_shift_z_only=False,+ more_img_aug=False,+ stronger_img_aug=False,+ debug_timing=False,+ use_gpu_conversion=False,+ # Test scenes handling+ num_test_scenes=2,+ test_scenes_file=None,+ samples_per_scene=None,+ # Weight overrides+ weight_overrides=None,+ ):+ """+ Args:+ config_path (str): Path to YAML config file+ split (str): 'train', 'test', 'val', or 'all'+ crop_size (int): Final crop size (overridden by config's img_size if present)+ weight_overrides (list or None): List of weights to override config weights (e.g., [0.7, 0.3])+ ... (other args are shared defaults, can be overridden per-dataset in config)+ """+ # Load config+ self.config = load_dataset_config(config_path)+ self.config_path = config_path++ # Validate and apply weight overrides if provided+ if weight_overrides is not None:+ if len(weight_overrides) != len(self.config['datasets']):+ raise ValueError(+ f"Number of weight overrides ({len(weight_overrides)}) must match "+ f"number of datasets ({len(self.config['datasets'])}) in config"+ )++ # Normalize weights to sum to 1.0+ total_weight = sum(weight_overrides)+ if abs(total_weight - 1.0) > 1e-6:+ print(f"[MixedDataset] Normalizing weights from sum={total_weight:.4f} to 1.0")+ weight_overrides = [w / total_weight for w in weight_overrides]++ # Override config weights+ for i, ds_config in enumerate(self.config['datasets']):+ original_weight = ds_config.get('weight', 1.0)+ ds_config['weight'] = weight_overrides[i]+ print(f"[MixedDataset] Overriding {ds_config['name']} weight: {original_weight} -> {weight_overrides[i]:.3f}")++ self.weight_overrides = weight_overrides++ # Shared settings from the config; the YAML's img_size wins over the passed crop_size.+ shared_img_size = self.config.get('img_size', crop_size)+ if shared_img_size is not None:+ crop_size = shared_img_size+ shared_resize_height = self.config.get('resize_height', None)+ shared_resize_width = self.config.get('resize_width', None)++ # High-res finetuning mode settings (from config)+ finetune_highres_mode = self.config.get('finetune_highres_mode', False)+ finetune_target_height = self.config.get('finetune_target_height', 512)+ finetune_target_width = self.config.get('finetune_target_width', None) # None = height-only mode+ finetune_target_crop = self.config.get('finetune_target_crop', 512)++ if finetune_highres_mode:+ print(f"[MixedDataset] High-res finetuning mode enabled: target_height={finetune_target_height}, target_width={finetune_target_width}, crop={finetune_target_crop}")++ # Create individual datasets+ datasets = []+ dataset_weights = []+ dataset_info = []++ for ds_config in self.config['datasets']:+ dataset_name = ds_config['name']+ data_path = ds_config['data_path']+ weight = ds_config.get('weight', 1.0)++ # Per-dataset overrides (with shared defaults)+ max_depth = ds_config.get('max_depth', 10.0)+ handle_sky = ds_config.get('handle_sky', False)+ use_sky_dome = ds_config.get('use_sky_dome', False)+ sky_loss_weight = ds_config.get('sky_loss_weight', 0.0)+ sky_far_plane_value = ds_config.get('sky_far_plane_value', 3.0)+ compute_scale_factor_only_valid = ds_config.get('compute_scale_factor_only_valid', False)+ compute_scale_factor_use_std = ds_config.get('compute_scale_factor_use_std', False)+ compute_scale_factor_use_percentile = ds_config.get('compute_scale_factor_use_percentile', False)+ clamp_max_depth = ds_config.get('clamp_max_depth', None)+ remove_outliers = ds_config.get('remove_outliers', False)+ outlier_threshold = ds_config.get('outlier_threshold', 5.0)+ scale_factor_augment = ds_config.get('scale_factor_augment', False)+ scale_factor_augment_range = ds_config.get('scale_factor_augment_range', (0.8, 1.2))++ # Per-dataset minimum image size (for filtering undersized samples)+ min_height = ds_config.get('min_height', None)+ min_width = ds_config.get('min_width', None)++ # Per-dataset resize height (defaults to shared setting)+ dataset_resize_height = ds_config.get('resize_height', shared_resize_height)++ # Per-dataset resize width (defaults to shared setting)+ dataset_resize_width = ds_config.get('resize_width', shared_resize_width)++ # Per-dataset num_test_scenes (defaults to shared setting)+ dataset_num_test_scenes = ds_config.get('num_test_scenes', num_test_scenes)++ # No dataset ships a curated holdout list. Pass through whatever the caller+ # supplied (None by default), in which case each loader falls back to its+ # `num_test_scenes` auto-split. A path given here is resolved relative to+ # dataloader/ by ImageDepthIntrinsicsDataset. Note that a list whose names do+ # not match any scene still counts as a "manual" split and so disables the+ # auto-split entirely, so only pass one that matches the dataset.+ dataset_test_scenes_file = test_scenes_file++ # Create dataset instance+ dataset = ImageDepthIntrinsicsDataset(+ root_dir=data_path,+ dataset_name=dataset_name,+ split=split,+ num_test_scenes=dataset_num_test_scenes,+ test_scenes_file=dataset_test_scenes_file,+ samples_per_scene=samples_per_scene,+ crop_size=crop_size,+ resize_height=dataset_resize_height,+ resize_width=dataset_resize_width,+ center_shift=center_shift,+ normalize_by_mean=normalize_by_mean,+ num_overfit_samples=num_overfit_samples,+ num_dataset_duplicates=num_dataset_duplicates,+ max_depth=max_depth,+ subsample_scenes=subsample_scenes,+ center_shift_z_only=center_shift_z_only,+ more_img_aug=more_img_aug,+ stronger_img_aug=stronger_img_aug,+ compute_scale_factor_only_valid=compute_scale_factor_only_valid,+ compute_scale_factor_use_std=compute_scale_factor_use_std,+ compute_scale_factor_use_percentile=compute_scale_factor_use_percentile,+ clamp_max_depth=clamp_max_depth,+ handle_sky=handle_sky,+ use_sky_dome=use_sky_dome,+ sky_far_plane_value=sky_far_plane_value,+ debug_timing=debug_timing,+ use_gpu_conversion=use_gpu_conversion,+ remove_outliers=remove_outliers,+ outlier_threshold=outlier_threshold,+ min_height=min_height,+ min_width=min_width,+ scale_factor_augment=scale_factor_augment,+ scale_factor_augment_range=scale_factor_augment_range,+ # High-res finetuning mode+ finetune_highres_mode=finetune_highres_mode,+ finetune_target_height=finetune_target_height,+ finetune_target_width=finetune_target_width,+ finetune_target_crop=finetune_target_crop,+ )++ datasets.append(dataset)+ dataset_weights.append(weight)+ dataset_info.append({+ 'name': dataset_name,+ 'size': len(dataset),+ 'weight': weight,+ 'max_depth': max_depth,+ })++ print(f"[MixedDataset] Loaded {dataset_name}: {len(dataset)} samples, weight={weight}, max_depth={max_depth}")++ # Initialize ConcatDataset+ super().__init__(datasets)++ # Store metadata+ self.datasets_info = dataset_info+ self.dataset_weights = dataset_weights+ self.num_datasets = len(datasets)++ # Print summary+ total_samples = len(self)++ # Check for empty datasets+ if total_samples == 0:+ raise ValueError(+ f"Total samples is 0. Check dataset paths and configurations.\n"+ f"Config: {config_path}\n"+ f"Dataset info: {dataset_info}"+ )++ print(f"\n[MixedDataset] Total samples: {total_samples:,}")+ print(f"[MixedDataset] Config: {config_path}")+ print(f"[MixedDataset] Split: {split}")+ print(f"[MixedDataset] Crop size: {crop_size}")+ print(f"[MixedDataset] Resize height: {shared_resize_height}")+ print(f"\nDataset composition:")+ for info in dataset_info:+ size_percentage = (info['size'] / total_samples) * 100+ sampling_percentage = info['weight'] * 100+ print(f" - {info['name']}: {info['size']:,} samples ({size_percentage:.1f}% of total)")+ print(f" → Sampling weight: {info['weight']:.3f} ({sampling_percentage:.1f}% of training samples per epoch)")++ def create_weighted_sampler(self, num_samples=None):+ """+ Create a WeightedRandomSampler for this mixed dataset.++ This sampler ensures that samples are drawn according to the specified+ dataset weights, rather than proportional to dataset sizes.++ Args:+ num_samples (int, optional): Total number of samples to draw per epoch.+ If None, defaults to the total dataset size.++ Returns:+ torch.utils.data.WeightedRandomSampler+ """+ # Compute per-sample weights based on dataset membership+ sample_weights = []++ for dataset, weight in zip(self.datasets, self.dataset_weights):+ dataset_size = len(dataset)+ if dataset_size == 0:+ print(f"[MixedDataset] WARNING: skipping empty dataset (weight={weight}) in weighted sampler")+ continue+ # Each sample in this dataset gets the same weight (normalized by dataset size)+ # This ensures the dataset is sampled proportional to its weight, not its size+ per_sample_weight = weight / dataset_size+ sample_weights.extend([per_sample_weight] * dataset_size)++ # Normalize weights to sum to 1+ total_weight = sum(sample_weights)+ sample_weights = [w / total_weight for w in sample_weights]++ if num_samples is None:+ num_samples = len(self)++ sampler = WeightedRandomSampler(+ weights=sample_weights,+ num_samples=num_samples,+ replacement=True,+ )++ print(f"[MixedDataset] Created WeightedRandomSampler with {num_samples} samples")++ return sampler++ def __repr__(self):+ info_strs = [f"{d['name']}({d['size']} samples, weight={d['weight']})"+ for d in self.datasets_info]+ return f"MixedImageDepthIntrinsicsDataset({', '.join(info_strs)})"diff --git a/dataloader/point_transforms.py b/dataloader/point_transforms.pynew file mode 100644index 0000000..0c43e13--- /dev/null+++ b/dataloader/point_transforms.py@@ -0,0 +1,188 @@+# coding=utf-8++"""Paired image/point-map transforms and the point-map scale statistic.++Used by the training dataloader, ``dataloader/img_depth_intrinsics.py``.+"""++import random++import torch+++# --- Custom Paired Transformation (Augmentation) ---++class RandomCropPaired:+ """+ Applies the exact same random crop to both the RGB image and the Point Cloud array.+ Used for the training set (augmentation).+ """+ def __init__(self, size):+ if isinstance(size, int):+ self.size = (size, size)+ else:+ self.size = size++ def __call__(self, img_pil, pc_np):+ width, height = img_pil.size+ target_h, target_w = self.size++ if width < target_w or height < target_h:+ print(f"Warning: Requested crop size {self.size} is larger than image size ({height}, {width}). No cropping applied.")+ return img_pil, pc_np++ i = random.randint(0, height - target_h)+ j = random.randint(0, width - target_w)++ cropped_img = img_pil.crop((j, i, j + target_w, i + target_h))+ cropped_pc = pc_np[i:i + target_h, j:j + target_w, :]++ return cropped_img, cropped_pc++# --- Paired Transformation (Evaluation) ---++class CenterCropPaired:+ """+ Applies a deterministic center crop to both the RGB image and the Point Cloud array.+ Used for the test/validation set.+ """+ def __init__(self, size):+ if isinstance(size, int):+ self.size = (size, size)+ else:+ self.size = size++ def __call__(self, img_pil, pc_np):+ width, height = img_pil.size+ target_h, target_w = self.size++ if width < target_w or height < target_h:+ print(f"Warning: Requested crop size {self.size} is larger than image size ({height}, {width}). No cropping applied.")+ return img_pil, pc_np++ i = (height - target_h) // 2+ j = (width - target_w) // 2++ cropped_img = img_pil.crop((j, i, j + target_w, i + target_h))+ cropped_pc = pc_np[i:i + target_h, j:j + target_w, :]++ return cropped_img, cropped_pc+++class RandomCropPairedWithOffset:+ """+ Applies the exact same random crop to both the RGB image and the Point Cloud array.+ Returns the crop offset (x, y) for accurate intrinsics adjustment.+ Used for high-res finetuning mode where we need to adjust cx, cy based on crop position.+ """+ def __init__(self, size):+ if isinstance(size, int):+ self.size = (size, size)+ else:+ self.size = size++ def __call__(self, img_pil, pc_np):+ width, height = img_pil.size+ target_h, target_w = self.size++ if width < target_w or height < target_h:+ print(f"Warning: Requested crop size {self.size} is larger than image size ({height}, {width}). No cropping applied.")+ return img_pil, pc_np, (0, 0)++ i = random.randint(0, height - target_h) # y offset+ j = random.randint(0, width - target_w) # x offset++ cropped_img = img_pil.crop((j, i, j + target_w, i + target_h))+ cropped_pc = pc_np[i:i + target_h, j:j + target_w, :]++ return cropped_img, cropped_pc, (j, i) # Return (x_offset, y_offset)+++class CenterCropPairedWithOffset:+ """+ Applies a deterministic center crop to both the RGB image and the Point Cloud array.+ Returns the crop offset (x, y) for accurate intrinsics adjustment.+ Used for high-res finetuning mode validation/test sets.+ """+ def __init__(self, size):+ if isinstance(size, int):+ self.size = (size, size)+ else:+ self.size = size++ def __call__(self, img_pil, pc_np):+ width, height = img_pil.size+ target_h, target_w = self.size++ if width < target_w or height < target_h:+ print(f"Warning: Requested crop size {self.size} is larger than image size ({height}, {width}). No cropping applied.")+ return img_pil, pc_np, (0, 0)++ i = (height - target_h) // 2 # y offset+ j = (width - target_w) // 2 # x offset++ cropped_img = img_pil.crop((j, i, j + target_w, i + target_h))+ cropped_pc = pc_np[i:i + target_h, j:j + target_w, :]++ return cropped_img, cropped_pc, (j, i) # Return (x_offset, y_offset)+++def compute_distance_statistic(+ point_cloud: torch.Tensor,+ valid_mask: torch.Tensor = None,+ use_mean: bool = True,+ use_std: bool = False,+ use_percentile: bool = False,+) -> torch.Tensor:+ """+ Computes the median (or mean) Euclidean distance of valid points.++ Args:+ point_cloud: Tensor of shape (3, H, W).+ valid_mask: Optional boolean Tensor of shape (1, H, W) or (H, W).+ True indicates a valid point to include.+ use_mean: If True, computes mean instead of median.+ use_percentile: If True, computes 99th percentile instead of mean/median.++ Returns:+ A scalar tensor.+ """+ # 1. Flatten the point cloud -> (3, N)+ # points_flat shape: [3, H*W]+ points_flat = point_cloud.reshape(3, -1)++ # 2. Compute distances for all points -> (N,)+ distances = torch.linalg.norm(points_flat, ord=2, dim=0)++ # 3. Apply the mask if provided+ if valid_mask is not None:+ # Flatten mask to match distances shape: (N,)+ mask_flat = valid_mask.reshape(-1)++ # Filter distances using boolean indexing+ distances = distances[mask_flat]++ # 4. Handle Edge Case: Empty mask (no valid points)+ if distances.numel() == 0:+ return torch.tensor(0.0, device=point_cloud.device)++ # 5. Compute Statistic+ if use_percentile:+ scale_factor = torch.quantile(distances, 0.98)+ elif use_mean:+ scale_factor = torch.mean(distances)+ else:+ scale_factor = torch.median(distances)++ if use_std:+ # FIX: Check if we have enough points to compute std+ if distances.numel() > 1:+ std = torch.std(distances)+ else:+ # If N=1, variance/std is 0+ std = torch.tensor(0.0, device=point_cloud.device)++ scale_factor = scale_factor + 2 * std++ return scale_factor+diff --git a/denoiser.py b/denoiser.pynew file mode 100644index 0000000..3319a7d--- /dev/null+++ b/denoiser.py@@ -0,0 +1,224 @@+# coding=utf-8++# Derived from JiT (https://github.com/LTH14/JiT), MIT License,+# Copyright (c) 2025 Tianhong Li. See THIRD_PARTY_NOTICES.+import torch+import torch.nn as nn+from model import PointDiT_models+++class Denoiser(nn.Module):+ def __init__(+ self,+ args+ ):+ super().__init__()+ self.net = PointDiT_models[args.model](+ input_size=args.img_size,+ in_channels=3,+ attn_drop=args.attn_dropout,+ proj_drop=args.proj_dropout,+ attention_type=args.attention_type,+ feature_embedding_type=args.feature_embedding_type,+ dinov3_use_intermediate_layers=args.dinov3_use_intermediate_layers,+ dinov3_num_intermediate_layers=args.dinov3_num_intermediate_layers,+ finetune_feature_embedding=args.feature_embedding_lr_scale > 0,+ )+ self.P_mean = args.P_mean+ self.P_std = args.P_std+ self.t_eps = args.t_eps+ self.noise_scale = args.noise_scale+++ # ema+ self.ema_decay1 = args.ema_decay1+ self.ema_decay2 = args.ema_decay2+ self.ema_params1 = None+ self.ema_params2 = None++ # generation hyper params+ self.steps = args.num_sampling_steps++ self.args = args++ def sample_t(self, n: int, device=None):++ z = torch.randn(n, device=device) * self.P_std + self.P_mean+ return torch.sigmoid(z)++ def forward(self, x, labels,+ return_model_input_output=False,+ force_zero_t=False,+ args=None,+ valid_mask=None,+ sky_mask=None,+ ):++ # Image-conditioned point map generation: the conditioning image is passed+ # through unchanged (the condition is never dropped during training).+ labels_dropped = labels # image in this task++ # logit-normal timestep sampling: t = sigmoid(P_mean + P_std * eps)+ t = self.sample_t(x.size(0), device=x.device).view(-1, *([1] * (x.ndim - 1))) # [B, 1, 1, 1]++ if force_zero_t:+ # Force 10% of samples to be exactly 0.0+ # (Useful if t=0 requires special handling in your model)+ if args.force_zero_t_ratio is not None:+ force_zero_t_ratio = args.force_zero_t_ratio+ else:+ force_zero_t_ratio = 0.1++ mask_zero = torch.rand(t.shape, device=t.device) < force_zero_t_ratio+ t[mask_zero] = 0.0++ e = torch.randn_like(x) * self.noise_scale++ if args.noise_fill_invalid:+ assert valid_mask is not None+ mask_expanded = valid_mask.unsqueeze(1).float()+ x_filled = x * mask_expanded + e * (1 - mask_expanded)+ z = t * x_filled + (1 - t) * e+ else:+ z = t * x + (1 - t) * e++ v = (x - z) / (1 - t).clamp_min(self.t_eps)++ x_pred = self.net(z, t.flatten(), labels_dropped)+ v_pred = (x_pred - z) / (1 - t).clamp_min(self.t_eps)++ # velocity (v-) loss+ loss = (v - v_pred) ** 2++ if self.args.exclude_invalid_gt:+ if args.center_shift_point:+ # use valid mask from dataloader+ assert valid_mask is not None++ if args.sky_loss_weight > 0.0:+ assert sky_mask is not None+ # Combine valid_mask and sky_mask+ non_sky_mask = valid_mask & (~sky_mask) # Valid non-sky regions+ sky_only_mask = sky_mask # Sky regions+ non_sky_mask_expanded = non_sky_mask.unsqueeze(1).repeat(1, 3, 1, 1) # [B, 3, H, W]+ sky_only_mask_expanded = sky_only_mask.unsqueeze(1).repeat(1, 3, 1, 1) # [B, 3, H, W]++ # 2. Robust Non-Sky Loss Calculation+ # Check if there are ANY non-sky pixels in the batch+ if non_sky_mask_expanded.any():+ non_sky_loss = loss[non_sky_mask_expanded].mean()+ else:+ # If looking straight at sky, object loss is 0+ non_sky_loss = torch.tensor(0.0, device=loss.device)++ # 3. Robust Sky Loss Calculation+ # Check if there are ANY sky pixels in the batch+ if sky_only_mask_expanded.any():+ sky_loss = loss[sky_only_mask_expanded].mean()+ else:+ # If indoors or looking down, sky loss is 0+ sky_loss = torch.tensor(0.0, device=loss.device)++ # 4. Final Weighted Sum+ # We maintain gradients for whichever part exists+ loss = non_sky_loss + args.sky_loss_weight * sky_loss++ else:+ valid_mask_expanded = valid_mask.unsqueeze(1).repeat(1, 3, 1, 1) # [B, 3, H, W]+ loss = loss[valid_mask_expanded].mean()+ else:+ valid_mask = (x[:, 2:] > 0).repeat(1, 3, 1, 1)+ loss = loss[valid_mask].mean()+ else:+ loss = loss.mean(dim=(1, 2, 3)).mean()++ if return_model_input_output:+ model_in_out = {+ 't': t,+ 'input': z,+ 'output': x_pred+ }+ return loss, model_in_out++ return loss+++ @torch.no_grad()+ def generate(self, labels, return_intermediate_steps=False):+ device = labels.device+ bsz = labels.size(0)+ # Use the condition image size rather than a fixed self.img_size.+ _, _, H, W = labels.shape+ # --generate_noise_scale 0.0 (the default) starts the ODE from zeros, which+ # makes inference deterministic.+ z = self.args.generate_noise_scale * torch.randn(bsz, 3, H, W, device=device)+ timesteps = torch.linspace(0.0, 1.0, self.steps+1, device=device)+ timesteps = timesteps.view(-1, *([1] * z.ndim)).expand(-1, bsz, -1, -1, -1)++ if return_intermediate_steps:+ intermediate_results = {}+ # hardcoded for 50 steps for now+ intermediate_steps = [0, 15, 22, 30, 38, 45]++ if self.steps == 50:+ pass+ elif self.steps == 100:+ intermediate_steps = [x * 2 for x in intermediate_steps]+ elif self.steps == 200:+ intermediate_steps = [x * 4 for x in intermediate_steps]+ elif self.steps == 500:+ intermediate_steps = [x * 10 for x in intermediate_steps]+ elif self.steps == 1000:+ intermediate_steps = [x * 20 for x in intermediate_steps]+ else:+ stride = self.steps // 6+ intermediate_steps = [i * stride for i in range(6)]+ if self.steps < 10:+ intermediate_steps = list(range(self.steps))++ # ode+ # Save initial noise as step -1 (before any denoising)+ if return_intermediate_steps:+ intermediate_results[-1] = z.clone() # Use -1 to distinguish from step 0 denoising++ # Cache the (frozen) image-encoder features once, instead of recomputing them+ # at every sampling step.+ h_patches = H // self.net.patch_size+ w_patches = W // self.net.patch_size+ cached_y_emb_cond = self.net.extract_y_embedding(labels, h_patches, w_patches)++ for i in range(self.steps - 1):+ t = timesteps[i]+ t_next = timesteps[i + 1]+ z = self._euler_step(z, t, t_next, labels, cached_y_emb_cond)++ if return_intermediate_steps and i in intermediate_steps:+ intermediate_results[i] = z++ # last step euler; guarded because self.steps == 0 leaves timesteps with a+ # single element, so timesteps[-2] would be out of range+ if self.steps > 0:+ z = self._euler_step(z, timesteps[-2], timesteps[-1], labels, cached_y_emb_cond)++ if return_intermediate_steps:+ return z, intermediate_results++ return z++ @torch.no_grad()+ def _forward_sample(self, z, t, labels, cached_y_emb_cond=None):+ x_cond = self.net(z, t.flatten(), labels, cached_y_emb=cached_y_emb_cond)+ return (x_cond - z) / (1.0 - t).clamp_min(self.args.sample_t_eps)++ @torch.no_grad()+ def _euler_step(self, z, t, t_next, labels, cached_y_emb_cond=None):+ v_pred = self._forward_sample(z, t, labels, cached_y_emb_cond)+ return z + (t_next - t) * v_pred++ @torch.no_grad()+ def update_ema(self):+ source_params = list(self.parameters())+ for targ, src in zip(self.ema_params1, source_params):+ targ.detach().mul_(self.ema_decay1).add_(src, alpha=1 - self.ema_decay1)+ for targ, src in zip(self.ema_params2, source_params):+ targ.detach().mul_(self.ema_decay2).add_(src, alpha=1 - self.ema_decay2)diff --git a/engine.py b/engine.pynew file mode 100644index 0000000..af7b3e9--- /dev/null+++ b/engine.py@@ -0,0 +1,1638 @@+# coding=utf-8++# Derived from JiT (https://github.com/LTH14/JiT), MIT License,+# Copyright (c) 2025 Tianhong Li. See THIRD_PARTY_NOTICES.+import math+import os+import builtins+import time++import torch+import numpy as np+from PIL import Image++from util import misc+from util import lr_sched+from util.paths import repo_path+import copy+import wandb++import torch.distributed as dist++from util.viz_depth import viz_depth_tensor+from util.log_tb import add_text_border+from util.viz_pointcloud import (depth_flying_points,+ save_generated_gt_point_cloud,+ save_single_point_cloud)+from loss import rel_point_loss+from metrics.compute_metrics import compute_metrics as compute_affine_metrics+++def combine_keep_masks(*masks):+ """AND together optional (H, W) bool keep-masks (True = keep). None = no constraint.++ Returns None if all inputs are None, otherwise the element-wise AND of the+ non-None masks. Used to merge the depth-edge keep-mask with the sky-removal+ keep-mask before saving point clouds.+ """+ result = None+ for m in masks:+ if m is None:+ continue+ result = m if result is None else (result & m)+ return result+++def train_one_epoch(model, model_without_ddp, data_loader, optimizer, device, epoch, log_writer=None, args=None, accelerator=None, global_step=0):+ model.train(True)+ metric_logger = misc.MetricLogger(delimiter=" ",+ print_func=print if accelerator is None else accelerator.print)+ metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))+ header = 'Epoch: [{}]'.format(epoch)+ print_freq = 100++ # GPU compute timing (when dataloader_debug_timing is enabled)+ if args.dataloader_debug_timing:+ gpu_timing = {'forward': 0.0, 'backward': 0.0, 'optimizer': 0.0, 'ema': 0.0}+ gpu_timing_count = 0++ optimizer.zero_grad()++ # Monotonic step counter, seeded from the resumed value so logging/checkpoint+ # intervals stay continuous across resumes (independent of dataset length).+ start_global_step = global_step++ if log_writer is not None:+ print('log_dir: {}'.format(log_writer.log_dir))++ for data_iter_step, sample in enumerate(metric_logger.log_every(data_loader, print_freq, header)):+ # per iteration (instead of per epoch) lr scheduler+ lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)++ # Start forward timing+ if args.dataloader_debug_timing:+ torch.cuda.synchronize()+ t_forward_start = time.perf_counter()++ # normalize image to [-1, 1]+ # NOTE: only need to divide by 255 for original JiT dataloader+ # otherwise already handled in the dataloader+ image = sample['image'] # [B, 3, H, W] in [0, 1]+ pointcloud = sample['pointcloud'] # [B, 3, H, W]++ # image to [-1, 1]+ image = image.to(device, non_blocking=True).to(torch.float32)+ image = image * 2.0 - 1.0++ pointcloud = pointcloud.to(device, non_blocking=True)++ # accelerate's prepared dataloader moves batches to the device for us, plain+ # torchrun/single-GPU runs do not -- move the masks explicitly so both work.+ valid_mask = sample.get('valid_mask', None)+ if valid_mask is not None:+ valid_mask = valid_mask.to(device, non_blocking=True)+ sky_mask = sample.get('sky_mask', None)+ if sky_mask is not None:+ sky_mask = sky_mask.to(device, non_blocking=True)++ with torch.amp.autocast('cuda', dtype=torch.bfloat16):+ loss, model_in_out = model(pointcloud, image, return_model_input_output=True,+ force_zero_t=args.force_zero_t,+ args=args,+ valid_mask=valid_mask,+ sky_mask=sky_mask,+ )++ denoise_loss_value = loss.item()++ # relative point loss+ if args.rel_point_loss_weight > 0:+ assert 'output' in model_in_out+ x_pred = model_in_out['output'] # [B, 3, H, W]++ rel_loss_val = rel_point_loss(x_pred, pointcloud) # [B, H, W]++ # exclude invalid points+ if args.exclude_invalid_gt:+ if args.center_shift_point:+ # use valid mask from dataloader+ assert 'valid_mask' in sample+ valid_mask = sample['valid_mask'].to(device, non_blocking=True)+ rel_loss_val = rel_loss_val[valid_mask].mean()+ else:+ valid_mask = pointcloud[:, 2:] > 0 # [B, 1, H, W]+ rel_loss_val = rel_loss_val[valid_mask.squeeze(1)].mean()+ else:+ rel_loss_val = rel_loss_val.mean()++ loss = loss + args.rel_point_loss_weight * rel_loss_val++ rel_point_loss_value = rel_loss_val.item()++ loss_value = loss.item()+ if not math.isfinite(loss_value):+ print("Loss is {}, skipping backward pass".format(loss_value))+ # Skip backward/optimizer but continue to maintain sync across nodes+ optimizer.zero_grad()+ model_without_ddp.update_ema()+ metric_logger.update(loss=0.0) # Log 0 to indicate skipped iteration+ continue++ # End forward timing, start backward timing+ if args.dataloader_debug_timing:+ torch.cuda.synchronize()+ t_forward_end = time.perf_counter()+ gpu_timing['forward'] += t_forward_end - t_forward_start++ optimizer.zero_grad()++ # Start backward timing+ if args.dataloader_debug_timing:+ torch.cuda.synchronize()+ t_backward_start = time.perf_counter()++ if accelerator is not None:+ # Use accelerate backward+ accelerator.backward(loss)++ if args.grad_clip:+ if accelerator.sync_gradients:+ accelerator.clip_grad_norm_(model.parameters(), max_norm=1.0)+ else:+ loss.backward()++ # End backward timing, start optimizer timing+ if args.dataloader_debug_timing:+ torch.cuda.synchronize()+ t_backward_end = time.perf_counter()+ gpu_timing['backward'] += t_backward_end - t_backward_start+ t_optimizer_start = time.perf_counter()++ optimizer.step()++ # End optimizer timing, start EMA timing+ if args.dataloader_debug_timing:+ torch.cuda.synchronize()+ t_optimizer_end = time.perf_counter()+ gpu_timing['optimizer'] += t_optimizer_end - t_optimizer_start+ t_ema_start = time.perf_counter()++ model_without_ddp.update_ema()++ # End EMA timing and log+ if args.dataloader_debug_timing:+ torch.cuda.synchronize()+ t_ema_end = time.perf_counter()+ gpu_timing['ema'] += t_ema_end - t_ema_start+ gpu_timing_count += 1++ if gpu_timing_count % 100 == 0:+ n = gpu_timing_count+ total_gpu = gpu_timing['forward'] + gpu_timing['backward'] + gpu_timing['optimizer'] + gpu_timing['ema']+ print(f"[GPU Timing] steps={n}, "+ f"forward={gpu_timing['forward']/n*1000:.1f}ms, "+ f"backward={gpu_timing['backward']/n*1000:.1f}ms, "+ f"optimizer={gpu_timing['optimizer']/n*1000:.1f}ms, "+ f"ema={gpu_timing['ema']/n*1000:.1f}ms, "+ f"total_gpu={total_gpu/n*1000:.1f}ms")++ metric_logger.update(loss=loss_value)+ lr = optimizer.param_groups[0]["lr"]+ metric_logger.update(lr=lr)++ # Debug early exit+ if args.debug_train_steps > 0 and data_iter_step + 1 >= args.debug_train_steps:+ print(f"[DEBUG] Exiting training loop early after {data_iter_step + 1} steps")+ break++ loss_value_reduce = misc.all_reduce_mean(loss_value)++ if accelerator is not None:+ is_main_process = accelerator.is_main_process+ else:+ is_main_process = misc.is_main_process()++ # Monotonic global step (continuous across resumes).+ global_step = start_global_step + data_iter_step++ # Save checkpoint at step intervals (sub-epoch checkpointing).+ # Must run on ALL ranks: the barrier is a collective and save_model+ # internally guards the disk write with is_main_process(). Gating this on+ # rank-0-only conditions (e.g. log_writer) deadlocks distributed training.+ if args.save_last_steps > 0 and global_step > 0 and global_step % args.save_last_steps == 0:+ if accelerator is not None:+ accelerator.wait_for_everyone()+ elif misc.is_dist_avail_and_initialized():+ torch.distributed.barrier()+ misc.save_model(+ args=args,+ model_without_ddp=model_without_ddp,+ optimizer=optimizer,+ epoch=epoch,+ epoch_name="last",+ global_step=global_step,+ resume_epoch=epoch+ )++ # log with tensorboard+ if log_writer is not None or (args.wandb and is_main_process):+ if global_step % args.log_freq == 0:+ if args.wandb:+ log_values = {+ 'train/loss': loss_value_reduce,+ 'train/lr': lr,+ }++ if args.rel_point_loss_weight > 0:+ log_values['train/denoise_loss'] = denoise_loss_value+ log_values['train/rel_point_loss'] = rel_point_loss_value++ wandb.log(log_values, step=global_step)+ else:+ log_writer.add_scalar('train_loss', loss_value_reduce, global_step)+ log_writer.add_scalar('lr', lr, global_step)++ # TODO: log training image and pointcloud+ # TODO: can use make_grid to show multiple samples++ if args.center_shift_point:+ # shift back the pointcloud for visualization+ assert 'center_shift' in sample+ center_shift = sample['center_shift'].to(device, non_blocking=True) # [B, 3, 1, 1]++ pointcloud = pointcloud + center_shift+ model_in_out['input'] = model_in_out['input'] + center_shift+ model_in_out['output'] = model_in_out['output'] + center_shift++ num_viz_samples = min(4, pointcloud.shape[0])+ for sample_idx in range(num_viz_samples):+ # TODO: filter invalid point+ if pointcloud[sample_idx, 2].max() > 0 and model_in_out['output'][sample_idx, 2].max() > 0:+ # log image and depth+ img_viz = image[sample_idx].detach().cpu() * 0.5 + 0.5 # [3, H, W] in 0-1+ depth_viz = viz_depth_tensor(pointcloud[sample_idx, 2].detach().cpu(), return_numpy=False, shifted_depth=False, colormap=args.depth_colormap) / 255. # [3, H, W] in 0-1+ # TODO: concat model prediction at different timesteps++ tmp_t = model_in_out['t'][sample_idx].squeeze(0).item()+ model_in = model_in_out['input'][sample_idx, 2].detach().cpu().float() # [H, W]+ model_out = model_in_out['output'][sample_idx, 2].detach().cpu().float() # [H, W]++ model_in_viz = viz_depth_tensor(model_in, return_numpy=False, shifted_depth=False, colormap=args.depth_colormap) / 255.+ model_out_viz = viz_depth_tensor(model_out, return_numpy=False, shifted_depth=False, colormap=args.depth_colormap) / 255.++ concat = torch.cat((img_viz, model_in_viz, model_out_viz, depth_viz), dim=-1)++ # viz point cloud error+ point_pred_error = torch.abs(model_in_out['output'][sample_idx] - pointcloud[sample_idx]).mean(0) # [H, W]+ error_normalized = (point_pred_error - point_pred_error.min()) / (point_pred_error.max() - point_pred_error.min() + 1e-8)+ # exclude invalid regions+ error_normalized[pointcloud[sample_idx, 2] <= 0] = 0.+ error_normalized = error_normalized[None, :, :].repeat(3, 1, 1) # [3, H, W]+ concat = torch.cat((concat, error_normalized.detach().cpu()), dim=-1)++ # viz valid_mask+ if 'valid_mask' in sample:+ valid_mask_viz = sample['valid_mask'][sample_idx].detach().cpu().float() # [H, W]+ valid_mask_viz = valid_mask_viz[None, :, :].repeat(3, 1, 1) # [3, H, W]+ concat = torch.cat((concat, valid_mask_viz), dim=-1)++ # add time step info+ concat = add_text_border(concat, f't = {tmp_t:.3f}')++ if global_step % (args.log_freq * args.log_img_stride) == 0:+ # log images less frequently to save space+ if args.wandb:+ wandb.log({+ f'train_viz/sample{sample_idx}': wandb.Image(concat.permute(1, 2, 0).numpy()),+ }, step=global_step)++ else:+ log_writer.add_image(f'train/sample{sample_idx}', concat, global_step)+++ if (args.local_rank == 0 and epoch == 0 and data_iter_step == 5+ and torch.cuda.is_available()):+ if accelerator is not None:+ if accelerator.is_main_process:+ os.system("nvidia-smi")+ else:+ os.system("nvidia-smi")++ # Return the monotonic step counter so the next epoch continues from here.+ return global_step + 1+++def evaluate_img2point(model_without_ddp, args, epoch, data_loader, log_writer=None, accelerator=None):++ model_without_ddp.eval()++ if accelerator is not None:+ print = accelerator.print+ world_size = accelerator.num_processes+ local_rank = accelerator.process_index+ else:+ world_size = misc.get_world_size()+ local_rank = misc.get_rank()+ print = builtins.print++ # metrics+ # affine metrics - track per dataset+ # Use defaultdict to automatically initialize metrics for each dataset+ from collections import defaultdict++ # Parse which datasets should compute SI boundary metrics+ boundary_datasets = set()+ if hasattr(args, 'eval_boundary_datasets') and args.eval_boundary_datasets:+ boundary_datasets = set(args.eval_boundary_datasets.split(','))++ per_dataset_metrics = defaultdict(lambda: {+ 'total_affine_rel_depth': 0.,+ 'total_affine_delta1_depth': 0.,+ 'total_affine_rel_point': 0.,+ 'total_affine_delta1_point': 0.,+ 'num_valid_samples': 0,+ 'total_si_boundary_f1': 0.,+ 'num_si_boundary_samples': 0,+ 'depth_range': {b: {'total_rel_depth': 0., 'total_delta1_depth': 0., 'total_rel_point': 0., 'total_delta1_point': 0., 'count': 0} for b in ['near', 'medium', 'far']},+ })++ # Per-sample metrics for detailed comparison (only if enabled)+ per_sample_metrics = [] if getattr(args, 'eval_save_per_sample_metrics', False) else None++ # Global metrics (aggregate across all datasets)+ total_affine_rel_depth = 0.+ total_affine_delta1_depth = 0.+ total_affine_rel_point = 0.+ total_affine_delta1_point = 0.+ total_si_boundary_f1 = 0.+ num_si_boundary_samples = 0++ # Depth-range stratified metrics (near/mid/far)+ depth_range_bins = ['near', 'medium', 'far']+ depth_range_global = {b: {'total_rel_depth': 0., 'total_delta1_depth': 0., 'total_rel_point': 0., 'total_delta1_point': 0., 'count': 0} for b in depth_range_bins}++ num_valid_samples = 0 # Track samples with enough valid points for metrics++ # Inference speed tracking (skip first 5 samples for warmup)+ total_inference_time = 0.0+ inference_sample_count = 0+ warmup_samples = 5++ if args.online_eval:+ # Check if using multiple datasets for visualization+ # We'll determine this by checking if MultiEvalDepthDataset is being used+ # This is indicated by having multiple dataset names in the loader+ is_multi_dataset_viz = hasattr(data_loader.dataset, 'datasets') and len(data_loader.dataset.datasets) > 1++ if is_multi_dataset_viz:+ # Multiple datasets: visualize 1 samples per dataset+ per_dataset_viz_counters = {}+ samples_per_dataset = 1+ else:+ # Single dataset: visualize 4 samples total+ num_val_samples = min(4, len(data_loader))+ eval_counter = 0+ log_eval_freq = len(data_loader) // num_val_samples++ if args.wandb:+ if accelerator is not None:+ if accelerator.is_main_process:+ wandb.define_metric("test_viz/*", step_metric="epoch")+ wandb.define_metric("test_metric/*", step_metric="epoch")+ else:+ if args.local_rank == 0:+ wandb.define_metric("test_viz/*", step_metric="epoch")+ wandb.define_metric("test_metric/*", step_metric="epoch")++ # 1. Initialize an empty dictionary before the loop+ val_logs = {'epoch': epoch}++ # Construct the folder name for saving generated results.+ if args.pretrained is not None and args.evaluate_gen and not args.eval_no_save_gen:+ # Name the output folder after (up to) the last three components of the checkpoint+ # path, so runs from different checkpoint directories do not collide.+ parts = [p for p in args.pretrained.split('/') if p]+ parts[-1] = os.path.splitext(parts[-1])[0]+ target_dir = '-'.join(parts[-3:])+ else:+ # No checkpoint to name the folder after: online eval during training, or a+ # standalone run over a randomly initialised model. Kept distinct from each other.+ target_dir = 'online' if args.online_eval else 'randinit'+ # Defaults to <repo>/generation rather than ./generation, so results land next+ # to the code even when the command is launched from elsewhere. Deliberately not inside+ # the image directory: generation/ is gitignored, an --eval_wild_images_dir may not be.+ save_folder = os.path.join(+ args.gen_output_root or repo_path('generation'),+ target_dir,+ )++ if args.save_path_postfix is not None and not args.eval_no_save_gen:+ save_folder += f'-{args.save_path_postfix}'+ if args.eval_wild_images:+ # A wild run has exactly one output subdirectory, so report the full path the files+ # actually land in rather than its parent.+ print("Save to:", os.path.join(save_folder, args.eval_wild_images_name))+ else:+ print("Save to:", save_folder)++ if accelerator is not None:+ if accelerator.is_main_process:+ if not os.path.exists(save_folder):+ os.makedirs(save_folder)+ else:+ if misc.get_rank() == 0 and not os.path.exists(save_folder):+ os.makedirs(save_folder)++ if not args.eval_no_ema and getattr(model_without_ddp, 'ema_params1', None) is not None:+ # switch to ema params, hard-coded to be the first one+ model_state_dict = copy.deepcopy(model_without_ddp.state_dict())+ ema_state_dict = copy.deepcopy(model_without_ddp.state_dict())+ for i, (name, _value) in enumerate(model_without_ddp.named_parameters()):+ assert name in ema_state_dict+ ema_state_dict[name] = model_without_ddp.ema_params1[i]+ print("Switch to ema")+ model_without_ddp.load_state_dict(ema_state_dict)++ # Track logged resolutions to avoid spam+ logged_resolutions = set()++ # Follow the model rather than assuming CUDA, so evaluation and the wild-image+ # demo also run on a CPU-only machine.+ device = next(model_without_ddp.parameters()).device++ # data iter+ for i, sample in enumerate(data_loader):+ if i in [0, len(data_loader) // 2, len(data_loader) // 4, len(data_loader) * 3 // 4]:+ print("Generation step {}/{}".format(i, len(data_loader)))++ # Benchmark samples carry 'intrinsics'; wild images do not.+ # WildImagesDataset has neither (inference-only, no GT)+ is_eval_depth_loader = 'intrinsics' in sample+ is_wild_images = 'pointcloud' not in sample and 'intrinsics' not in sample++ image = sample['image'] # [B, 3, H, W] in [0, 1]++ # image to [-1, 1]+ image_01 = image.to(device, non_blocking=True).to(torch.float32)+ image = image_01 * 2.0 - 1.0++ if not is_wild_images:+ pointcloud = sample['pointcloud'].to(device, non_blocking=True)+ else:+ pointcloud = None++ # Handle original resolution evaluation: resize input to div-16, then resize output back+ original_size = None+ eval_num_tokens = getattr(args, 'eval_num_tokens', 0)+ if eval_num_tokens > 0 and is_eval_depth_loader:+ # MoGe-style token-based resizing: resize to match target token count while preserving aspect ratio+ B, C, H, W = image.shape+ original_size = (H, W)++ # MoGe-style resize factor calculation+ # Formula: resize_factor = sqrt((num_tokens * patch_size^2) / (H * W))+ patch_size = 16 # PointDiT uses 16x16 patches (vs MoGe's 14x14)+ resize_factor = ((eval_num_tokens * patch_size ** 2) / (H * W)) ** 0.5+ new_H = int(H * resize_factor)+ new_W = int(W * resize_factor)++ # Round to nearest multiple of patch_size (16)+ new_H = (new_H // patch_size) * patch_size+ new_W = (new_W // patch_size) * patch_size++ # Ensure minimum size+ new_H = max(new_H, patch_size)+ new_W = max(new_W, patch_size)++ if (new_H, new_W) != (H, W):+ image = torch.nn.functional.interpolate(+ image, size=(new_H, new_W), mode='bilinear', align_corners=False+ )+ dataset_name = sample['dataset_name'][0] if isinstance(sample.get('dataset_name'), (list, tuple)) else sample.get('dataset_name', 'unknown')+ if (dataset_name, H, W, new_H, new_W) not in logged_resolutions:+ logged_resolutions.add((dataset_name, H, W, new_H, new_W))+ print(f"[eval_num_tokens={eval_num_tokens}] Resized {dataset_name} input: ({H}, {W}) -> ({new_H}, {new_W})")+ else:+ # No resize needed, but still log the resolution info+ dataset_name = sample['dataset_name'][0] if isinstance(sample.get('dataset_name'), (list, tuple)) else sample.get('dataset_name', 'unknown')+ actual_tokens = (new_H // patch_size) * (new_W // patch_size)+ if (dataset_name, H, W, new_H, new_W) not in logged_resolutions:+ logged_resolutions.add((dataset_name, H, W, new_H, new_W))+ print(f"[eval_num_tokens={eval_num_tokens}] {dataset_name}: ({H}, {W}) -> no resize, tokens={actual_tokens}")++ elif getattr(args, 'resize_input_nearest_res', False) and is_eval_depth_loader:+ # Resize to nearest resolution divisible by 16, with optional token constraints+ B, C, H, W = image.shape+ original_size = (H, W)+ patch_size = 16++ # Round to NEAREST multiple of 16 (not floor)+ nearest_H = max(patch_size, int(round(H / patch_size)) * patch_size)+ nearest_W = max(patch_size, int(round(W / patch_size)) * patch_size)+ nearest_tokens = (nearest_H // patch_size) * (nearest_W // patch_size)++ eval_num_tokens = getattr(args, 'eval_num_tokens', 0)++ if eval_num_tokens > 0:+ # Override: use specific token count+ target_tokens = eval_num_tokens+ resize_factor = ((target_tokens * patch_size ** 2) / (nearest_H * nearest_W)) ** 0.5+ new_H = max(patch_size, int(round(nearest_H * resize_factor / patch_size)) * patch_size)+ new_W = max(patch_size, int(round(nearest_W * resize_factor / patch_size)) * patch_size)+ else:+ # Use min/max token logic+ min_tokens = getattr(args, 'eval_min_tokens', 0)+ max_tokens = getattr(args, 'eval_max_tokens', 0)++ if min_tokens > 0 and nearest_tokens < min_tokens:+ target_tokens = min_tokens+ resize_factor = ((target_tokens * patch_size ** 2) / (nearest_H * nearest_W)) ** 0.5+ # Use ceil to ensure tokens >= min_tokens+ new_H = max(patch_size, math.ceil(nearest_H * resize_factor / patch_size) * patch_size)+ new_W = max(patch_size, math.ceil(nearest_W * resize_factor / patch_size) * patch_size)+ elif max_tokens > 0 and nearest_tokens > max_tokens:+ target_tokens = max_tokens+ resize_factor = ((target_tokens * patch_size ** 2) / (nearest_H * nearest_W)) ** 0.5+ # Use floor to ensure tokens <= max_tokens+ new_H = max(patch_size, int(nearest_H * resize_factor / patch_size) * patch_size)+ new_W = max(patch_size, int(nearest_W * resize_factor / patch_size) * patch_size)+ else:+ # Tokens within range, use nearest-16 resolution+ new_H, new_W = nearest_H, nearest_W++ dataset_name = sample['dataset_name'][0] if isinstance(sample.get('dataset_name'), (list, tuple)) else sample.get('dataset_name', 'unknown')+ actual_tokens = (new_H // patch_size) * (new_W // patch_size)++ if (new_H, new_W) != (H, W):+ image = torch.nn.functional.interpolate(+ image, size=(new_H, new_W), mode='bilinear', align_corners=False+ )+ if (dataset_name, H, W, new_H, new_W) not in logged_resolutions:+ logged_resolutions.add((dataset_name, H, W, new_H, new_W))+ print(f"[resize_input_nearest_res] {dataset_name}: ({H}, {W}) -> ({new_H}, {new_W}), tokens={actual_tokens}")+ else:+ # No resize needed, but still log the resolution info+ if (dataset_name, H, W, new_H, new_W) not in logged_resolutions:+ logged_resolutions.add((dataset_name, H, W, new_H, new_W))+ print(f"[resize_input_nearest_res] {dataset_name}: ({H}, {W}) -> no resize, tokens={actual_tokens}")++ elif getattr(args, 'eval_depth_original_resolution', False) and (is_eval_depth_loader or is_wild_images):+ B, C, H, W = image.shape+ original_size = (H, W)++ patch_size = 16+ min_tokens = getattr(args, 'eval_min_tokens', 0)+ max_tokens = getattr(args, 'eval_max_tokens', 0)++ if min_tokens > 0 or max_tokens > 0:+ # Token-based resizing: compute target from original aspect ratio+ nearest_H = max(patch_size, int(round(H / patch_size)) * patch_size)+ nearest_W = max(patch_size, int(round(W / patch_size)) * patch_size)+ nearest_tokens = (nearest_H // patch_size) * (nearest_W // patch_size)++ if min_tokens > 0 and nearest_tokens < min_tokens:+ resize_factor = ((min_tokens * patch_size ** 2) / (nearest_H * nearest_W)) ** 0.5+ new_H = max(patch_size, math.ceil(nearest_H * resize_factor / patch_size) * patch_size)+ new_W = max(patch_size, math.ceil(nearest_W * resize_factor / patch_size) * patch_size)+ elif max_tokens > 0 and nearest_tokens > max_tokens:+ resize_factor = ((max_tokens * patch_size ** 2) / (nearest_H * nearest_W)) ** 0.5+ new_H = max(patch_size, int(nearest_H * resize_factor / patch_size) * patch_size)+ new_W = max(patch_size, int(nearest_W * resize_factor / patch_size) * patch_size)+ else:+ new_H, new_W = nearest_H, nearest_W+ else:+ # Pixel-based resizing fallback+ max_height = getattr(args, 'eval_depth_max_height', None)+ max_width = getattr(args, 'eval_depth_max_width', None)++ if max_height is not None and max_width is not None:+ scale = min(max_height / H, max_width / W, 1.0)+ new_H = int(H * scale)+ new_W = int(W * scale)+ else:+ max_res = getattr(args, 'eval_depth_max_resolution', 1024)+ if max(H, W) > max_res:+ scale = max_res / max(H, W)+ new_H = int(H * scale)+ new_W = int(W * scale)+ else:+ new_H, new_W = H, W++ new_H = (new_H // patch_size) * patch_size+ new_W = (new_W // patch_size) * patch_size+ new_H = max(new_H, patch_size)+ new_W = max(new_W, patch_size)++ if (new_H, new_W) != (H, W):+ image = torch.nn.functional.interpolate(+ image, size=(new_H, new_W), mode='bilinear', align_corners=False+ )+ dataset_name = sample['dataset_name'][0] if isinstance(sample.get('dataset_name'), (list, tuple)) else sample.get('dataset_name', 'unknown')+ actual_tokens = (new_H // patch_size) * (new_W // patch_size)+ if (dataset_name, H, W, new_H, new_W) not in logged_resolutions:+ logged_resolutions.add((dataset_name, H, W, new_H, new_W))+ print(f"[Original Res] Resized {dataset_name} input: ({H}, {W}) -> ({new_H}, {new_W}), tokens={actual_tokens}")+ else:+ # No resize needed, but still log the resolution info+ dataset_name = sample['dataset_name'][0] if isinstance(sample.get('dataset_name'), (list, tuple)) else sample.get('dataset_name', 'unknown')+ actual_tokens = (new_H // patch_size) * (new_W // patch_size)+ if (dataset_name, H, W, new_H, new_W) not in logged_resolutions:+ logged_resolutions.add((dataset_name, H, W, new_H, new_W))+ print(f"[Original Res] {dataset_name}: ({H}, {W}) -> no resize, tokens={actual_tokens}")++ elif is_wild_images:+ # Wild images arrive at their native resolution and have no GT to match, so the+ # only thing that matters is giving the model an input it generalizes well on.+ # It only ever saw one square resolution during training, so keep the token+ # count close to that budget: resize the whole frame with the aspect ratio+ # preserved to the patch-aligned resolution nearest the budget, predict there,+ # and let the original_size block below resize the prediction back to native.+ # Aspect ratio is preserved rather than forced square, since a squashed image is+ # itself off-distribution.+ B, C, H, W = image.shape++ patch_size = getattr(model_without_ddp, 'patch_size', 16)+ target_tokens = getattr(args, 'eval_wild_target_tokens', 0) or eval_num_tokens+ if target_tokens <= 0:+ target_tokens = (args.img_size // patch_size) ** 2++ # Round rather than truncate, so the realized token count straddles the target+ # instead of always landing below it.+ resize_factor = ((target_tokens * patch_size ** 2) / (H * W)) ** 0.5+ new_H = max(patch_size, int(round(H * resize_factor / patch_size)) * patch_size)+ new_W = max(patch_size, int(round(W * resize_factor / patch_size)) * patch_size)++ # An input already at the training token count (a 512x512 image at --img_size 512)+ # needs no resize in either direction. Leaving original_size as None also skips+ # the resize-back below, instead of interpolating to the size it already has.+ if (new_H, new_W) != (H, W):+ original_size = (H, W)+ image = torch.nn.functional.interpolate(+ image, size=(new_H, new_W), mode='bilinear', align_corners=False+ )++ # generation+ with torch.amp.autocast('cuda', dtype=torch.bfloat16):+ # Start inference timing (skip warmup samples)+ if i >= warmup_samples:+ if torch.cuda.is_available():+ torch.cuda.synchronize()+ t_inference_start = time.perf_counter()++ sampled_pointcloud, intermediate_pointcloud = model_without_ddp.generate(image, return_intermediate_steps=True)++ # End inference timing (skip warmup samples)+ if i >= warmup_samples:+ if torch.cuda.is_available():+ torch.cuda.synchronize()+ t_inference_end = time.perf_counter()+ batch_size = image.shape[0]+ total_inference_time += (t_inference_end - t_inference_start)+ inference_sample_count += batch_size++ if args.distributed:+ torch.distributed.barrier()++ sampled_pointcloud = sampled_pointcloud.float()++ # Resize prediction back to original resolution (use 'nearest' for depth/pointcloud)+ if original_size is not None:+ sampled_pointcloud = torch.nn.functional.interpolate(+ sampled_pointcloud, size=original_size, mode='nearest'+ )+ # Also resize intermediate_pointcloud for visualization consistency+ for k in intermediate_pointcloud.keys():+ intermediate_pointcloud[k] = torch.nn.functional.interpolate(+ intermediate_pointcloud[k].float(), size=original_size, mode='nearest'+ )++ # remove_sky: detect predicted sky on the RAW model output (normalized space),+ # BEFORE the radial-log inverse and scale/shift alignment. Training with+ # --handle_sky places sky pixels at norm ~sky_far_plane_value (default 3.0) in+ # this space; after the inverse transform / affine alignment the value becomes+ # scene-dependent (e.g. norm ~exp(3)-1 in linear space, then metric after+ # alignment), so a fixed threshold is only meaningful here. The per-pixel mask+ # is computed at the final (post-resize) resolution so it stays aligned with the+ # saved point clouds, which are spatially unchanged by the later affine transform.+ pred_sky_mask = None+ if getattr(args, 'remove_sky', False):+ if getattr(args, 'remove_sky_metric', 'norm') == 'depth':+ sky_metric = sampled_pointcloud[:, 2] # [B, H, W]+ else:+ sky_metric = sampled_pointcloud.norm(dim=1) # [B, H, W]+ pred_sky_mask = sky_metric > args.remove_sky_threshold # [B, H, W] bool, True = sky++ # compute metrics (skipped for wild images with no GT)+ raw_sampled_pointcloud = None+ # Initialised per sample: the "<100 valid GT points" early exit below skips the+ # compute_affine_metrics() call that populates this, while the shared visualization+ # path still reads it. Without this, the first such sample raises UnboundLocalError+ # and later ones would splice the previous sample's boundary_viz into this panel.+ align_outputs = {}+ if is_wild_images:+ affine_points_scale = torch.tensor(1.0, device=sampled_pointcloud.device)+ affine_points_shift = torch.zeros(1, 3, 1, 1, device=sampled_pointcloud.device)+ with torch.no_grad():+ if not is_wild_images:++ # compute affine metrics+ assert sampled_pointcloud.shape[0] == 1 # only support batch size 1 for now++ # Get GT pointcloud based on dataloader type+ if is_eval_depth_loader:+ # EvalDepthDataset: pointcloud is already unnormalized (raw GT)+ gt_pointcloud = sample['pointcloud'].to(sampled_pointcloud.device, non_blocking=True)+ # Use valid_mask from dataloader (handles NaN/Inf)+ gt_valid_mask = sample['valid_mask'].to(sampled_pointcloud.device, non_blocking=True)+ else:+ # fall back to the unnormalized point cloud+ gt_pointcloud = sample['pointcloud_unnormalized'].to(sampled_pointcloud.device, non_blocking=True)+ # Valid mask is depth > 0+ gt_valid_mask = gt_pointcloud[:, 2] > 0++ # Check if there are enough valid points for metric computation+ num_valid_points = gt_valid_mask.sum().item()+ if num_valid_points < 100:+ print(f"[Warning] Sample {i} has only {num_valid_points} valid points, skipping metrics computation")+ # Skip this sample but still save visualization if needed+ pointcloud = gt_pointcloud+ # Use dummy values for visualization+ affine_points_scale = torch.tensor(1.0, device=sampled_pointcloud.device)+ affine_points_shift = torch.zeros(1, 3, 1, 1, device=sampled_pointcloud.device)+ else:+ pred = {+ 'points_affine_invariant': sampled_pointcloud.permute(0, 2, 3, 1), # [B, H, W, 3],+ 'depth_affine_invariant': sampled_pointcloud[:, 2], # [B, H, W]+ }+ gt = {+ 'points': gt_pointcloud.permute(0, 2, 3, 1), # [B, H, W, 3],+ 'depth': gt_pointcloud[:, 2], # [B, H, W]+ 'depth_mask': gt_valid_mask,+ }+ # Determine if this sample's dataset should compute SI boundary F1+ dataset_name = sample['dataset_name'][0] if 'dataset_name' in sample and isinstance(sample['dataset_name'], (list, tuple)) else sample.get('dataset_name', '')+ compute_si_boundary = dataset_name in boundary_datasets+ compute_depth_range = getattr(args, 'eval_depth_range_metrics', False)+ affine_metrics, align_outputs = compute_affine_metrics(pred, gt, vis=True, compute_si_boundary=compute_si_boundary, compute_depth_range=compute_depth_range)++ total_affine_rel_depth += affine_metrics['depth_affine_invariant']['rel']+ total_affine_delta1_depth += affine_metrics['depth_affine_invariant']['delta1']++ total_affine_rel_point += affine_metrics['points_affine_invariant']['rel']+ total_affine_delta1_point += affine_metrics['points_affine_invariant']['delta1']++ num_valid_samples += 1 # Increment valid sample counter++ # Accumulate SI boundary F1 if computed+ if 'si_boundary_f1' in affine_metrics:+ total_si_boundary_f1 += affine_metrics['si_boundary_f1']+ num_si_boundary_samples += 1++ # Accumulate depth-range metrics+ if 'depth_range' in affine_metrics:+ for bin_name, bin_metrics in affine_metrics['depth_range'].items():+ depth_range_global[bin_name]['total_rel_depth'] += bin_metrics['rel_depth']+ depth_range_global[bin_name]['total_delta1_depth'] += bin_metrics['delta1_depth']+ depth_range_global[bin_name]['count'] += 1+ if 'rel_point' in bin_metrics:+ depth_range_global[bin_name]['total_rel_point'] += bin_metrics['rel_point']+ depth_range_global[bin_name]['total_delta1_point'] += bin_metrics['delta1_point']++ # Track per-dataset metrics+ if 'dataset_name' in sample:+ # Extract dataset name (handle batch dimension)+ dataset_name = sample['dataset_name'][0] if isinstance(sample['dataset_name'], (list, tuple)) else sample['dataset_name']+ per_dataset_metrics[dataset_name]['total_affine_rel_depth'] += affine_metrics['depth_affine_invariant']['rel']+ per_dataset_metrics[dataset_name]['total_affine_delta1_depth'] += affine_metrics['depth_affine_invariant']['delta1']+ per_dataset_metrics[dataset_name]['total_affine_rel_point'] += affine_metrics['points_affine_invariant']['rel']+ per_dataset_metrics[dataset_name]['total_affine_delta1_point'] += affine_metrics['points_affine_invariant']['delta1']+ per_dataset_metrics[dataset_name]['num_valid_samples'] += 1+ # Track SI boundary F1 per dataset+ if 'si_boundary_f1' in affine_metrics:+ per_dataset_metrics[dataset_name]['total_si_boundary_f1'] += affine_metrics['si_boundary_f1']+ per_dataset_metrics[dataset_name]['num_si_boundary_samples'] += 1++ # Track depth-range metrics per dataset+ if 'depth_range' in affine_metrics:+ for bin_name, bin_metrics in affine_metrics['depth_range'].items():+ ds_bin = per_dataset_metrics[dataset_name]['depth_range'][bin_name]+ ds_bin['total_rel_depth'] += bin_metrics['rel_depth']+ ds_bin['total_delta1_depth'] += bin_metrics['delta1_depth']+ ds_bin['count'] += 1+ if 'rel_point' in bin_metrics:+ ds_bin['total_rel_point'] += bin_metrics['rel_point']+ ds_bin['total_delta1_point'] += bin_metrics['delta1_point']++ # DIODE indoor/outdoor split - additionally track split metrics+ if getattr(args, 'eval_diode_split_indoor_outdoor', False) and dataset_name == 'DIODE':+ sample_id = sample['sample_id'][0] if isinstance(sample['sample_id'], (list, tuple)) else sample['sample_id']+ if 'indoor' in sample_id.lower():+ split_name = 'DIODE_indoor'+ elif 'outdoor' in sample_id.lower():+ split_name = 'DIODE_outdoor'+ else:+ split_name = None++ if split_name:+ per_dataset_metrics[split_name]['total_affine_rel_depth'] += affine_metrics['depth_affine_invariant']['rel']+ per_dataset_metrics[split_name]['total_affine_delta1_depth'] += affine_metrics['depth_affine_invariant']['delta1']+ per_dataset_metrics[split_name]['total_affine_rel_point'] += affine_metrics['points_affine_invariant']['rel']+ per_dataset_metrics[split_name]['total_affine_delta1_point'] += affine_metrics['points_affine_invariant']['delta1']+ per_dataset_metrics[split_name]['num_valid_samples'] += 1++ # Collect per-sample metrics if enabled+ if per_sample_metrics is not None and 'sample_id' in sample:+ sample_id_str = sample['sample_id'][0] if isinstance(sample['sample_id'], (list, tuple)) else sample['sample_id']+ dataset_name_str = dataset_name if 'dataset_name' in sample else 'default'+ sample_record = {+ 'sample_id': sample_id_str,+ 'dataset_name': dataset_name_str,+ 'affine_rel_depth': affine_metrics['depth_affine_invariant']['rel'],+ 'affine_delta1_depth': affine_metrics['depth_affine_invariant']['delta1'],+ 'affine_rel_point': affine_metrics['points_affine_invariant']['rel'],+ 'affine_delta1_point': affine_metrics['points_affine_invariant']['delta1'],+ 'si_boundary_f1': affine_metrics.get('si_boundary_f1', None),+ }++ # Compute boundary F1 for each intermediate diffusion step+ if (getattr(args, 'eval_intermediate_boundary', False)+ and intermediate_pointcloud+ and compute_si_boundary):+ step_boundary_f1 = {}+ for step_key in sorted(intermediate_pointcloud.keys()):+ if step_key == -1:+ continue # skip initial noise+ step_pc = intermediate_pointcloud[step_key].float()+ step_pred = {+ 'points_affine_invariant': step_pc.permute(0, 2, 3, 1),+ 'depth_affine_invariant': step_pc[:, 2],+ }+ step_metrics, _ = compute_affine_metrics(+ step_pred, gt, vis=False,+ compute_si_boundary=True,+ compute_depth_range=False+ )+ num_steps_done = step_key + 1+ step_boundary_f1[f'step_{num_steps_done}'] = step_metrics.get('si_boundary_f1', None)++ # Add final output as the last step+ total_steps = len([k for k in intermediate_pointcloud if k != -1]) + 1+ step_boundary_f1[f'step_{total_steps}'] = affine_metrics.get('si_boundary_f1', None)+ sample_record['si_boundary_f1_by_step'] = step_boundary_f1++ per_sample_metrics.append(sample_record)++ # Save raw (unaligned) prediction for optional visualization+ if getattr(args, 'viz_unaligned_depth', False):+ raw_sampled_pointcloud = sampled_pointcloud.detach().clone()++ # update viz+ sampled_pointcloud = align_outputs['pred_points'].permute(0, 3, 1, 2) # [B, 3, H, W]+ sampled_pointcloud[:, 2][sampled_pointcloud[:, 2] < 0.] = 0.++ affine_points_scale = align_outputs['affine_points_scale'] # [1]+ affine_points_shift = align_outputs['affine_points_shift'].reshape(1, 3, 1, 1) # [1, 3, 1, 1]++ # unnormalize gt pointcloud for visualization+ pointcloud = gt_pointcloud++ # distributed save depths+ for b_id in range(sampled_pointcloud.size(0)):+ img_id = i * sampled_pointcloud.size(0) * world_size + local_rank * sampled_pointcloud.size(0) + b_id++ # Determine save directory (per-dataset subdirectory for multi-dataset evaluation).+ # For wild images the name comes from --eval_wild_images_name.+ if 'dataset_name' in sample:+ dataset_name = sample['dataset_name'][b_id] if isinstance(sample['dataset_name'], (list, tuple)) else sample['dataset_name']+ dataset_save_folder = os.path.join(save_folder, dataset_name)+ # Create dataset-specific subdirectory if it doesn't exist+ if not args.online_eval and not args.eval_no_save_gen:+ if accelerator is not None:+ if accelerator.is_main_process:+ os.makedirs(dataset_save_folder, exist_ok=True)+ else:+ if misc.get_rank() == 0:+ os.makedirs(dataset_save_folder, exist_ok=True)+ else:+ # Single dataset or no dataset_name - save to root folder+ dataset_save_folder = save_folder++ # Use sample_id for filename if available (EvalDepthDataset or WildImagesDataset)+ if 'sample_id' in sample:+ sample_id_raw = sample['sample_id'][b_id] if isinstance(sample['sample_id'], list) else sample['sample_id']+ if args.eval_wild_images:+ # Mirror the input filename, so sample0.png yields sample0_depth.png and+ # sample0_pointcloud.ply. No index prefix, and the extension is dropped so+ # it is not doubled. Any subdirectory the image sat in is preserved, which+ # also stops same-named images in different folders overwriting each other.+ file_prefix = os.path.splitext(sample_id_raw)[0]+ sub = os.path.dirname(file_prefix)+ if sub and not args.online_eval and not args.eval_no_save_gen:+ os.makedirs(os.path.join(dataset_save_folder, sub), exist_ok=True)+ else:+ # Replace / with _ for valid filename+ file_prefix = f"{img_id:05d}_{sample_id_raw.replace('/', '_')}"+ else:+ file_prefix = f'{img_id:05d}'++ # remove_sky: per-sample keep-mask (True = keep, False = sky to drop), derived+ # from the raw-output sky detection above. Used both to hide sky in the depth+ # viz and to filter sky out of the saved point clouds.+ sky_keep_mask = None+ if pred_sky_mask is not None:+ sky_keep_mask = (~pred_sky_mask[b_id]).detach().cpu().numpy() # (H, W) bool++ # depth_gt (only available when GT exists)+ if not is_wild_images:+ depth_gt = pointcloud[b_id, 2].detach().cpu() # [H, W]+ if is_eval_depth_loader:+ depth_gt_for_viz = depth_gt.clone()+ depth_gt_for_viz[~torch.isfinite(depth_gt_for_viz)] = 0+ depth_gt_viz = viz_depth_tensor(depth_gt_for_viz, shifted_depth=False, colormap=args.depth_colormap) # [H, W, 3] np+ else:+ depth_gt_viz = viz_depth_tensor(depth_gt, shifted_depth=False, colormap=args.depth_colormap) # [H, W, 3] np++ # depth from z+ # For wild images the model output is zero-centered (center_shift_point + normalize_point_by_mean)+ # with no affine alignment, so we must not clamp to 0 and must use shifted_depth=True+ if is_wild_images:+ sampled_depth = sampled_pointcloud[b_id, 2] # [H, W], may be negative+ sampled_depth_viz = sampled_depth+ # remove_sky: push predicted sky to far so it drops out of the depth viz+ if pred_sky_mask is not None:+ sampled_depth_viz = torch.where(pred_sky_mask[b_id], torch.full_like(sampled_depth_viz, 1e6), sampled_depth_viz)+ depth_viz = viz_depth_tensor(sampled_depth_viz, shifted_depth=True, colormap=args.depth_colormap) # [H, W, 3] np+ else:+ sampled_depth = sampled_pointcloud[b_id, 2].clamp(min=0) # [H, W]+ sampled_depth_viz = sampled_depth+ # remove_sky: treat predicted sky as far/invalid in the depth viz+ if pred_sky_mask is not None:+ sampled_depth_viz = torch.where(pred_sky_mask[b_id], torch.full_like(sampled_depth_viz, 1e6), sampled_depth_viz)+ depth_viz = viz_depth_tensor(sampled_depth_viz, shifted_depth=False, colormap=args.depth_colormap) # [H, W, 3] np++ img_viz = (image_01[b_id].permute(1, 2, 0).detach().cpu() * 255.).to(torch.uint8).numpy()++ # remove_sky: build an [input | sky-mask | overlay] panel so the threshold can+ # be checked visually. mask is white where sky (removed); overlay tints sky red.+ skymask_concat = None+ if pred_sky_mask is not None:+ sky_b = pred_sky_mask[b_id].detach().cpu().numpy() # (H, W) bool, True = sky+ mask_viz = np.repeat((sky_b[:, :, None].astype(np.uint8) * 255), 3, axis=2) # (H, W, 3)+ overlay = img_viz.copy()+ overlay[sky_b] = (0.5 * overlay[sky_b].astype(np.float32)+ + 0.5 * np.array([255, 0, 0], dtype=np.float32)).astype(np.uint8)+ skymask_concat = np.concatenate([img_viz, mask_viz, overlay], axis=1)++ concat_list = [img_viz]++ # save the intermediate generation results+ for k, v in intermediate_pointcloud.items():+ # to the original scale+ v = v * affine_points_scale + affine_points_shift # [B, 3, H, W]+ if is_wild_images:+ depth_k = v[b_id, 2].detach().cpu() # [H, W], keep raw (zero-centered)+ depth_k_viz = viz_depth_tensor(depth_k, shifted_depth=True, colormap=args.depth_colormap)+ else:+ depth_k = v[b_id, 2].detach().cpu().clamp(min=0) # [H, W]+ depth_k_viz = viz_depth_tensor(depth_k, shifted_depth=False, colormap=args.depth_colormap)+ if not is_wild_images:+ concat_list.append(depth_k_viz)++ # final prediction (and GT + error map if available)+ concat_list.append(depth_viz)+ if not is_wild_images and raw_sampled_pointcloud is not None:+ unaligned_depth = raw_sampled_pointcloud[b_id, 2] # [H, W], zero-centered+ unaligned_depth_viz = viz_depth_tensor(unaligned_depth, shifted_depth=True, colormap=args.depth_colormap)+ concat_list.append(unaligned_depth_viz)+ if not is_wild_images:+ concat_list.append(depth_gt_viz)++ # also visualize point error map+ point_pred_error = torch.abs(sampled_pointcloud[b_id] - pointcloud[b_id]).mean(0) # [H, W]+ # For EvalDepthDataset, mask out NaN/Inf before computing min/max+ if is_eval_depth_loader:+ valid_error_mask = gt_valid_mask[b_id]+ point_pred_error_valid = point_pred_error.clone()+ point_pred_error_valid[~valid_error_mask] = 0+ valid_errors = point_pred_error[valid_error_mask]+ if valid_errors.numel() > 0:+ error_min, error_max = valid_errors.min(), valid_errors.max()+ else:+ error_min, error_max = 0, 1+ error_normalized = (point_pred_error_valid - error_min) / (error_max - error_min + 1e-8)+ error_normalized[~valid_error_mask] = 0.+ else:+ error_normalized = (point_pred_error - point_pred_error.min()) / (point_pred_error.max() - point_pred_error.min() + 1e-8)+ error_normalized[pointcloud[b_id, 2] <= 0] = 0.+ error_normalized = (error_normalized * 255.).to(torch.uint8).detach().cpu()+ error_normalized = error_normalized[:, :, None].repeat(1, 1, 3).numpy() # [H, W, 3]+ concat_list.append(error_normalized)++ # Add boundary visualization if computed+ if 'boundary_viz' in align_outputs:+ concat_list.append(align_outputs['boundary_viz'])++ # concat all the results+ concat = np.concatenate(concat_list, axis=1)++ # save+ if not args.online_eval and not args.eval_no_save_gen:+ save_path = os.path.join(dataset_save_folder, f'{file_prefix}_depth.png')+ Image.fromarray(concat).save(save_path)++ # remove_sky: save the [input | mask | overlay] panel; threshold is in the+ # filename so multiple --remove_sky_threshold runs can be compared side by side.+ # Skipped for demo runs, which want only the depth map and the point cloud.+ if skymask_concat is not None and not args.eval_wild_images:+ skymask_path = os.path.join(+ dataset_save_folder,+ f'{file_prefix}_skymask_th{args.remove_sky_threshold:.2f}.png')+ Image.fromarray(skymask_concat).save(skymask_path)++ # save raw numpy arrays for cross-run comparison+ if getattr(args, 'save_raw_depth_npy', False) and not args.online_eval and not args.eval_no_save_gen:+ # Save predicted depth (after affine alignment)+ pred_depth_path = os.path.join(dataset_save_folder, f'{file_prefix}_depth_pred.npy')+ np.save(pred_depth_path, sampled_depth.detach().cpu().numpy())+ # Save predicted pointcloud [3, H, W]+ pred_pc_path = os.path.join(dataset_save_folder, f'{file_prefix}_pointcloud_pred.npy')+ np.save(pred_pc_path, sampled_pointcloud[b_id].detach().cpu().numpy())+ # Save input image for visualization+ input_img_path = os.path.join(dataset_save_folder, f'{file_prefix}_input.png')+ Image.fromarray(img_viz).save(input_img_path)++ # log to wandb+ if args.online_eval and b_id == 0:+ should_log = False+ viz_tag = None++ if is_multi_dataset_viz:+ # Multiple datasets: log 2 samples per dataset+ if 'dataset_name' in sample:+ dataset_name = sample['dataset_name'][b_id] if isinstance(sample['dataset_name'], (list, tuple)) else sample['dataset_name']+ if dataset_name not in per_dataset_viz_counters:+ per_dataset_viz_counters[dataset_name] = 0++ counter = per_dataset_viz_counters[dataset_name]+ if counter < samples_per_dataset:+ should_log = True+ viz_tag = f'test_viz/{dataset_name}_sample{counter}'+ per_dataset_viz_counters[dataset_name] += 1+ else:+ # Single dataset: log 4 samples total+ if i % log_eval_freq == 0 and eval_counter < num_val_samples:+ should_log = True+ viz_tag = f'test_viz/sample{eval_counter}'+ eval_counter += 1++ if should_log and viz_tag is not None:+ is_main = accelerator.is_main_process if accelerator is not None else (misc.get_rank() == 0)+ if is_main:+ val_logs[viz_tag] = wandb.Image(concat)+ # remove_sky: also log the [input | mask | overlay] panel+ if skymask_concat is not None:+ val_logs[f'{viz_tag}_skymask'] = wandb.Image(skymask_concat)++ # save point cloud+ save_path_pointcloud = os.path.join(dataset_save_folder, f'{file_prefix}_pointcloud.ply')++ # save generated and gt point cloud+ if not args.online_eval and not args.eval_no_save_gen:+ # For EvalDepthDataset, filter out NaN/Inf points before saving+ if is_eval_depth_loader:+ valid_mask_np = gt_valid_mask[b_id].detach().cpu().numpy()++ # Get point clouds and colors+ sampled_pc_np = sampled_pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy() # (H, W, 3)+ gt_pc_np = pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy() # (H, W, 3)+ img_np = image_01[b_id].permute(1, 2, 0).detach().cpu().numpy() # (H, W, 3)++ # Set invalid points to 0 (or filter them out)+ sampled_pc_clean = sampled_pc_np.copy()+ gt_pc_clean = gt_pc_np.copy()+ # sampled_pc_clean[~valid_mask_np] = 0+ gt_pc_clean[~valid_mask_np] = 0++ de_mask = None+ gt_de_mask = None+ if getattr(args, 'remove_depth_edge', False):+ de_mask = ~depth_flying_points(sampled_pc_clean[:, :, 2], rtol=args.depth_edge_rtol)+ gt_de_mask = ~depth_flying_points(gt_pc_clean[:, :, 2], rtol=args.depth_edge_rtol)+ # remove_sky: drop predicted sky points (prediction only, not GT)+ de_mask = combine_keep_masks(de_mask, sky_keep_mask)+ save_generated_gt_point_cloud(+ sampled_pc_clean,+ img_np,+ gt_pc_clean,+ img_np,+ filename=save_path_pointcloud,+ mask=de_mask,+ gt_mask=gt_de_mask,+ )+ else:+ if is_wild_images:+ de_mask = None+ if getattr(args, 'remove_depth_edge', False):+ pred_depth_np = sampled_pointcloud[b_id][2].detach().cpu().numpy()+ de_mask = ~depth_flying_points(pred_depth_np, rtol=args.depth_edge_rtol)+ # remove_sky: drop predicted sky points+ de_mask = combine_keep_masks(de_mask, sky_keep_mask)+ save_single_point_cloud(+ sampled_pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy(),+ image_01[b_id].permute(1, 2, 0).detach().cpu().numpy(),+ filename=save_path_pointcloud,+ mask=de_mask,+ )+ else:+ save_generated_gt_point_cloud(sampled_pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy(),+ image_01[b_id].permute(1, 2, 0).detach().cpu().numpy(),+ pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy(),+ image_01[b_id].permute(1, 2, 0).detach().cpu().numpy(),+ filename=save_path_pointcloud,+ mask=sky_keep_mask,+ )++ # save intermediate generated point cloud separately if flag is enabled+ if args.save_separate_intermediate_plys and not args.online_eval and not args.eval_no_save_gen:+ # Get base filename without extension+ base_path = save_path_pointcloud.replace('.ply', '')++ # Prepare point clouds and colors+ img_np = image_01[b_id].permute(1, 2, 0).detach().cpu().numpy() # (H, W, 3)++ # Handle EvalDepthDataset with valid masks+ if is_eval_depth_loader:+ valid_mask_np = gt_valid_mask[b_id].detach().cpu().numpy()+ sampled_pc_np = sampled_pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy() # (H, W, 3)+ gt_pc_np = pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy() # (H, W, 3)++ # Set invalid points to 0+ sampled_pc_clean = sampled_pc_np.copy()+ gt_pc_clean = gt_pc_np.copy()+ # sampled_pc_clean[~valid_mask_np] = 0+ gt_pc_clean[~valid_mask_np] = 0+ elif is_wild_images:+ sampled_pc_clean = sampled_pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy()+ gt_pc_clean = None+ else:+ sampled_pc_clean = sampled_pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy()+ gt_pc_clean = pointcloud[b_id].permute(1, 2, 0).detach().cpu().numpy()++ # Compute depth edge masks+ de_mask = None+ gt_de_mask = None+ if getattr(args, 'remove_depth_edge', False):+ de_mask = ~depth_flying_points(sampled_pc_clean[:, :, 2], rtol=args.depth_edge_rtol)+ if gt_pc_clean is not None:+ gt_de_mask = ~depth_flying_points(gt_pc_clean[:, :, 2], rtol=args.depth_edge_rtol)+ # remove_sky: drop predicted sky points (applied to pred + intermediate steps,+ # which share the same sky pixels; GT is left untouched)+ de_mask = combine_keep_masks(de_mask, sky_keep_mask)++ # Save predicted point cloud+ pred_path = f'{base_path}_pred.ply'+ save_single_point_cloud(sampled_pc_clean, img_np, pred_path, transform_to_gl=True, mask=de_mask)++ # Save GT point cloud (only when GT exists)+ if gt_pc_clean is not None:+ gt_path = f'{base_path}_gt.ply'+ save_single_point_cloud(gt_pc_clean, img_np, gt_path, transform_to_gl=True, mask=gt_de_mask)++ # Save intermediate diffusion steps+ if intermediate_pointcloud:+ for k, v in intermediate_pointcloud.items():+ # Convert to original scale+ v_scaled = v * affine_points_scale + affine_points_shift # [B, 3, H, W]+ point_k = v_scaled[b_id].permute(1, 2, 0).detach().cpu().numpy() # (H, W, 3)++ # Handle valid masks for EvalDepthDataset+ if is_eval_depth_loader:+ point_k_clean = point_k.copy()+ # point_k_clean[~valid_mask_np] = 0+ else:+ point_k_clean = point_k++ # Save with appropriate naming+ if k == -1:+ # Initial random noise+ step_path = f'{base_path}_noise_init.ply'+ else:+ # Regular diffusion step+ step_path = f'{base_path}_step{k}.ply'+ save_single_point_cloud(point_k_clean, img_np, step_path, transform_to_gl=True, mask=de_mask)++ # save intermediate depth maps separately if flag is enabled+ if args.save_separate_intermediate_depths and not args.online_eval and not args.eval_no_save_gen:+ # Get base filename without extension+ base_path = save_path_pointcloud.replace('.ply', '')++ # Save input image+ img_h, img_w = image_01.shape[-2], image_01.shape[-1]+ res_suffix = f'_{img_h}x{img_w}' if getattr(args, 'save_resolution_in_filename', False) else ''+ input_img_path = f'{base_path}_input{res_suffix}.png'+ Image.fromarray((image_01[b_id].permute(1, 2, 0).detach().cpu().numpy() * 255).astype(np.uint8)).save(input_img_path)++ # Save predicted depth+ pred_depth_path = f'{base_path}_depth_pred.png'+ Image.fromarray(depth_viz).save(pred_depth_path)++ # Save GT depth (only when GT exists)+ if not is_wild_images:+ gt_depth_path = f'{base_path}_depth_gt.png'+ Image.fromarray(depth_gt_viz).save(gt_depth_path)++ # Save intermediate diffusion steps+ if intermediate_pointcloud:+ for k, v in intermediate_pointcloud.items():+ # Convert to original scale+ v_scaled = v * affine_points_scale + affine_points_shift # [B, 3, H, W]+ depth_k = v_scaled[b_id, 2].detach().cpu().clamp(min=0) # [H, W]+ depth_k_viz = viz_depth_tensor(depth_k, shifted_depth=False, colormap=args.depth_colormap) # [H, W, 3] np++ # Save with appropriate naming+ if k == -1:+ # Initial random noise+ step_path = f'{base_path}_depth_noise_init.png'+ else:+ # Regular diffusion step+ step_path = f'{base_path}_depth_step{k}.png'+ Image.fromarray(depth_k_viz).save(step_path)++ # TODO: compute depth and pointcloud metrics++ # Save per-sample metrics to JSON (if enabled)+ if per_sample_metrics is not None:+ import json+ if accelerator is not None:+ # Gather all per-sample metrics from all processes+ gathered = accelerator.gather_for_metrics(per_sample_metrics)+ if accelerator.is_main_process:+ # Flatten the gathered list (it may be nested)+ all_per_sample_metrics = gathered if isinstance(gathered, list) else list(gathered)+ metrics_path = os.path.join(save_folder, 'per_sample_metrics.json')+ with open(metrics_path, 'w') as f:+ json.dump(all_per_sample_metrics, f, indent=2)+ print(f"Saved per-sample metrics to: {metrics_path}")+ elif args.distributed:+ # For torch.distributed, gather to all processes then save on rank 0+ gathered = [None] * world_size+ dist.all_gather_object(gathered, per_sample_metrics)+ if misc.get_rank() == 0:+ all_per_sample_metrics = [m for sublist in gathered for m in sublist]+ metrics_path = os.path.join(save_folder, 'per_sample_metrics.json')+ with open(metrics_path, 'w') as f:+ json.dump(all_per_sample_metrics, f, indent=2)+ print(f"Saved per-sample metrics to: {metrics_path}")+ else:+ # Single GPU+ metrics_path = os.path.join(save_folder, 'per_sample_metrics.json')+ with open(metrics_path, 'w') as f:+ json.dump(per_sample_metrics, f, indent=2)+ print(f"Saved per-sample metrics to: {metrics_path}")++ # Aggregate per_dataset_metrics across all processes+ if accelerator is not None and per_dataset_metrics:+ # Aggregate each local dataset's metrics across all processes+ # No need to gather dataset names - just aggregate what each process has seen+ # accelerator.reduce() will sum metrics from all processes+ aggregated_per_dataset_metrics = {}++ for dataset_name, local_metrics in per_dataset_metrics.items():+ stats = [+ local_metrics['total_affine_rel_depth'],+ local_metrics['total_affine_delta1_depth'],+ local_metrics['total_affine_rel_point'],+ local_metrics['total_affine_delta1_point'],+ float(local_metrics['num_valid_samples']),+ local_metrics['total_si_boundary_f1'],+ float(local_metrics['num_si_boundary_samples']),+ ]+ # Add depth-range stats: 5 values per bin (rel_depth, delta1_depth, rel_point, delta1_point, count)+ for b in depth_range_bins:+ dr = local_metrics['depth_range'][b]+ stats.extend([dr['total_rel_depth'], dr['total_delta1_depth'], dr['total_rel_point'], dr['total_delta1_point'], float(dr['count'])])+ stats_tensor = torch.tensor(stats, dtype=torch.float32, device=accelerator.device)+ global_stats = accelerator.reduce(stats_tensor, reduction="sum")++ # Store aggregated metrics+ aggregated_per_dataset_metrics[dataset_name] = {+ 'total_affine_rel_depth': global_stats[0].item(),+ 'total_affine_delta1_depth': global_stats[1].item(),+ 'total_affine_rel_point': global_stats[2].item(),+ 'total_affine_delta1_point': global_stats[3].item(),+ 'num_valid_samples': int(global_stats[4].item()),+ 'total_si_boundary_f1': global_stats[5].item(),+ 'num_si_boundary_samples': int(global_stats[6].item()),+ 'depth_range': {},+ }+ for i, b in enumerate(depth_range_bins):+ base = 7 + i * 5+ aggregated_per_dataset_metrics[dataset_name]['depth_range'][b] = {+ 'total_rel_depth': global_stats[base].item(),+ 'total_delta1_depth': global_stats[base + 1].item(),+ 'total_rel_point': global_stats[base + 2].item(),+ 'total_delta1_point': global_stats[base + 3].item(),+ 'count': int(global_stats[base + 4].item()),+ }++ # Replace local per_dataset_metrics with aggregated version+ per_dataset_metrics = aggregated_per_dataset_metrics++ elif args.distributed and per_dataset_metrics:+ # Fallback to torch.distributed for aggregation+ # Aggregate each local dataset's metrics across all processes+ aggregated_per_dataset_metrics = {}++ for dataset_name, local_metrics in per_dataset_metrics.items():+ stats = [+ local_metrics['total_affine_rel_depth'],+ local_metrics['total_affine_delta1_depth'],+ local_metrics['total_affine_rel_point'],+ local_metrics['total_affine_delta1_point'],+ float(local_metrics['num_valid_samples']),+ local_metrics['total_si_boundary_f1'],+ float(local_metrics['num_si_boundary_samples']),+ ]+ for b in depth_range_bins:+ dr = local_metrics['depth_range'][b]+ stats.extend([dr['total_rel_depth'], dr['total_delta1_depth'], dr['total_rel_point'], dr['total_delta1_point'], float(dr['count'])])+ stats_tensor = torch.tensor(stats, dtype=torch.float32, device='cuda')++ # Barrier to ensure all processes are ready+ dist.barrier()++ # All-Reduce (Sum) across all GPUs+ dist.all_reduce(stats_tensor, op=dist.ReduceOp.SUM)++ # Store aggregated metrics+ aggregated_per_dataset_metrics[dataset_name] = {+ 'total_affine_rel_depth': stats_tensor[0].item(),+ 'total_affine_delta1_depth': stats_tensor[1].item(),+ 'total_affine_rel_point': stats_tensor[2].item(),+ 'total_affine_delta1_point': stats_tensor[3].item(),+ 'num_valid_samples': int(stats_tensor[4].item()),+ 'total_si_boundary_f1': stats_tensor[5].item(),+ 'num_si_boundary_samples': int(stats_tensor[6].item()),+ 'depth_range': {},+ }+ for i, b in enumerate(depth_range_bins):+ base = 7 + i * 5+ aggregated_per_dataset_metrics[dataset_name]['depth_range'][b] = {+ 'total_rel_depth': stats_tensor[base].item(),+ 'total_delta1_depth': stats_tensor[base + 1].item(),+ 'total_rel_point': stats_tensor[base + 2].item(),+ 'total_delta1_point': stats_tensor[base + 3].item(),+ 'count': int(stats_tensor[base + 4].item()),+ }++ # Replace local per_dataset_metrics with aggregated version+ per_dataset_metrics = aggregated_per_dataset_metrics++ # Debug: Print aggregated per-dataset sample counts+ if per_dataset_metrics:+ total_per_dataset_samples = sum(m['num_valid_samples'] for m in per_dataset_metrics.values())+ if accelerator is not None:+ if accelerator.is_main_process:+ print(f"[Aggregated] Per-dataset samples: {dict((k, v['num_valid_samples']) for k, v in per_dataset_metrics.items())}")+ print(f"[Aggregated] Total per-dataset samples: {total_per_dataset_samples}")+ elif misc.get_rank() == 0:+ print(f"[Aggregated] Per-dataset samples: {dict((k, v['num_valid_samples']) for k, v in per_dataset_metrics.items())}")+ print(f"[Aggregated] Total per-dataset samples: {total_per_dataset_samples}")++ if accelerator is not None:+ # 1. Wrap your values in a tensor (include num_valid_samples)+ stats_tensor = torch.tensor([+ total_affine_rel_depth,+ total_affine_delta1_depth,+ total_affine_rel_point,+ total_affine_delta1_point,+ float(num_valid_samples), # Add sample count+ total_si_boundary_f1,+ float(num_si_boundary_samples),+ ], dtype=torch.float32, device=accelerator.device)++ # 2. Reduce across all processes (default op is "sum")+ # This replaces the barrier and the manual all_reduce+ reduced_stats = accelerator.reduce(stats_tensor, reduction="sum")++ # 3. Extract values (sum across all processes)+ global_affine_rel_depth_sum = reduced_stats[0].item()+ global_affine_delta1_depth_sum = reduced_stats[1].item()+ global_affine_rel_point_sum = reduced_stats[2].item()+ global_affine_delta1_point_sum = reduced_stats[3].item()+ global_num_valid_samples = int(reduced_stats[4].item())+ global_si_boundary_f1_sum = reduced_stats[5].item()+ global_num_si_boundary_samples = int(reduced_stats[6].item())++ elif args.distributed:+ # 1. Create a tensor to hold the data (include num_valid_samples)+ stats_tensor = torch.tensor([total_affine_rel_depth, total_affine_delta1_depth, total_affine_rel_point, total_affine_delta1_point,+ float(num_valid_samples),+ total_si_boundary_f1, float(num_si_boundary_samples)],+ dtype=torch.float32, device='cuda')++ # 2. Barrier to ensure all processes are ready+ torch.distributed.barrier()++ # 3. All-Reduce (Sum) across all GPUs+ # This sums the error and the sample count from Rank 0, Rank 1, etc.+ dist.all_reduce(stats_tensor, op=dist.ReduceOp.SUM)++ # 4. Extract aggregated values (sum across all processes)+ global_affine_rel_depth_sum = stats_tensor[0].item()+ global_affine_delta1_depth_sum = stats_tensor[1].item()+ global_affine_rel_point_sum = stats_tensor[2].item()+ global_affine_delta1_point_sum = stats_tensor[3].item()+ global_num_valid_samples = int(stats_tensor[4].item())+ global_si_boundary_f1_sum = stats_tensor[5].item()+ global_num_si_boundary_samples = int(stats_tensor[6].item())+ else:+ global_affine_rel_depth_sum = total_affine_rel_depth+ global_affine_delta1_depth_sum = total_affine_delta1_depth+ global_affine_rel_point_sum = total_affine_rel_point+ global_affine_delta1_point_sum = total_affine_delta1_point++ global_num_valid_samples = num_valid_samples+ global_si_boundary_f1_sum = total_si_boundary_f1+ global_num_si_boundary_samples = num_si_boundary_samples++ if not args.eval_no_ema and getattr(model_without_ddp, 'ema_params1', None) is not None:+ # back to no ema+ print("Switch back from ema")+ model_without_ddp.load_state_dict(model_state_dict)++ # mean metrics+ # Use num_valid_samples instead of len(data_loader) to handle skipped samples+ num_samples_for_avg = max(1, global_num_valid_samples) # Avoid division by zero++ avg_affine_rel_depth = (global_affine_rel_depth_sum / num_samples_for_avg) * 100.+ avg_affine_delta1_depth = (global_affine_delta1_depth_sum / num_samples_for_avg) * 100.+ avg_affine_rel_point = (global_affine_rel_point_sum / num_samples_for_avg) * 100.+ avg_affine_delta1_point = (global_affine_delta1_point_sum / num_samples_for_avg) * 100.++ # Wild images carry no ground truth, so every average above is 0 by construction. They are+ # still computed because the tensorboard/wandb logging below reads them, but printing zeros+ # invites reading them as scores.+ if not args.eval_wild_images:+ print(f"Valid samples for metrics: {global_num_valid_samples} / {len(data_loader)}")+ print(f"affine_real_point: {avg_affine_rel_point:.3f}, affine_delta1_point: {avg_affine_delta1_point:.3f}")+ print(f"affine_real_depth: {avg_affine_rel_depth:.3f}, affine_delta1_depth: {avg_affine_delta1_depth:.3f}")++ # Global depth-range metrics (aggregate from per-dataset if distributed, else use local accumulators)+ if getattr(args, 'eval_depth_range_metrics', False):+ # Recompute global depth-range from per-dataset aggregated data if available+ if per_dataset_metrics:+ for b in depth_range_bins:+ depth_range_global[b] = {'total_rel_depth': 0., 'total_delta1_depth': 0., 'total_rel_point': 0., 'total_delta1_point': 0., 'count': 0}+ for ds_metrics in per_dataset_metrics.values():+ if 'depth_range' in ds_metrics:+ dr = ds_metrics['depth_range'][b]+ for k in ['total_rel_depth', 'total_delta1_depth', 'total_rel_point', 'total_delta1_point', 'count']:+ depth_range_global[b][k] += dr[k]+ has_global_dr = any(depth_range_global[b]['count'] > 0 for b in depth_range_bins)+ if has_global_dr:+ print("\n=== Global Depth-Range Metrics ===")+ for b in depth_range_bins:+ dr = depth_range_global[b]+ if dr['count'] > 0:+ n_dr = dr['count']+ print(f" [{b}] rel_depth: {dr['total_rel_depth']/n_dr*100:.3f}, "+ f"delta1_depth: {dr['total_delta1_depth']/n_dr*100:.3f}, "+ f"rel_point: {dr['total_rel_point']/n_dr*100:.3f}, "+ f"delta1_point: {dr['total_delta1_point']/n_dr*100:.3f} (n={n_dr})")+ print("=" * 50)++ # SI Boundary F1 metric+ if global_num_si_boundary_samples > 0:+ avg_si_boundary_f1 = (global_si_boundary_f1_sum / global_num_si_boundary_samples) * 100.+ print(f"si_boundary_f1: {avg_si_boundary_f1:.3f}")+ else:+ avg_si_boundary_f1 = 0.++ # Inference speed metrics+ if inference_sample_count > 0:+ avg_time_per_image = total_inference_time / inference_sample_count+ fps = inference_sample_count / total_inference_time+ print(f"Inference speed: {avg_time_per_image*1000:.2f} ms/image, {fps:.2f} FPS (total: {inference_sample_count} images in {total_inference_time:.2f}s)")++ if args.eval_wild_images:+ # No metrics to report, so close the run with something unambiguous instead.+ print("Done!")++ # Compute and print per-dataset metrics+ per_dataset_avg_metrics = {}+ if per_dataset_metrics:+ print("\n=== Per-Dataset Metrics ===")+ for dataset_name, metrics in per_dataset_metrics.items():+ num_samples = max(1, metrics['num_valid_samples'])+ avg_metrics = {+ 'affine_rel_depth': (metrics['total_affine_rel_depth'] / num_samples) * 100.,+ 'affine_delta1_depth': (metrics['total_affine_delta1_depth'] / num_samples) * 100.,+ 'affine_rel_point': (metrics['total_affine_rel_point'] / num_samples) * 100.,+ 'affine_delta1_point': (metrics['total_affine_delta1_point'] / num_samples) * 100.,+ 'num_samples': num_samples,+ }+ # Add SI boundary F1 if computed for this dataset+ if metrics['num_si_boundary_samples'] > 0:+ avg_metrics['si_boundary_f1'] = (metrics['total_si_boundary_f1'] / metrics['num_si_boundary_samples']) * 100.+ per_dataset_avg_metrics[dataset_name] = avg_metrics++ print(f"\n[{dataset_name}] (n={num_samples})")+ print(f" affine_rel_point: {avg_metrics['affine_rel_point']:.3f}, "+ f"affine_delta1_point: {avg_metrics['affine_delta1_point']:.3f}")+ print(f" affine_rel_depth: {avg_metrics['affine_rel_depth']:.3f}, "+ f"affine_delta1_depth: {avg_metrics['affine_delta1_depth']:.3f}")+ if 'si_boundary_f1' in avg_metrics:+ print(f" si_boundary_f1: {avg_metrics['si_boundary_f1']:.3f}")++ # Print depth-range breakdown for this dataset+ if 'depth_range' in metrics:+ has_depth_range = any(metrics['depth_range'][b]['count'] > 0 for b in depth_range_bins)+ if has_depth_range:+ print(f" Depth-range breakdown:")+ for b in depth_range_bins:+ dr = metrics['depth_range'][b]+ if dr['count'] > 0:+ n_dr = dr['count']+ print(f" [{b}] rel_depth: {dr['total_rel_depth']/n_dr*100:.3f}, "+ f"delta1_depth: {dr['total_delta1_depth']/n_dr*100:.3f}, "+ f"rel_point: {dr['total_rel_point']/n_dr*100:.3f}, "+ f"delta1_point: {dr['total_delta1_point']/n_dr*100:.3f} (n={n_dr})")+ print("=" * 50)++ # log with tensorboard+ if accelerator is not None:+ if accelerator.is_main_process and log_writer is not None:++ log_writer.add_scalar('test/affine_rel_depth', avg_affine_rel_depth, epoch)+ log_writer.add_scalar('test/affine_delta1_depth', avg_affine_delta1_depth, epoch)+ log_writer.add_scalar('test/affine_rel_point', avg_affine_rel_point, epoch)+ log_writer.add_scalar('test/affine_delta1_point', avg_affine_delta1_point, epoch)+ if global_num_si_boundary_samples > 0:+ log_writer.add_scalar('test/si_boundary_f1', avg_si_boundary_f1, epoch)++ # Add per-dataset metrics to tensorboard+ for dataset_name, avg_metrics in per_dataset_avg_metrics.items():+ log_writer.add_scalar(f'test/{dataset_name}/affine_rel_depth', avg_metrics['affine_rel_depth'], epoch)+ log_writer.add_scalar(f'test/{dataset_name}/affine_delta1_depth', avg_metrics['affine_delta1_depth'], epoch)+ log_writer.add_scalar(f'test/{dataset_name}/affine_rel_point', avg_metrics['affine_rel_point'], epoch)+ log_writer.add_scalar(f'test/{dataset_name}/affine_delta1_point', avg_metrics['affine_delta1_point'], epoch)+ if 'si_boundary_f1' in avg_metrics:+ log_writer.add_scalar(f'test/{dataset_name}/si_boundary_f1', avg_metrics['si_boundary_f1'], epoch)+ else:+ if misc.get_rank() == 0 and log_writer is not None:++ log_writer.add_scalar('test/affine_rel_depth', avg_affine_rel_depth, epoch)+ log_writer.add_scalar('test/affine_delta1_depth', avg_affine_delta1_depth, epoch)+ log_writer.add_scalar('test/affine_rel_point', avg_affine_rel_point, epoch)+ log_writer.add_scalar('test/affine_delta1_point', avg_affine_delta1_point, epoch)+ if global_num_si_boundary_samples > 0:+ log_writer.add_scalar('test/si_boundary_f1', avg_si_boundary_f1, epoch)++ # Add per-dataset metrics to tensorboard+ for dataset_name, avg_metrics in per_dataset_avg_metrics.items():+ log_writer.add_scalar(f'test/{dataset_name}/affine_rel_depth', avg_metrics['affine_rel_depth'], epoch)+ log_writer.add_scalar(f'test/{dataset_name}/affine_delta1_depth', avg_metrics['affine_delta1_depth'], epoch)+ log_writer.add_scalar(f'test/{dataset_name}/affine_rel_point', avg_metrics['affine_rel_point'], epoch)+ log_writer.add_scalar(f'test/{dataset_name}/affine_delta1_point', avg_metrics['affine_delta1_point'], epoch)+ if 'si_boundary_f1' in avg_metrics:+ log_writer.add_scalar(f'test/{dataset_name}/si_boundary_f1', avg_metrics['si_boundary_f1'], epoch)++ # log with wandb+ if accelerator is not None:+ if accelerator.is_main_process and args.wandb:++ val_logs['test_metric/affine_rel_depth'] = avg_affine_rel_depth+ val_logs['test_metric/affine_delta1_depth'] = avg_affine_delta1_depth+ val_logs['test_metric/affine_rel_point'] = avg_affine_rel_point+ val_logs['test_metric/affine_delta1_point'] = avg_affine_delta1_point++ # Add per-dataset metrics to wandb+ for dataset_name, avg_metrics in per_dataset_avg_metrics.items():+ val_logs[f'test_metric_{dataset_name}/affine_rel_depth'] = avg_metrics['affine_rel_depth']+ val_logs[f'test_metric_{dataset_name}/affine_delta1_depth'] = avg_metrics['affine_delta1_depth']+ val_logs[f'test_metric_{dataset_name}/affine_rel_point'] = avg_metrics['affine_rel_point']+ val_logs[f'test_metric_{dataset_name}/affine_delta1_point'] = avg_metrics['affine_delta1_point']++ wandb.log(val_logs)+ else:+ if misc.get_rank() == 0 and args.wandb:++ val_logs['test_metric/affine_rel_depth'] = avg_affine_rel_depth+ val_logs['test_metric/affine_delta1_depth'] = avg_affine_delta1_depth+ val_logs['test_metric/affine_rel_point'] = avg_affine_rel_point+ val_logs['test_metric/affine_delta1_point'] = avg_affine_delta1_point++ # Add per-dataset metrics to wandb+ for dataset_name, avg_metrics in per_dataset_avg_metrics.items():+ val_logs[f'test_metric_{dataset_name}/affine_rel_depth'] = avg_metrics['affine_rel_depth']+ val_logs[f'test_metric_{dataset_name}/affine_delta1_depth'] = avg_metrics['affine_delta1_depth']+ val_logs[f'test_metric_{dataset_name}/affine_rel_point'] = avg_metrics['affine_rel_point']+ val_logs[f'test_metric_{dataset_name}/affine_delta1_point'] = avg_metrics['affine_delta1_point']++ wandb.log(val_logs)++ if args.distributed:+ torch.distributed.barrier()++ returndiff --git a/loss.py b/loss.pynew file mode 100644index 0000000..af8fb8a--- /dev/null+++ b/loss.py@@ -0,0 +1,26 @@+# coding=utf-8++import torch+++def rel_point_loss(pred: torch.Tensor, gt: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:+ """+ Relative point loss - normalizes error by distance from origin.+ Directly optimizes rel_point_metric.++ Args:+ pred: Predicted points [B, 3, H, W] or [B, H, W, 3]+ gt: Ground truth points [B, 3, H, W] or [B, H, W, 3]+ eps: Small constant for numerical stability++ Returns:+ Loss tensor [B, H, W]+ """+ # Handle [B, 3, H, W] -> [B, H, W, 3]+ if pred.shape[1] == 3 and pred.dim() == 4:+ pred = pred.permute(0, 2, 3, 1)+ gt = gt.permute(0, 2, 3, 1)++ dist_gt = torch.norm(gt, dim=-1) # [B, H, W]+ dist_err = (pred - gt).abs().sum(dim=-1) # L1 norm+ return dist_err / (dist_gt + eps)diff --git a/main.py b/main.pynew file mode 100644index 0000000..05433de--- /dev/null+++ b/main.py@@ -0,0 +1,894 @@+# coding=utf-8++# Derived from JiT (https://github.com/LTH14/JiT), MIT License,+# Copyright (c) 2025 Tianhong Li. See THIRD_PARTY_NOTICES.+import argparse+import datetime+import numpy as np+import os+import time+from pathlib import Path+import sys++import torch+import torch.backends.cudnn as cudnn+from torch.utils.tensorboard import SummaryWriter++from accelerate import Accelerator+from datetime import timedelta+from accelerate import InitProcessGroupKwargs++import wandb+import signal++from util import misc++import copy+from engine import train_one_epoch, evaluate_img2point++from denoiser import Denoiser++from dataloader.img_depth_intrinsics import ImageDepthIntrinsicsDataset+from dataloader.eval_depth import EvalDepthDataset, MultiEvalDepthDataset, WildImagesDataset+from dataloader.mixed_dataset import MixedImageDepthIntrinsicsDataset++from util.paths import repo_path+from util.resize_posemb import (resize_patch_embed_and_final_layer,+ resize_vit_pos_embed)+++def get_args_parser():+ parser = argparse.ArgumentParser('PointDiT', add_help=False)++ # architecture+ parser.add_argument('--model', default='PointDiT-B/16', type=str, metavar='MODEL',+ help='Name of the model to train')+ parser.add_argument('--img_size', default=256, type=int, help='Image size')+ parser.add_argument('--attn_dropout', type=float, default=0.0, help='Attention dropout rate')+ parser.add_argument('--proj_dropout', type=float, default=0.0, help='Projection dropout rate')++ # training+ parser.add_argument('--epochs', default=200, type=int)+ parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N',+ help='Epochs to warm up LR')+ parser.add_argument('--batch_size', default=128, type=int,+ help='Batch size per GPU (effective batch size = batch_size * # GPUs)')+ parser.add_argument('--lr', type=float, default=None, metavar='LR',+ help='Learning rate (absolute)')+ parser.add_argument('--blr', type=float, default=5e-5, metavar='LR',+ help='Base learning rate: absolute_lr = base_lr * total_batch_size / 256')+ parser.add_argument('--min_lr', type=float, default=0., metavar='LR',+ help='Minimum LR for cyclic schedulers that hit 0')+ parser.add_argument('--lr_schedule', type=str, default='constant',+ help='Learning rate schedule')+ parser.add_argument('--weight_decay', type=float, default=0.0,+ help='Weight decay (default: 0.0)')+ parser.add_argument('--ema_decay1', type=float, default=0.9999,+ help='The first ema to track. Use the first ema for sampling by default.')+ parser.add_argument('--ema_decay2', type=float, default=0.9996,+ help='The second ema to track')+ parser.add_argument('--P_mean', default=-0.8, type=float)+ parser.add_argument('--P_std', default=0.8, type=float)+ parser.add_argument('--noise_scale', default=1.0, type=float)+ parser.add_argument('--generate_noise_scale', default=0.0, type=float,+ help='Scale of the Gaussian noise the sampler starts from. 0.0 (default) '+ 'starts from zeros, making inference deterministic.')+ parser.add_argument('--t_eps', default=5e-2, type=float)+ parser.add_argument('--sample_t_eps', default=0., type=float)++ parser.add_argument('--seed', default=0, type=int)+ parser.add_argument('--start_epoch', default=0, type=int, metavar='N',+ help='Starting epoch')+ parser.add_argument('--num_workers', default=16, type=int)+ parser.add_argument('--pin_mem', action='store_true',+ help='Pin CPU memory in DataLoader for faster GPU transfers')+ parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')+ parser.set_defaults(pin_mem=True)++ # sampling+ parser.add_argument('--num_sampling_steps', default=3, type=int,+ help='Number of ODE steps (released setting: 3)')+ parser.add_argument('--eval_freq', type=int, default=40,+ help='Frequency (in epochs) for evaluation')+ parser.add_argument('--online_eval', action='store_true')+ parser.add_argument('--evaluate_gen', action='store_true')+ parser.add_argument('--gen_bsz', type=int, default=1,+ help='Evaluation/inference batch size. Keep at 1: the eval dataloader uses '+ 'drop_last=True, so larger values silently discard the tail of each dataset.')++ # dataset+ parser.add_argument('--data_path', default=None, type=str,+ help='Root directory of a single training dataset. Ignored when '+ '--dataset_config is given (the YAML carries a data_path per dataset).')++ # checkpointing+ parser.add_argument('--output_dir', default='./output_dir',+ help='Directory to save outputs (empty for no saving)')+ parser.add_argument('--resume', action='store_true')+ parser.add_argument('--save_last_freq', type=int, default=1,+ help='Frequency (in epochs) to save checkpoints')+ parser.add_argument('--save_ckpt_freq', default=100, type=int)+ parser.add_argument('--save_last_steps', type=int, default=0,+ help='Save last checkpoint every N steps (0 to disable, use epoch-based saving)')+ parser.add_argument('--log_freq', default=100, type=int)+ parser.add_argument('--log_img_stride', default=10, type=int)+ parser.add_argument('--device', default='cuda',+ help='Device to use for training/testing')++ # distributed training+ parser.add_argument('--world_size', default=1, type=int,+ help='Number of distributed processes')+ parser.add_argument('--local_rank', default=0, type=int)+ parser.add_argument('--local-rank', default=0, type=int)+ parser.add_argument('--dist_on_itp', action='store_true')+ parser.add_argument('--dist_url', default='env://',+ help='URL used to set up distributed training')+ parser.add_argument('--distributed', action='store_true',+ help='Use distributed training')++ # new+ parser.add_argument('--task', default='img2point', type=str,+ choices=['img2point'],+ help='Kept for backwards compatibility with released checkpoints; '+ 'PointDiT only supports img2point.')+ parser.add_argument('--save_path_postfix', default=None, type=str)++ # resume from pretrained model, only the model, this is not resume training+ parser.add_argument('--pretrained', default=None, type=str)+ parser.add_argument('--no_strict_load', action='store_true')++ # data normalization+ parser.add_argument('--center_shift_point', action='store_true', default=True,+ help='Center each GT point map on the mean of its valid points (default: on)')+ parser.add_argument('--no_center_shift_point', action='store_false', dest='center_shift_point')+ parser.add_argument('--center_shift_z_only', action='store_true')+ parser.add_argument('--normalize_point_by_mean', action='store_true', default=True,+ help='Normalize point maps by the MEAN distance of the shifted points '+ '(default: on; off = median)')+ parser.add_argument('--no_normalize_point_by_mean', action='store_false', dest='normalize_point_by_mean')+ parser.add_argument('--compute_scale_factor_only_valid', action='store_true',+ help='Compute the normalization scale from valid points only. NOTE: ignored '+ 'when --dataset_config is used; set it per dataset in the YAML instead.')+ parser.add_argument('--compute_scale_factor_use_std', action='store_true')+ parser.add_argument('--compute_scale_factor_use_percentile', action='store_true')+ parser.add_argument('--remove_outliers', action='store_true')+ parser.add_argument('--outlier_threshold', default=3.0, type=float)+ parser.add_argument('--scale_factor_augment', action='store_true')+ parser.add_argument('--scale_factor_augment_min', default=0.8, type=float)+ parser.add_argument('--scale_factor_augment_max', default=1.2, type=float)+ parser.add_argument('--no_scale_factor', action='store_true')++ # ema+ parser.add_argument('--eval_no_ema', action='store_true')++ parser.add_argument('--num_overfit_samples', default=None, type=int)+ parser.add_argument('--num_dataset_duplicates', default=None, type=int)++ parser.add_argument('--force_zero_t', action='store_true', default=True,+ help='Rectified sampling: force a fraction of timesteps to exactly 0 during '+ 'training (default: on, fraction --force_zero_t_ratio)')+ parser.add_argument('--no_force_zero_t', action='store_false', dest='force_zero_t')+ parser.add_argument('--force_zero_t_ratio', default=None, type=float)+ # other datasets+ parser.add_argument('--train_subsample_scenes', default=None, type=int)+ parser.add_argument('--dataset_name', default=None, type=str)++ # multi-dataset config+ parser.add_argument('--dataset_config', default=None, type=str,+ help='Path to YAML config file for multi-dataset training')+ parser.add_argument('--dataset_weights', default=None, type=str,+ help='Comma-separated dataset weights to override config (e.g., "0.7,0.3" for 70%%/30%% split)')++ # depth intrinsics dataloader+ parser.add_argument('--depth_intrinsics_resize_height', default=None, type=int,+ help='Resize height before crop for depth intrinsics dataloader')++ # relative point loss (directly optimizes rel_point_metric)+ parser.add_argument('--rel_point_loss_weight', default=0.1, type=float,+ help='Weight of the relative point loss (normalized by distance from the '+ 'origin). 0.1 in all released models.')++ parser.add_argument('--noise_fill_invalid', action='store_true', help='Fill invalid regions with noise during training')++ parser.add_argument('--exclude_invalid_gt', action='store_true', default=True,+ help='Exclude invalid GT pixels from the loss (default: on)')+ parser.add_argument('--no_exclude_invalid_gt', action='store_false', dest='exclude_invalid_gt')++ # wandb+ parser.add_argument('--wandb', action='store_true')+ parser.add_argument('--resume_wandb_id', default=None, type=str,+ help='Resume logging into an existing W&B run id')+ parser.add_argument('--wandb_project', default='pointdit', type=str)+ parser.add_argument('--wandb_entity', default=None, type=str,+ help='W&B entity (team/user). Defaults to your configured default entity.')++ # network attention type+ parser.add_argument('--attention_type', default='torch', choices=['torch', 'flash3'], type=str,+ help="Attention kernel: 'torch' (default, scaled_dot_product_attention) "+ "or 'flash3' (needs flash-attn; used by the Stage-1 L and H runs). "+ "Same weights either way — this is only a kernel choice.")++ # gradient clipping+ parser.add_argument('--grad_clip', action='store_true', help='Use gradient clipping')++ # model design++ # feature embedding+ parser.add_argument('--feature_embedding_type', default='dinov3_vitb16', type=str,+ help='Frozen image encoder used for conditioning: '+ 'dinov3_{vits16,vits16plus,vitb16,vitl16,vith16plus,vit7b16}. '+ 'Must match --model: PointDiT-B/16 -> dinov3_vitb16, '+ 'PointDiT-L/16 -> dinov3_vitl16, '+ 'PointDiT-H/16 -> dinov3_vith16plus')+ parser.add_argument('--dinov3_use_intermediate_layers', action='store_true', default=True,+ help='Condition on --dinov3_num_intermediate_layers equally-spaced DINOv3 '+ 'layers instead of only the last one (default: on -- required to load '+ 'the released checkpoints)')+ parser.add_argument('--no_dinov3_intermediate_layers', action='store_false',+ dest='dinov3_use_intermediate_layers')+ parser.add_argument('--dinov3_num_intermediate_layers', type=int, default=4,+ help='Number of equally-spaced intermediate layers to extract from DINOv3')+ parser.add_argument('--feature_embedding_lr_scale', type=float, default=0.0,+ help='LR scale for feature embedding (0 = frozen, 0.1 = 10x smaller LR)')++ # misc+ parser.add_argument('--eval_no_save_gen', action='store_true', help='Do not save generated samples during evaluation')+ parser.add_argument('--gen_output_root', default=None, type=str,+ help='Root directory for evaluation/demo artifacts. Defaults to '+ '<repo>/generation, i.e. inside the PointDiT directory rather '+ 'than relative to the current working directory.')+ parser.add_argument('--resize_posemb', action='store_true', help='Resize positional embedding when loading pretrained weights')+ parser.add_argument('--resize_patch_embed', type=int, default=0, help='Original patch size to resize from (e.g., 16 when loading patch16 into patch32)')+ parser.add_argument('--persistent_workers', action='store_true', help='Use persistent workers in DataLoader')+ parser.add_argument('--dataloader_debug_timing', action='store_true', help='Print dataloader timing breakdown every 100 samples')+ parser.add_argument('--debug_train_steps', type=int, default=0, help='Exit training loop after N steps (0=disabled, for debugging)')++ # data augmentation+ parser.add_argument('--more_img_aug', action='store_true', default=True,+ help='Photometric image augmentation (default: on)')+ parser.add_argument('--no_more_img_aug', action='store_false', dest='more_img_aug')+ parser.add_argument('--stronger_img_aug', action='store_true', default=True,+ help='Stronger photometric augmentation (default: on)')+ parser.add_argument('--no_stronger_img_aug', action='store_false', dest='stronger_img_aug')++ parser.add_argument('--max_depth', default=10.0, type=float, help='Maximum depth value for depth normalization')+ parser.add_argument('--clamp_max_depth', default=None, type=float, help='Clamp maximum depth value to this value')+ parser.add_argument('--handle_sky', action='store_true', help='Handle sky regions specially in depth normalization for img2point task')++ # eval depth dataset (MoGe format)+ parser.add_argument('--eval_depth_dataset', action='store_true',+ help='Use EvalDepthDataset for evaluation (MoGe format)')+ parser.add_argument('--eval_depth_data_root', default='datasets/eval', type=str,+ help='Root directory holding the benchmark evaluation datasets')+ parser.add_argument('--eval_depth_dataset_name', default='NYUv2', type=str,+ help="Name(s) of eval depth dataset: a single name (e.g. NYUv2) or a "+ "comma-separated list. The paper's 7: "+ "DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster")+ parser.add_argument('--eval_depth_max_samples', default=None, type=int,+ help='Maximum number of samples per dataset to evaluate (for faster testing)')+ parser.add_argument('--eval_depth_resize_height', default=None, type=int,+ help='Resize shortest side to this height before crop. Useful for evaluating high-res images at lower resolution')+ parser.add_argument('--eval_depth_original_resolution', action='store_true',+ help='Evaluate at original resolution (resize input to nearest div-16, predict, resize back)')+ parser.add_argument('--eval_depth_max_resolution', default=1024, type=int,+ help='Max resolution for longer side in original_resolution mode (default: 1024)')+ parser.add_argument('--eval_depth_max_height', default=None, type=int,+ help='Max height for original resolution eval. If set with max_width, uses separate H/W constraints instead of max_resolution')+ parser.add_argument('--eval_depth_max_width', default=None, type=int,+ help='Max width for original resolution eval. If set with max_height, uses separate H/W constraints instead of max_resolution')+ parser.add_argument('--eval_save_per_sample_metrics', action='store_true',+ help='Save per-sample metrics to JSON file for method comparison')+ parser.add_argument('--eval_intermediate_boundary', action='store_true',+ help='Compute SI boundary F1 for each intermediate diffusion step (requires --eval_save_per_sample_metrics)')+ parser.add_argument('--eval_diode_split_indoor_outdoor', action='store_true',+ help='Split DIODE metrics into indoor and outdoor scenes (also keeps full DIODE metrics)')+ parser.add_argument('--eval_depth_range_metrics', action='store_true',+ help='Compute metrics stratified by depth range (near/mid/far based on GT depth percentiles)')+ parser.add_argument('--eval_boundary_datasets', default=None, type=str,+ help='Comma-separated list of dataset names to compute SI_boundary_F1 on (e.g., "NYUv2,KITTI")')+ parser.add_argument('--eval_num_tokens', default=0, type=int,+ help='Number of tokens for eval resizing (MoGe-style). 0 = use existing logic. '+ 'When > 0, resize input to match token count while preserving aspect ratio.')+ parser.add_argument('--resize_input_nearest_res', action='store_true',+ help='Resize input to nearest resolution divisible by 16 (round to nearest, not floor). '+ 'Optionally combined with --eval_num_tokens or --eval_min_tokens/--eval_max_tokens.')+ parser.add_argument('--eval_min_tokens', default=0, type=int,+ help='Minimum tokens for resize_input_nearest_res mode. 0 = no minimum.')+ parser.add_argument('--eval_max_tokens', default=0, type=int,+ help='Maximum tokens for resize_input_nearest_res mode. 0 = no maximum.')+ parser.add_argument('--sky_loss_weight', default=0.0, type=float, help='Weight for sky region loss if handle_sky is enabled')+ parser.add_argument('--use_sky_dome', action='store_true', help='Use sky dome information if available in img2point task')+ parser.add_argument('--sky_far_plane_value', default=3.0, type=float, help='Far plane value for sky regions when using sky dome')++ # remove sky at eval/inference (for models trained with --handle_sky)+ parser.add_argument('--remove_sky', action='store_true', default=True,+ help='Remove predicted sky points at eval/inference (default: on). Sky is detected on the '+ 'RAW model output (normalized space, before the radial-log inverse and scale/shift '+ 'alignment) by thresholding the per-point value against --remove_sky_threshold. Only '+ 'meaningful for models trained with sky handling (handle_sky, typically set per-dataset '+ 'in the dataset config), which places sky at norm ~sky_far_plane_value (default 3.0); '+ 'pass --no_remove_sky for models trained without it, such as the Stage-1 SceneNet '+ 'checkpoints. Affects saved point clouds and depth panels only, never the metrics.')+ parser.add_argument('--no_remove_sky', action='store_false', dest='remove_sky')+ parser.add_argument('--remove_sky_threshold', default=2.9, type=float,+ help='Threshold (in normalized model-output space) for sky removal. Points whose raw-output '+ 'value (see --remove_sky_metric) exceeds this are treated as sky and removed. Should be '+ 'slightly below --sky_far_plane_value (default 2.9 for far plane 3.0).')+ parser.add_argument('--remove_sky_metric', default='norm', type=str, choices=['norm', 'depth'],+ help="Quantity thresholded on the raw model output for sky removal: 'norm' = Euclidean "+ "distance from origin (default, robust for --use_sky_dome), 'depth' = z coordinate.")++ # dataset split+ parser.add_argument('--split', default=None, type=str,+ choices=['train', 'val', 'test', 'all'],+ help='Dataset split to use. "all" uses both train and val for training.')++ # save separate intermediate PLYs+ parser.add_argument('--remove_depth_edge', action='store_true', default=True,+ help='Remove noisy depth-edge pixels before saving PLY point clouds (default: on). '+ 'Affects saved point clouds only, never the metrics.')+ parser.add_argument('--no_remove_depth_edge', action='store_false', dest='remove_depth_edge')+ parser.add_argument('--depth_edge_rtol', type=float, default=0.04,+ help='Relative tolerance for depth edge detection (default: 0.04, matching MoGe)')+ parser.add_argument('--save_separate_intermediate_plys', action='store_true',+ help='Save intermediate diffusion steps as separate PLY files instead of combined')+ parser.add_argument('--save_separate_intermediate_depths', action='store_true',+ help='Save intermediate diffusion steps as separate depth PNG files')+ parser.add_argument('--save_resolution_in_filename', action='store_true',+ help='Append _HxW to saved input image filenames to highlight inference resolution')+ parser.add_argument('--save_raw_depth_npy', action='store_true',+ help='Save raw depth/pointcloud arrays as .npy files for cross-run comparison')+ parser.add_argument('--viz_unaligned_depth', action='store_true',+ help='Also visualize unaligned predicted depth on benchmark datasets (using shifted_depth normalization)')+ parser.add_argument('--depth_colormap', default='plasma', type=str,+ help='Matplotlib colormap for depth visualization (e.g. plasma, magma, inferno, turbo)')++ # Wild images inference (no ground truth)+ parser.add_argument('--eval_wild_images', action='store_true',+ help='Run inference on arbitrary images without ground truth (e.g. DA-2K)')+ parser.add_argument('--eval_wild_images_dir', default=None, type=str,+ help='Directory containing images for wild inference')+ parser.add_argument('--eval_wild_images_name', default=None, type=str,+ help='Name of the output subdirectory for wild inference. Defaults to the '+ 'folder name of --eval_wild_images_dir, so images in assets/demo land '+ 'in <generation>/<checkpoint>/demo/')+ parser.add_argument('--eval_wild_target_tokens', default=0, type=int,+ help='Token budget for full-frame wild inference. The whole image is '+ 'resized (aspect ratio preserved) to the patch-aligned resolution '+ 'whose token count is closest to this budget, the prediction runs '+ 'there, then it is resized back to the native resolution for saving. '+ '0 (the default) derives the budget from --img_size, so the model '+ 'sees the same number of tokens it was trained on. Pass '+ '--eval_depth_resize_height instead to use the legacy '+ 'resize-shortest-side-then-center-crop path.')++ return parser+++def main(args):+ # 1. Initialize Accelerator. Accelerate drives every run, single process or not, so the+ # device comes from it. cpu=True is how --device cpu still forces CPU on a GPU host;+ # otherwise the accelerator picks CUDA when it is available.+ kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=1800)) # 30 minutes+ accelerator = Accelerator(cpu=(args.device == 'cpu'), kwargs_handlers=[kwargs])+ device = accelerator.device+ global_rank = accelerator.process_index+ print = accelerator.print++ # remove_sky: thresholding the z coordinate ('depth') under-detects sky in sky-dome+ # mode, where sky is encoded as direction*sky_far_plane_value and z can be small at+ # the horizon. Only the Euclidean norm is reliable there.+ if getattr(args, 'remove_sky', False) and args.remove_sky_metric == 'depth' and args.use_sky_dome:+ print("[Warning] --remove_sky_metric depth is unreliable with --use_sky_dome "+ "(dome sky has small z near the horizon); using 'norm' instead.")+ args.remove_sky_metric = 'norm'++ # Set seeds for reproducibility+ seed = args.seed + global_rank+ torch.manual_seed(seed)+ np.random.seed(seed)++ cudnn.benchmark = True++ # Set up TensorBoard logging (only on main process)+ is_main_process = accelerator.is_main_process++ if is_main_process and args.output_dir is not None and not args.evaluate_gen:+ os.makedirs(args.output_dir, exist_ok=True)+ if args.wandb:+ # Authenticate beforehand with `wandb login` or the WANDB_API_KEY env var.+ wandb.login()++ def signal_handler(sig, frame):+ print('You pressed CTRL+C!')+ # Adjust exit code as needed+ wandb.finish(exit_code=255, quiet=True)+ # Additional cleanup here+ sys.exit(0)++ signal.signal(signal.SIGINT, signal_handler)++ wandb_extra_kwargs = {}++ if args.resume_wandb_id:+ wandb_extra_kwargs.update({+ 'id': args.resume_wandb_id,+ 'resume': 'must'+ })++ wandb.init(entity=args.wandb_entity,+ project=args.wandb_project,+ name=os.path.basename(args.output_dir),+ dir=args.output_dir,+ **wandb_extra_kwargs,+ )+ log_writer = None+ else:+ log_writer = SummaryWriter(log_dir=args.output_dir)+ else:+ log_writer = None++ # log slurm id to wandb+ if is_main_process and args.wandb:+ slurm_job_id = os.environ.get('SLURM_JOB_ID')+ if slurm_job_id is not None:+ print('slurm id:', slurm_job_id)++ if not args.evaluate_gen:+ print('Job directory:', os.path.dirname(os.path.realpath(__file__)))+ print("Arguments:\n{}".format(args).replace(', ', ',\n'))++ # train loader+ if not args.evaluate_gen:+ # skip train loader for evaluation only since data loading can be slow+ # TODO: maybe consider random hflip augmentation+ crop_size_for_dataset = args.img_size++ if args.dataset_config:+ # Use MixedImageDepthIntrinsicsDataset (multi-dataset training)+ print(f"Using MixedImageDepthIntrinsicsDataset with config: {args.dataset_config}")++ # Parse dataset weights if provided+ weight_overrides = None+ if args.dataset_weights:+ try:+ weight_overrides = [float(w.strip()) for w in args.dataset_weights.split(',')]+ print(f"Using CLI weight overrides: {weight_overrides}")+ except ValueError as e:+ raise ValueError(+ f"Invalid --dataset_weights format: '{args.dataset_weights}'. "+ f"Expected comma-separated floats (e.g., '0.7,0.3')"+ ) from e++ dataset_train = MixedImageDepthIntrinsicsDataset(+ config_path=args.dataset_config,+ split=args.split if args.split else 'train',+ crop_size=crop_size_for_dataset,+ center_shift=args.center_shift_point,+ center_shift_z_only=args.center_shift_z_only,+ normalize_by_mean=args.normalize_point_by_mean,+ num_overfit_samples=args.num_overfit_samples,+ num_dataset_duplicates=args.num_dataset_duplicates,+ subsample_scenes=args.train_subsample_scenes,+ more_img_aug=args.more_img_aug,+ stronger_img_aug=args.stronger_img_aug,+ debug_timing=args.dataloader_debug_timing,+ weight_overrides=weight_overrides,+ )+ else:+ # Use ImageDepthIntrinsicsDataset (single dataset, raw depth + intrinsics)+ print(f"Using ImageDepthIntrinsicsDataset for {args.dataset_name or 'scenenet'}")++ dataset_name = args.dataset_name or 'scenenet'++ dataset_train = ImageDepthIntrinsicsDataset(+ root_dir=args.data_path,+ dataset_name=dataset_name,+ split=args.split if args.split else 'train',+ num_test_scenes=None,+ test_scenes_file=None, # ImageDepthIntrinsicsDataset handles test split internally+ samples_per_scene=None,+ crop_size=crop_size_for_dataset,+ resize_height=args.depth_intrinsics_resize_height,+ center_shift=args.center_shift_point,+ center_shift_z_only=args.center_shift_z_only,+ normalize_by_mean=args.normalize_point_by_mean,+ num_overfit_samples=args.num_overfit_samples,+ num_dataset_duplicates=args.num_dataset_duplicates,+ max_depth=args.max_depth,+ subsample_scenes=args.train_subsample_scenes,+ more_img_aug=args.more_img_aug,+ stronger_img_aug=args.stronger_img_aug,+ compute_scale_factor_only_valid=args.compute_scale_factor_only_valid,+ compute_scale_factor_use_std=args.compute_scale_factor_use_std,+ compute_scale_factor_use_percentile=args.compute_scale_factor_use_percentile,+ clamp_max_depth=args.clamp_max_depth,+ handle_sky=args.handle_sky,+ use_sky_dome=args.use_sky_dome,+ sky_far_plane_value=args.sky_far_plane_value,+ debug_timing=args.dataloader_debug_timing,+ remove_outliers=args.remove_outliers,+ outlier_threshold=args.outlier_threshold,+ scale_factor_augment=args.scale_factor_augment,+ scale_factor_augment_range=(args.scale_factor_augment_min, args.scale_factor_augment_max),+ no_scale_factor=args.no_scale_factor,+ )++ print('Train samples:', len(dataset_train))++ # Check if we need WeightedRandomSampler (for mixed datasets)+ use_weighted_sampler = isinstance(dataset_train, MixedImageDepthIntrinsicsDataset)++ # Sampler is created by the accelerator+ # For mixed datasets, use WeightedRandomSampler+ if use_weighted_sampler:+ print("[MixedDataset] Using WeightedRandomSampler for dataset mixing")+ # Create weighted sampler+ sampler_train = dataset_train.create_weighted_sampler()+ shuffle = False # Don't shuffle when using custom sampler+ else:+ sampler_train = None+ shuffle = True++ data_loader_train = torch.utils.data.DataLoader(+ dataset_train,+ sampler=sampler_train,+ shuffle=shuffle if sampler_train is None else False,+ batch_size=args.batch_size,+ num_workers=args.num_workers,+ pin_memory=args.pin_mem,+ drop_last=True,+ persistent_workers=args.persistent_workers,+ prefetch_factor=4 if args.num_workers > 0 else None,+ )++ # test dataloader+ if args.online_eval or args.evaluate_gen:+ # Enforce batch_size=1 whenever inputs keep their native size, since images then+ # differ in size from one another and the default collate cannot stack them.+ use_original_res = getattr(args, 'eval_depth_original_resolution', False)+ wild_full_frame = args.eval_wild_images and args.eval_depth_resize_height is None+ if use_original_res or wild_full_frame:+ if args.batch_size != 1:+ cause = '--eval_depth_original_resolution' if use_original_res else 'full-frame wild inference'+ print(f"[Warning] {cause} requires batch_size=1, overriding batch_size={args.batch_size} to 1")+ args.batch_size = 1++ if args.eval_depth_dataset:+ # Use EvalDepthDataset for evaluation (MoGe format)+ # Parse dataset names (can be comma-separated)+ dataset_names = [name.strip() for name in args.eval_depth_dataset_name.split(',')]++ # Use None for crop_size and resize_height in original resolution mode+ use_original_res = getattr(args, 'eval_depth_original_resolution', False)+ eval_crop_size = None if use_original_res else args.img_size+ eval_resize_height = None if use_original_res else args.eval_depth_resize_height++ if len(dataset_names) == 1:+ # Single dataset+ dataset_test = EvalDepthDataset(+ data_root=args.eval_depth_data_root,+ dataset_name=dataset_names[0],+ crop_size=eval_crop_size,+ max_samples=args.eval_depth_max_samples,+ resize_height=eval_resize_height,+ )+ else:+ # Multiple datasets+ dataset_test = MultiEvalDepthDataset(+ data_root=args.eval_depth_data_root,+ dataset_names=dataset_names,+ crop_size=eval_crop_size,+ max_samples=args.eval_depth_max_samples,+ resize_height=eval_resize_height,+ )+ elif args.eval_wild_images:+ assert args.eval_wild_images_dir is not None, "--eval_wild_images_dir must be set when using --eval_wild_images"+ # Full frame by default: the dataset hands over the native image untouched and+ # the engine resizes it to the training token count, predicts, then resizes the+ # prediction back to native. --eval_depth_resize_height opts into the legacy+ # resize-shortest-side-then-center-crop path, which throws away everything+ # outside the central crop.+ if use_original_res or args.eval_depth_resize_height is None:+ eval_crop_size = None+ eval_resize_height = None+ else:+ eval_crop_size = args.img_size+ eval_resize_height = args.eval_depth_resize_height+ # Name the output subdirectory after the image folder, so the results are easy to+ # trace back to their input. normpath first, or a trailing slash yields ''.+ if args.eval_wild_images_name is None:+ args.eval_wild_images_name = os.path.basename(+ os.path.normpath(args.eval_wild_images_dir)) or 'wild'+ dataset_test = WildImagesDataset(+ images_dir=args.eval_wild_images_dir,+ dataset_name=args.eval_wild_images_name,+ crop_size=eval_crop_size,+ resize_height=eval_resize_height,+ max_samples=args.eval_depth_max_samples,+ )+ else:+ raise ValueError(+ 'Evaluation requires either --eval_depth_dataset (benchmark datasets in MoGe '+ 'format) or --eval_wild_images (inference on arbitrary images).'+ )++ print('Test dataset:', dataset_test)++ # Sampler is created by the accelerator+ data_loader_test = torch.utils.data.DataLoader(+ dataset_test,+ shuffle=False,+ batch_size=args.gen_bsz,+ num_workers=args.num_workers,+ pin_memory=args.pin_mem,+ drop_last=True,+ persistent_workers=args.persistent_workers,+ )+ else:+ data_loader_test = None++ torch._dynamo.config.cache_size_limit = 128+ torch._dynamo.config.optimize_ddp = False++ # Create denoiser (the PointDiT model)+ model = Denoiser(args)++ if accelerator.is_main_process and args.wandb:+ wandb.log({'model': print(model)})++ model.to(device)++ # Calculate effective batch size based on accelerator's count+ eff_batch_size = args.batch_size * accelerator.num_processes++ if args.lr is None: # only base_lr (blr) is specified+ args.lr = args.blr * eff_batch_size / 256++ if not args.evaluate_gen:+ print("Base lr: {:.2e}".format(args.lr * 256 / eff_batch_size))+ print("Actual lr: {:.2e}".format(args.lr))+ print("Effective batch size: %d" % eff_batch_size)++ # Prepare for distributed training+ param_groups = misc.add_weight_decay(model, args.weight_decay,+ feature_embedding_lr_scale=args.feature_embedding_lr_scale)+ optimizer = torch.optim.AdamW(param_groups, lr=args.lr, betas=(0.9, 0.95))+ if not args.evaluate_gen:+ print(optimizer)++ # This handles DDP wrapping and Sampler creation automatically+ if args.evaluate_gen:+ model, optimizer, data_loader_test = accelerator.prepare(+ model, optimizer, data_loader_test+ )+ else:+ model, optimizer, data_loader_train, data_loader_test = accelerator.prepare(+ model, optimizer, data_loader_train, data_loader_test+ )+ model_without_ddp = accelerator.unwrap_model(model)++ # Resume from checkpoint if provided+ # Wait for all processes to be ready+ accelerator.wait_for_everyone()++ # resume pretrained feature embedding+ if args.feature_embedding_type.startswith('dinov3'):+ vit_type = args.feature_embedding_type.split('_')[-1]+ assert vit_type in ['vits16', 'vits16plus', 'vitb16', 'vitl16', 'vith16plus', 'vit7b16'], f'ViT type {vit_type} not supported for DINOv3 feature embedding'++ # load pretrained DINOv3 weights+ sha_dict = {+ 'vits16': '08c60483',+ 'vits16plus': '4057cbaa',+ 'vitb16': '73cec8be',+ 'vitl16': '8aa4cbdd',+ 'vith16plus': '7c1da9a5',+ 'vit7b16': 'a955f4ea',+ }+ sha = sha_dict[vit_type]+ dinov3_weights_dir = os.environ.get(+ 'DINOV3_WEIGHTS_DIR', repo_path('pretrained/dinov3'))+ ckpt_path = os.path.join(+ dinov3_weights_dir, f'dinov3_{vit_type}_pretrain_lvd1689m-{sha}.pth')++ if os.path.exists(ckpt_path):+ ckpts = torch.load(ckpt_path, map_location='cpu')+ model_without_ddp.net.y_embedder.load_state_dict(ckpts, strict=True)+ print(f'Loaded pretrained DINOv3 {vit_type} from {ckpt_path}')+ elif args.pretrained is None:+ # With --pretrained the encoder arrives with the checkpoint (net.y_embedder.*),+ # loaded further below, so a missing gated file is normal and not worth a line of+ # output. Without one there is nothing else to initialise the encoder from, so the+ # run really would condition on a random encoder: say so.+ print(f'[DINOv3] {ckpt_path} not found -> encoder left randomly initialised. '+ f'Download the gated LVD-1689M weights to train from scratch.')++ else:+ raise NotImplementedError(f'Feature embedding type {args.feature_embedding_type} not supported')++ if not args.evaluate_gen:+ print(model)+ n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)+ print("Number of trainable parameters: {:.2f}M".format(n_params / 1e6))+ n_params_non_train = sum(p.numel() for p in model.parameters() if not p.requires_grad)+ print("Number of non-trainable parameters: {:.2f}M".format(n_params_non_train / 1e6))++ # Monotonic training step counter (persisted across resumes so logging and+ # sub-epoch checkpoint intervals stay continuous regardless of dataset length).+ global_step = 0++ checkpoint = None+ if args.resume:+ # Try the latest checkpoint, then the rolling backup. A corrupt/truncated+ # file (e.g. job killed mid-write) is skipped instead of crashing, and if+ # nothing loads we fall through to the --pretrained branch below.+ for cand in [os.path.join(args.output_dir, "checkpoint-last.pth"),+ os.path.join(args.output_dir, "checkpoint-last-prev.pth")]:+ if not os.path.exists(cand):+ continue+ try:+ checkpoint = torch.load(cand, map_location='cpu', weights_only=False)+ print("Resumed checkpoint from", cand)+ break+ except Exception as e:+ print(f"WARNING: failed to load {cand} ({e}); trying fallback")+ if checkpoint is None:+ print("No valid resume checkpoint; falling back to --pretrained / scratch")+ if checkpoint is not None:+ model_without_ddp.load_state_dict(checkpoint['model'])++ ema_state_dict1 = checkpoint['model_ema1']+ ema_state_dict2 = checkpoint['model_ema2']+ model_without_ddp.ema_params1 = [ema_state_dict1[name].to(device) for name, _ in model_without_ddp.named_parameters()]+ model_without_ddp.ema_params2 = [ema_state_dict2[name].to(device) for name, _ in model_without_ddp.named_parameters()]+ print("Resumed checkpoint from", args.output_dir)++ if 'optimizer' in checkpoint and 'epoch' in checkpoint:+ optimizer.load_state_dict(checkpoint['optimizer'])+ # Sub-epoch checkpoints store resume_epoch = in-progress epoch (re-run+ # it from the top); end-of-epoch checkpoints resume at epoch + 1.+ if checkpoint.get('resume_epoch') is not None:+ args.start_epoch = checkpoint['resume_epoch']+ else:+ args.start_epoch = checkpoint['epoch'] + 1+ if checkpoint.get('global_step') is not None:+ global_step = checkpoint['global_step']+ print("Loaded optimizer & scaler state! Resuming at epoch {}, global_step {}".format(+ args.start_epoch, global_step))+ del checkpoint+ elif args.pretrained:+ assert os.path.exists(args.pretrained)+ checkpoint = torch.load(args.pretrained, map_location='cpu', weights_only=False)++ # Slim checkpoints produced by tools/extract_ema.py carry a single weight set under+ # 'model' and no EMA copies. Skip all EMA handling for them so only one copy of the+ # parameters reaches the GPU (a full PointDiT-H checkpoint otherwise needs ~3x).+ has_ema = 'model_ema1' in checkpoint and 'model_ema2' in checkpoint++ if args.resize_posemb:+ # Update the checkpoint dict (key matches your error: 'net.pos_embed')+ patch_size = int(args.model.split('/')[-1])+ new_num_patches = (args.img_size // patch_size) ** 2+ ema_keys = ['model_ema1', 'model_ema2'] if has_ema else []+ for key in ['model'] + ema_keys:+ checkpoint[key] = resize_vit_pos_embed(checkpoint[key], new_num_patches=new_num_patches, key='net.pos_embed')++ # dino feature embedding pos emb+ if 'net.pos_embed_y' in checkpoint['model']:+ # for img2point task with separate pos embed for image and point tokens+ for key in ['model'] + ema_keys:+ checkpoint[key] = resize_vit_pos_embed(checkpoint[key], new_num_patches=new_num_patches, key='net.pos_embed_y')++ if args.resize_patch_embed > 0:+ new_patch_size = int(args.model.split('/')[-1])+ ema_keys = ['model_ema1', 'model_ema2'] if has_ema else []+ for key in ['model'] + ema_keys:+ checkpoint[key] = resize_patch_embed_and_final_layer(+ checkpoint[key], args.resize_patch_embed, new_patch_size, out_channels=3)++ model_without_ddp.load_state_dict(checkpoint['model'], strict=not args.no_strict_load)++ if args.evaluate_gen and 'epoch' in checkpoint:+ args.start_epoch = checkpoint['epoch']++ if not has_ema:+ # Nothing to restore: the weights in 'model' are already the ones we want to+ # evaluate. Leaving ema_params1/2 as None makes the engine skip the EMA swap.+ model_without_ddp.ema_params1 = None+ model_without_ddp.ema_params2 = None+ print('No EMA weights in checkpoint ({}); evaluating the "model" weights directly.'+ .format(checkpoint.get('extracted_from', 'slim checkpoint')))+ else:+ ema_params1 = copy.deepcopy(list(model_without_ddp.parameters()))+ ema_params2 = copy.deepcopy(list(model_without_ddp.parameters()))++ print('resume pretrained ema')+ ema_state_dict1 = checkpoint['model_ema1']+ ema_state_dict2 = checkpoint['model_ema2']++ # partial resume+ model_without_ddp.ema_params1 = []+ model_without_ddp.ema_params2 = []+ for i, (name, _ )in enumerate(model_without_ddp.named_parameters()):+ if name in ema_state_dict1:+ model_without_ddp.ema_params1.append(ema_state_dict1[name].to(device))+ else:+ model_without_ddp.ema_params1.append(ema_params1[i])++ if name in ema_state_dict2:+ model_without_ddp.ema_params2.append(ema_state_dict2[name].to(device))+ else:+ model_without_ddp.ema_params2.append(ema_params2[i])++ print('Load pretrained model from', args.pretrained)++ else:+ model_without_ddp.ema_params1 = copy.deepcopy(list(model_without_ddp.parameters()))+ model_without_ddp.ema_params2 = copy.deepcopy(list(model_without_ddp.parameters()))+ print("Training from scratch")++ # Barrier to ensure all processes have finished loading before starting training+ accelerator.wait_for_everyone()++ # Evaluate generation+ if args.evaluate_gen:+ with torch.random.fork_rng():+ torch.manual_seed(seed)+ with torch.no_grad():+ # no log to tb if eval only+ evaluate_img2point(model_without_ddp, args, 0, data_loader_test, log_writer=None)+ return++ # Training loop+ print(f"Start training for {args.epochs} epochs")+ start_time = time.time()+ for epoch in range(args.start_epoch, args.epochs):+ global_step = train_one_epoch(model, model_without_ddp, data_loader_train, optimizer, device, epoch, log_writer=log_writer, args=args, accelerator=accelerator, global_step=global_step)++ # Save checkpoint periodically+ if epoch % args.save_last_freq == 0 or epoch + 1 == args.epochs:++ accelerator.wait_for_everyone()++ misc.save_model(+ args=args,+ model_without_ddp=model_without_ddp,+ optimizer=optimizer,+ epoch=epoch,+ epoch_name="last",+ global_step=global_step+ )++ if epoch % args.save_ckpt_freq == 0 and epoch > 0:++ accelerator.wait_for_everyone()++ misc.save_model(+ args=args,+ model_without_ddp=model_without_ddp,+ optimizer=optimizer,+ epoch=epoch,+ global_step=global_step+ )++ # Perform online evaluation at specified intervals+ if args.online_eval and (epoch % args.eval_freq == 0 or epoch + 1 == args.epochs):+ torch.cuda.empty_cache()+ with torch.no_grad():+ evaluate_img2point(model_without_ddp, args, epoch, data_loader_test, log_writer=log_writer, accelerator=accelerator)+ torch.cuda.empty_cache()++ if accelerator.is_main_process and log_writer is not None:+ log_writer.flush()++ total_time = time.time() - start_time+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))+ print('Training time:', total_time_str)+++if __name__ == '__main__':+ args = get_args_parser().parse_args()++ Path(args.output_dir).mkdir(parents=True, exist_ok=True)+ main(args)diff --git a/metrics/alignment.py b/metrics/alignment.pynew file mode 100644index 0000000..1bf8fa0--- /dev/null+++ b/metrics/alignment.py@@ -0,0 +1,419 @@+# coding=utf-8++# Least-squares / least-absolute-deviations alignment of affine-invariant predictions.+# Adapted from MoGe (https://github.com/microsoft/MoGe), MIT License.+from typing import *+import math+from collections import namedtuple++import numpy as np+import torch+import torch.nn as nn+import torch.nn.functional as F+import torch.types+++def scatter_min(size: int, dim: int, index: torch.LongTensor, src: torch.Tensor) -> torch.return_types.min:+ "Scatter the minimum value along the given dimension of `input` into `src` at the indices specified in `index`."+ shape = src.shape[:dim] + (size,) + src.shape[dim + 1:]+ minimum = torch.full(shape, float('inf'), dtype=src.dtype, device=src.device).scatter_reduce(dim=dim, index=index, src=src, reduce='amin', include_self=False)+ minimum_where = torch.where(src == torch.gather(minimum, dim=dim, index=index))+ indices = torch.full(shape, -1, dtype=torch.long, device=src.device)+ indices[(*minimum_where[:dim], index[minimum_where], *minimum_where[dim + 1:])] = minimum_where[dim]+ return torch.return_types.min((minimum, indices))+++def split_batch_fwd(fn: Callable, chunk_size: int, *args, **kwargs):+ batch_size = next(x for x in (*args, *kwargs.values()) if isinstance(x, torch.Tensor)).shape[0]+ n_chunks = batch_size // chunk_size + (batch_size % chunk_size > 0)+ splited_args = tuple(arg.split(chunk_size, dim=0) if isinstance(arg, torch.Tensor) else [arg] * n_chunks for arg in args)+ splited_kwargs = {k: [v.split(chunk_size, dim=0) if isinstance(v, torch.Tensor) else [v] * n_chunks] for k, v in kwargs.items()}+ results = []+ for i in range(n_chunks):+ chunk_args = tuple(arg[i] for arg in splited_args)+ chunk_kwargs = {k: v[i] for k, v in splited_kwargs.items()}+ results.append(fn(*chunk_args, **chunk_kwargs))++ if isinstance(results[0], tuple):+ return tuple(torch.cat(r, dim=0) for r in zip(*results))+ else:+ return torch.cat(results, dim=0)+++def _pad_inf(x_: torch.Tensor):+ return torch.cat([torch.full_like(x_[..., :1], -torch.inf), x_, torch.full_like(x_[..., :1], torch.inf)], dim=-1)+++def _pad_cumsum(cumsum: torch.Tensor):+ return torch.cat([torch.zeros_like(cumsum[..., :1]), cumsum, cumsum[..., -1:]], dim=-1)+++def _compute_residual(a: torch.Tensor, xyw: torch.Tensor, trunc: float):+ return a.mul(xyw[..., 0]).sub_(xyw[..., 1]).abs_().mul_(xyw[..., 2]).clamp_max_(trunc).sum(dim=-1)+++def align(x: torch.Tensor, y: torch.Tensor, w: torch.Tensor, trunc: Optional[Union[float, torch.Tensor]] = None, eps: float = 1e-7) -> Tuple[torch.Tensor, torch.Tensor, torch.LongTensor]:+ """+ If trunc is None, solve `min sum_i w_i * |a * x_i - y_i|`, otherwise solve `min sum_i min(trunc, w_i * |a * x_i - y_i|)`.++ w_i must be >= 0.++ ### Parameters:+ - `x`: tensor of shape (..., n)+ - `y`: tensor of shape (..., n)+ - `w`: tensor of shape (..., n)+ - `trunc`: optional, float or tensor of shape (..., n) or None++ ### Returns:+ - `a`: tensor of shape (...), differentiable+ - `loss`: tensor of shape (...), value of loss function at `a`, detached+ - `index`: tensor of shape (...), where a = y[idx] / x[idx]+ """+ if trunc is None:+ x, y, w = torch.broadcast_tensors(x, y, w)+ sign = torch.sign(x)+ x, y = x * sign, y * sign+ y_div_x = y / x.clamp_min(eps)+ y_div_x, argsort = y_div_x.sort(dim=-1)++ wx = torch.gather(x * w, dim=-1, index=argsort)+ derivatives = 2 * wx.cumsum(dim=-1) - wx.sum(dim=-1, keepdim=True)+ search = torch.searchsorted(derivatives, torch.zeros_like(derivatives[..., :1]), side='left').clamp_max(derivatives.shape[-1] - 1)++ a = y_div_x.gather(dim=-1, index=search).squeeze(-1)+ index = argsort.gather(dim=-1, index=search).squeeze(-1)+ loss = (w * (a[..., None] * x - y).abs()).sum(dim=-1)++ else:+ # Reshape to (batch_size, n) for simplicity+ x, y, w = torch.broadcast_tensors(x, y, w)+ batch_shape = x.shape[:-1]+ batch_size = math.prod(batch_shape)+ x, y, w = x.reshape(-1, x.shape[-1]), y.reshape(-1, y.shape[-1]), w.reshape(-1, w.shape[-1])++ sign = torch.sign(x)+ x, y = x * sign, y * sign+ wx, wy = w * x, w * y+ xyw = torch.stack([x, y, w], dim=-1) # Stacked for convenient gathering++ y_div_x = A = y / x.clamp_min(eps)+ B = (wy - trunc) / wx.clamp_min(eps)+ C = (wy + trunc) / wx.clamp_min(eps)+ with torch.no_grad():+ # Caculate prefix sum by orders of A, B, C+ A, A_argsort = A.sort(dim=-1)+ Q_A = torch.cumsum(torch.gather(wx, dim=-1, index=A_argsort), dim=-1)+ A, Q_A = _pad_inf(A), _pad_cumsum(Q_A) # Pad [-inf, A1, ..., An, inf] and [0, Q1, ..., Qn, Qn] to handle edge cases.++ B, B_argsort = B.sort(dim=-1)+ Q_B = torch.cumsum(torch.gather(wx, dim=-1, index=B_argsort), dim=-1)+ B, Q_B = _pad_inf(B), _pad_cumsum(Q_B)++ C, C_argsort = C.sort(dim=-1)+ Q_C = torch.cumsum(torch.gather(wx, dim=-1, index=C_argsort), dim=-1)+ C, Q_C = _pad_inf(C), _pad_cumsum(Q_C)++ # Caculate left and right derivative of A+ j_A = torch.searchsorted(A, y_div_x, side='left').sub_(1)+ j_B = torch.searchsorted(B, y_div_x, side='left').sub_(1)+ j_C = torch.searchsorted(C, y_div_x, side='left').sub_(1)+ left_derivative = 2 * torch.gather(Q_A, dim=-1, index=j_A) - torch.gather(Q_B, dim=-1, index=j_B) - torch.gather(Q_C, dim=-1, index=j_C)+ j_A = torch.searchsorted(A, y_div_x, side='right').sub_(1)+ j_B = torch.searchsorted(B, y_div_x, side='right').sub_(1)+ j_C = torch.searchsorted(C, y_div_x, side='right').sub_(1)+ right_derivative = 2 * torch.gather(Q_A, dim=-1, index=j_A) - torch.gather(Q_B, dim=-1, index=j_B) - torch.gather(Q_C, dim=-1, index=j_C)++ # Find extrema+ is_extrema = (left_derivative < 0) & (right_derivative >= 0)+ is_extrema[..., 0] |= ~is_extrema.any(dim=-1) # In case all derivatives are zero, take the first one as extrema.+ where_extrema_batch, where_extrema_index = torch.where(is_extrema)++ # Calculate objective value at extrema+ extrema_a = y_div_x[where_extrema_batch, where_extrema_index] # (num_extrema,)+ MAX_ELEMENTS = 4096 ** 2 # Split into small batches to avoid OOM in case there are too many extrema.(~1G)+ SPLIT_SIZE = MAX_ELEMENTS // x.shape[-1]+ extrema_value = torch.cat([+ _compute_residual(extrema_a_split[:, None], xyw[extrema_i_split, :, :], trunc)+ for extrema_a_split, extrema_i_split in zip(extrema_a.split(SPLIT_SIZE), where_extrema_batch.split(SPLIT_SIZE))+ ]) # (num_extrema,)++ # Find minima among corresponding extrema+ minima, indices = scatter_min(size=batch_size, dim=0, index=where_extrema_batch, src=extrema_value) # (batch_size,)+ index = where_extrema_index[indices]++ a = torch.gather(y, dim=-1, index=index[..., None]) / torch.gather(x, dim=-1, index=index[..., None]).clamp_min(eps)+ a = a.reshape(batch_shape)+ loss = minima.reshape(batch_shape)+ index = index.reshape(batch_shape)++ return a, loss, index+++def align_depth_scale(depth_src: torch.Tensor, depth_tgt: torch.Tensor, weight: Optional[torch.Tensor], trunc: Optional[Union[float, torch.Tensor]] = None):+ """+ Align `depth_src` to `depth_tgt` with given constant weights.++ ### Parameters:+ - `depth_src: torch.Tensor` of shape (..., N)+ - `depth_tgt: torch.Tensor` of shape (..., N)++ """+ scale, _, _ = align(depth_src, depth_tgt, weight, trunc)++ return scale+++def align_depth_affine(depth_src: torch.Tensor, depth_tgt: torch.Tensor, weight: Optional[torch.Tensor], trunc: Optional[Union[float, torch.Tensor]] = None):+ """+ Align `depth_src` to `depth_tgt` with given constant weights.++ ### Parameters:+ - `depth_src: torch.Tensor` of shape (..., N)+ - `depth_tgt: torch.Tensor` of shape (..., N)+ - `weight: torch.Tensor` of shape (..., N)+ - `trunc: float` or tensor of shape (..., N) or None++ ### Returns:+ - `scale: torch.Tensor` of shape (...).+ - `shift: torch.Tensor` of shape (...).+ """+ dtype, device = depth_src.dtype, depth_src.device++ # Flatten batch dimensions for simplicity+ batch_shape, n = depth_src.shape[:-1], depth_src.shape[-1]+ batch_size = math.prod(batch_shape)+ depth_src, depth_tgt, weight = depth_src.reshape(batch_size, n), depth_tgt.reshape(batch_size, n), weight.reshape(batch_size, n)++ # Here, we take anchors only for non-zero weights.+ # Although the results will be still correct even anchor points have zero weight,+ # it is wasting computation and may cause instability in some cases, e.g. too many extrema.+ anchors_where_batch, anchors_where_n = torch.where(weight > 0)++ # Stop gradient when solving optimal anchors+ with torch.no_grad():+ depth_src_anchor = depth_src[anchors_where_batch, anchors_where_n] # (anchors)+ depth_tgt_anchor = depth_tgt[anchors_where_batch, anchors_where_n] # (anchors)++ depth_src_anchored = depth_src[anchors_where_batch, :] - depth_src_anchor[..., None] # (anchors, n)+ depth_tgt_anchored = depth_tgt[anchors_where_batch, :] - depth_tgt_anchor[..., None] # (anchors, n)+ weight_anchored = weight[anchors_where_batch, :] # (anchors, n)++ scale, loss, index = align(depth_src_anchored, depth_tgt_anchored, weight_anchored, trunc) # (anchors)++ loss, index_anchor = scatter_min(size=batch_size, dim=0, index=anchors_where_batch, src=loss) # (batch_size,)++ # Reproduce by indexing for shorter compute graph+ index_1 = anchors_where_n[index_anchor] # (batch_size,)+ index_2 = index[index_anchor] # (batch_size,)++ tgt_1, src_1 = torch.gather(depth_tgt, dim=1, index=index_1[..., None]).squeeze(-1), torch.gather(depth_src, dim=1, index=index_1[..., None]).squeeze(-1)+ tgt_2, src_2 = torch.gather(depth_tgt, dim=1, index=index_2[..., None]).squeeze(-1), torch.gather(depth_src, dim=1, index=index_2[..., None]).squeeze(-1)++ scale = (tgt_2 - tgt_1) / torch.where(src_2 != src_1, src_2 - src_1, 1e-7)+ shift = tgt_1 - scale * src_1++ scale, shift = scale.reshape(batch_shape), shift.reshape(batch_shape)++ return scale, shift++def align_depth_affine_irls(depth_src: torch.Tensor, depth_tgt: torch.Tensor, weight: Optional[torch.Tensor], max_iter: int = 100, eps: float = 1e-12):+ """+ Align `depth_src` to `depth_tgt` with given constant weights using IRLS.+ """+ dtype, device = depth_src.dtype, depth_src.device++ w = weight+ x = torch.stack([depth_src, torch.ones_like(depth_src)], dim=-1)+ y = depth_tgt++ for i in range(max_iter):+ beta = (x.transpose(-1, -2) @ (w * y)) @ (x.transpose(-1, -2) @ (w[..., None] * x)).inverse().transpose(-2, -1)+ w = 1 / (y - (x @ beta[..., None])[..., 0]).abs().clamp_min(eps)++ return beta[..., 0], beta[..., 1]+++def align_points_scale(points_src: torch.Tensor, points_tgt: torch.Tensor, weight: Optional[torch.Tensor], trunc: Optional[Union[float, torch.Tensor]] = None):+ """+ ### Parameters:+ - `points_src: torch.Tensor` of shape (..., N, 3)+ - `points_tgt: torch.Tensor` of shape (..., N, 3)+ - `weight: torch.Tensor` of shape (..., N)++ ### Returns:+ - `a: torch.Tensor` of shape (...). Only positive solutions are garunteed. You should filter out negative scales before using it.+ - `b: torch.Tensor` of shape (...)+ """+ dtype, device = points_src.dtype, points_src.device++ scale, _, _ = align(points_src.flatten(-2), points_tgt.flatten(-2), weight[..., None].expand_as(points_src).flatten(-2), trunc)++ return scale+++def align_points_scale_z_shift(points_src: torch.Tensor, points_tgt: torch.Tensor, weight: Optional[torch.Tensor], trunc: Optional[Union[float, torch.Tensor]] = None):+ """+ Align `points_src` to `points_tgt` with respect to a shared xyz scale and z shift.+ It is similar to `align_affine` but scale and shift are applied to different dimensions.++ ### Parameters:+ - `points_src: torch.Tensor` of shape (..., N, 3)+ - `points_tgt: torch.Tensor` of shape (..., N, 3)+ - `weights: torch.Tensor` of shape (..., N)++ ### Returns:+ - `scale: torch.Tensor` of shape (...).+ - `shift: torch.Tensor` of shape (..., 3). x and y shifts are zeros.+ """+ dtype, device = points_src.dtype, points_src.device++ # Flatten batch dimensions for simplicity+ batch_shape, n = points_src.shape[:-2], points_src.shape[-2]+ batch_size = math.prod(batch_shape)+ points_src, points_tgt, weight = points_src.reshape(batch_size, n, 3), points_tgt.reshape(batch_size, n, 3), weight.reshape(batch_size, n)++ # Take anchors+ anchor_where_batch, anchor_where_n = torch.where(weight > 0)+ with torch.no_grad():+ zeros = torch.zeros(anchor_where_batch.shape[0], device=device, dtype=dtype)+ points_src_anchor = torch.stack([zeros, zeros, points_src[anchor_where_batch, anchor_where_n, 2]], dim=-1) # (anchors, 3)+ points_tgt_anchor = torch.stack([zeros, zeros, points_tgt[anchor_where_batch, anchor_where_n, 2]], dim=-1) # (anchors, 3)++ points_src_anchored = points_src[anchor_where_batch, :, :] - points_src_anchor[..., None, :] # (anchors, n, 3)+ points_tgt_anchored = points_tgt[anchor_where_batch, :, :] - points_tgt_anchor[..., None, :] # (anchors, n, 3)+ weight_anchored = weight[anchor_where_batch, :, None].expand(-1, -1, 3) # (anchors, n, 3)++ # Solve optimal scale and shift for each anchor+ MAX_ELEMENTS = 2 ** 20+ scale, loss, index = split_batch_fwd(align, MAX_ELEMENTS // n, points_src_anchored.flatten(-2), points_tgt_anchored.flatten(-2), weight_anchored.flatten(-2), trunc) # (anchors,)++ loss, index_anchor = scatter_min(size=batch_size, dim=0, index=anchor_where_batch, src=loss) # (batch_size,)++ # Reproduce by indexing for shorter compute graph+ index_2 = index[index_anchor] # (batch_size,) [0, 3n)+ index_1 = anchor_where_n[index_anchor] * 3 + index_2 % 3 # (batch_size,) [0, 3n)++ zeros = torch.zeros((batch_size, n), device=device, dtype=dtype)+ points_tgt_00z, points_src_00z = torch.stack([zeros, zeros, points_tgt[..., 2]], dim=-1), torch.stack([zeros, zeros, points_src[..., 2]], dim=-1)+ tgt_1, src_1 = torch.gather(points_tgt_00z.flatten(-2), dim=1, index=index_1[..., None]).squeeze(-1), torch.gather(points_src_00z.flatten(-2), dim=1, index=index_1[..., None]).squeeze(-1)+ tgt_2, src_2 = torch.gather(points_tgt.flatten(-2), dim=1, index=index_2[..., None]).squeeze(-1), torch.gather(points_src.flatten(-2), dim=1, index=index_2[..., None]).squeeze(-1)++ scale = (tgt_2 - tgt_1) / torch.where(src_2 != src_1, src_2 - src_1, 1.0)+ shift = torch.gather(points_tgt_00z, dim=1, index=(index_1 // 3)[..., None, None].expand(-1, -1, 3)).squeeze(-2) - scale[..., None] * torch.gather(points_src_00z, dim=1, index=(index_1 // 3)[..., None, None].expand(-1, -1, 3)).squeeze(-2)+ scale, shift = scale.reshape(batch_shape), shift.reshape(*batch_shape, 3)++ return scale, shift+++def align_points_scale_xyz_shift(points_src: torch.Tensor, points_tgt: torch.Tensor, weight: Optional[torch.Tensor], trunc: Optional[Union[float, torch.Tensor]] = None, max_iters: int = 30, eps: float = 1e-6):+ """+ Align `points_src` to `points_tgt` with respect to a shared xyz scale and z shift.+ It is similar to `align_affine` but scale and shift are applied to different dimensions.++ ### Parameters:+ - `points_src: torch.Tensor` of shape (..., N, 3)+ - `points_tgt: torch.Tensor` of shape (..., N, 3)+ - `weights: torch.Tensor` of shape (..., N)++ ### Returns:+ - `scale: torch.Tensor` of shape (...).+ - `shift: torch.Tensor` of shape (..., 3)+ """+ dtype, device = points_src.dtype, points_src.device++ # Flatten batch dimensions for simplicity+ batch_shape, n = points_src.shape[:-2], points_src.shape[-2]+ batch_size = math.prod(batch_shape)+ points_src, points_tgt, weight = points_src.reshape(batch_size, n, 3), points_tgt.reshape(batch_size, n, 3), weight.reshape(batch_size, n)++ # Take anchors+ anchor_where_batch, anchor_where_n = torch.where(weight > 0)++ with torch.no_grad():+ points_src_anchor = points_src[anchor_where_batch, anchor_where_n] # (anchors, 3)+ points_tgt_anchor = points_tgt[anchor_where_batch, anchor_where_n] # (anchors, 3)++ points_src_anchored = points_src[anchor_where_batch, :, :] - points_src_anchor[..., None, :] # (anchors, n, 3)+ points_tgt_anchored = points_tgt[anchor_where_batch, :, :] - points_tgt_anchor[..., None, :] # (anchors, n, 3)+ weight_anchored = weight[anchor_where_batch, :, None].expand(-1, -1, 3) # (anchors, n, 3)++ # Solve optimal scale and shift for each anchor+ MAX_ELEMENTS = 2 ** 20+ scale, loss, index = split_batch_fwd(align, MAX_ELEMENTS // 2, points_src_anchored.flatten(-2), points_tgt_anchored.flatten(-2), weight_anchored.flatten(-2), trunc) # (anchors,)++ # Get optimal scale and shift for each batch element+ loss, index_anchor = scatter_min(size=batch_size, dim=0, index=anchor_where_batch, src=loss) # (batch_size,)++ index_2 = index[index_anchor] # (batch_size,) [0, 3n)+ index_1 = anchor_where_n[index_anchor] * 3 + index_2 % 3 # (batch_size,) [0, 3n)++ src_1, tgt_1 = torch.gather(points_src.flatten(-2), dim=1, index=index_1[..., None]).squeeze(-1), torch.gather(points_tgt.flatten(-2), dim=1, index=index_1[..., None]).squeeze(-1)+ src_2, tgt_2 = torch.gather(points_src.flatten(-2), dim=1, index=index_2[..., None]).squeeze(-1), torch.gather(points_tgt.flatten(-2), dim=1, index=index_2[..., None]).squeeze(-1)++ scale = (tgt_2 - tgt_1) / torch.where(src_2 != src_1, src_2 - src_1, 1.0)+ shift = torch.gather(points_tgt, dim=1, index=(index_1 // 3)[..., None, None].expand(-1, -1, 3)).squeeze(-2) - scale[..., None] * torch.gather(points_src, dim=1, index=(index_1 // 3)[..., None, None].expand(-1, -1, 3)).squeeze(-2)++ scale, shift = scale.reshape(batch_shape), shift.reshape(*batch_shape, 3)++ return scale, shift+++def align_points_z_shift(points_src: torch.Tensor, points_tgt: torch.Tensor, weight: Optional[torch.Tensor], trunc: Optional[Union[float, torch.Tensor]] = None, max_iters: int = 30, eps: float = 1e-6):+ """+ Align `points_src` to `points_tgt` with respect to a Z-axis shift.++ ### Parameters:+ - `points_src: torch.Tensor` of shape (..., N, 3)+ - `points_tgt: torch.Tensor` of shape (..., N, 3)+ - `weights: torch.Tensor` of shape (..., N)++ ### Returns:+ - `scale: torch.Tensor` of shape (...).+ - `shift: torch.Tensor` of shape (..., 3)+ """+ dtype, device = points_src.dtype, points_src.device++ shift, _, _ = align(torch.ones_like(points_src[..., 2]), points_tgt[..., 2] - points_src[..., 2], weight, trunc)+ shift = torch.stack([torch.zeros_like(shift), torch.zeros_like(shift), shift], dim=-1)++ return shift+++def align_points_xyz_shift(points_src: torch.Tensor, points_tgt: torch.Tensor, weight: Optional[torch.Tensor], trunc: Optional[Union[float, torch.Tensor]] = None, max_iters: int = 30, eps: float = 1e-6):+ """+ Align `points_src` to `points_tgt` with respect to a Z-axis shift.++ ### Parameters:+ - `points_src: torch.Tensor` of shape (..., N, 3)+ - `points_tgt: torch.Tensor` of shape (..., N, 3)+ - `weights: torch.Tensor` of shape (..., N)++ ### Returns:+ - `scale: torch.Tensor` of shape (...).+ - `shift: torch.Tensor` of shape (..., 3)+ """+ dtype, device = points_src.dtype, points_src.device++ shift, _, _ = align(torch.ones_like(points_src).swapaxes(-2, -1), (points_tgt - points_src).swapaxes(-2, -1), weight[..., None, :], trunc)++ return shift+++def align_affine_lstsq(x: torch.Tensor, y: torch.Tensor, w: torch.Tensor = None) -> Tuple[torch.Tensor, torch.Tensor]:+ """+ Solve `min sum_i w_i * (a * x_i + b - y_i ) ^ 2`, where `a` and `b` are scalars, with respect to `a` and `b` using least squares.++ ### Parameters:+ - `x: torch.Tensor` of shape (..., N)+ - `y: torch.Tensor` of shape (..., N)+ - `w: torch.Tensor` of shape (..., N)++ ### Returns:+ - `a: torch.Tensor` of shape (...,)+ - `b: torch.Tensor` of shape (...,)+ """+ w_sqrt = torch.ones_like(x) if w is None else w.sqrt()+ A = torch.stack([w_sqrt * x, torch.ones_like(x)], dim=-1)+ B = (w_sqrt * y)[..., None]+ a, b = torch.linalg.lstsq(A, B)[0].squeeze(-1).unbind(-1)+ return a, bdiff --git a/metrics/boundary_metrics.py b/metrics/boundary_metrics.pynew file mode 100644index 0000000..ab551a1--- /dev/null+++ b/metrics/boundary_metrics.py@@ -0,0 +1,336 @@+# coding=utf-8++# Scale-invariant boundary F1 (edge sharpness).+# Adapted from Depth Pro (https://github.com/apple/ml-depth-pro), Apple sample code License.+from typing import List, Tuple++import numpy as np+++def connected_component(r: np.ndarray, c: np.ndarray) -> List[List[int]]:+ """Find connected components in the given row and column indices.++ Args:+ ----+ r (np.ndarray): Row indices.+ c (np.ndarray): Column indices.++ Yields:+ ------+ List[int]: Indices of connected components.++ """+ indices = [0]+ for i in range(1, r.size):+ if r[i] == r[indices[-1]] and c[i] == c[indices[-1]] + 1:+ indices.append(i)+ else:+ yield indices+ indices = [i]+ yield indices+++def nms_horizontal(ratio: np.ndarray, threshold: float) -> np.ndarray:+ """Apply Non-Maximum Suppression (NMS) horizontally on the given ratio matrix.++ Args:+ ----+ ratio (np.ndarray): Input ratio matrix.+ threshold (float): Threshold for NMS.++ Returns:+ -------+ np.ndarray: Binary mask after applying NMS.++ """+ mask = np.zeros_like(ratio, dtype=bool)+ r, c = np.nonzero(ratio > threshold)+ if len(r) == 0:+ return mask+ for ids in connected_component(r, c):+ values = [ratio[r[i], c[i]] for i in ids]+ mi = np.argmax(values)+ mask[r[ids[mi]], c[ids[mi]]] = True+ return mask+++def nms_vertical(ratio: np.ndarray, threshold: float) -> np.ndarray:+ """Apply Non-Maximum Suppression (NMS) vertically on the given ratio matrix.++ Args:+ ----+ ratio (np.ndarray): Input ratio matrix.+ threshold (float): Threshold for NMS.++ Returns:+ -------+ np.ndarray: Binary mask after applying NMS.++ """+ return np.transpose(nms_horizontal(np.transpose(ratio), threshold))+++def fgbg_depth(+ d: np.ndarray, t: float+) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:+ """Find foreground-background relations between neighboring pixels.++ Args:+ ----+ d (np.ndarray): Depth matrix.+ t (float): Threshold for comparison.++ Returns:+ -------+ Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating+ left, top, right, and bottom foreground-background relations.++ """+ right_is_big_enough = (d[..., :, 1:] / d[..., :, :-1]) > t+ left_is_big_enough = (d[..., :, :-1] / d[..., :, 1:]) > t+ bottom_is_big_enough = (d[..., 1:, :] / d[..., :-1, :]) > t+ top_is_big_enough = (d[..., :-1, :] / d[..., 1:, :]) > t+ return (+ left_is_big_enough,+ top_is_big_enough,+ right_is_big_enough,+ bottom_is_big_enough,+ )+++def fgbg_depth_thinned(+ d: np.ndarray, t: float+) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:+ """Find foreground-background relations between neighboring pixels with Non-Maximum Suppression.++ Args:+ ----+ d (np.ndarray): Depth matrix.+ t (float): Threshold for NMS.++ Returns:+ -------+ Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating+ left, top, right, and bottom foreground-background relations with NMS applied.++ """+ right_is_big_enough = nms_horizontal(d[..., :, 1:] / d[..., :, :-1], t)+ left_is_big_enough = nms_horizontal(d[..., :, :-1] / d[..., :, 1:], t)+ bottom_is_big_enough = nms_vertical(d[..., 1:, :] / d[..., :-1, :], t)+ top_is_big_enough = nms_vertical(d[..., :-1, :] / d[..., 1:, :], t)+ return (+ left_is_big_enough,+ top_is_big_enough,+ right_is_big_enough,+ bottom_is_big_enough,+ )+++def fgbg_binary_mask(+ d: np.ndarray,+) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:+ """Find foreground-background relations between neighboring pixels in binary masks.++ Args:+ ----+ d (np.ndarray): Binary depth matrix.++ Returns:+ -------+ Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating+ left, top, right, and bottom foreground-background relations in binary masks.++ """+ assert d.dtype == bool+ right_is_big_enough = d[..., :, 1:] & ~d[..., :, :-1]+ left_is_big_enough = d[..., :, :-1] & ~d[..., :, 1:]+ bottom_is_big_enough = d[..., 1:, :] & ~d[..., :-1, :]+ top_is_big_enough = d[..., :-1, :] & ~d[..., 1:, :]+ return (+ left_is_big_enough,+ top_is_big_enough,+ right_is_big_enough,+ bottom_is_big_enough,+ )+++def edge_recall_matting(pr: np.ndarray, gt: np.ndarray, t: float) -> float:+ """Calculate edge recall for image matting.++ Args:+ ----+ pr (np.ndarray): Predicted depth matrix.+ gt (np.ndarray): Ground truth binary mask.+ t (float): Threshold for NMS.++ Returns:+ -------+ float: Edge recall value.++ """+ assert gt.dtype == bool+ ap, bp, cp, dp = fgbg_depth_thinned(pr, t)+ ag, bg, cg, dg = fgbg_binary_mask(gt)+ return 0.25 * (+ np.count_nonzero(ap & ag) / max(np.count_nonzero(ag), 1)+ + np.count_nonzero(bp & bg) / max(np.count_nonzero(bg), 1)+ + np.count_nonzero(cp & cg) / max(np.count_nonzero(cg), 1)+ + np.count_nonzero(dp & dg) / max(np.count_nonzero(dg), 1)+ )+++def boundary_f1(+ pr: np.ndarray,+ gt: np.ndarray,+ t: float,+ return_p: bool = False,+ return_r: bool = False,+) -> float:+ """Calculate Boundary F1 score.++ Args:+ ----+ pr (np.ndarray): Predicted depth matrix.+ gt (np.ndarray): Ground truth depth matrix.+ t (float): Threshold for comparison.+ return_p (bool, optional): If True, return precision. Defaults to False.+ return_r (bool, optional): If True, return recall. Defaults to False.++ Returns:+ -------+ float: Boundary F1 score, or precision, or recall depending on the flags.++ """+ ap, bp, cp, dp = fgbg_depth(pr, t)+ ag, bg, cg, dg = fgbg_depth(gt, t)++ r = 0.25 * (+ np.count_nonzero(ap & ag) / max(np.count_nonzero(ag), 1)+ + np.count_nonzero(bp & bg) / max(np.count_nonzero(bg), 1)+ + np.count_nonzero(cp & cg) / max(np.count_nonzero(cg), 1)+ + np.count_nonzero(dp & dg) / max(np.count_nonzero(dg), 1)+ )+ p = 0.25 * (+ np.count_nonzero(ap & ag) / max(np.count_nonzero(ap), 1)+ + np.count_nonzero(bp & bg) / max(np.count_nonzero(bp), 1)+ + np.count_nonzero(cp & cg) / max(np.count_nonzero(cp), 1)+ + np.count_nonzero(dp & dg) / max(np.count_nonzero(dp), 1)+ )+ if r + p == 0:+ return 0.0+ if return_p:+ return p+ if return_r:+ return r+ return 2 * (r * p) / (r + p)+++def get_thresholds_and_weights(+ t_min: float, t_max: float, N: int+) -> Tuple[np.ndarray, np.ndarray]:+ """Generate thresholds and weights for the given range.++ Args:+ ----+ t_min (float): Minimum threshold.+ t_max (float): Maximum threshold.+ N (int): Number of thresholds.++ Returns:+ -------+ Tuple[np.ndarray, np.ndarray]: Array of thresholds and corresponding weights.++ """+ thresholds = np.linspace(t_min, t_max, N)+ weights = thresholds / thresholds.sum()+ return thresholds, weights+++def invert_depth(depth: np.ndarray, eps: float = 1e-6) -> np.ndarray:+ """Inverts a depth map with numerical stability.++ Args:+ ----+ depth (np.ndarray): Depth map to be inverted.+ eps (float): Minimum value to avoid division by zero (default is 1e-6).++ Returns:+ -------+ np.ndarray: Inverted depth map.++ """+ inverse_depth = 1.0 / depth.clip(min=eps)+ return inverse_depth+++def SI_boundary_F1(+ predicted_depth: np.ndarray,+ target_depth: np.ndarray,+ t_min: float = 1.05,+ t_max: float = 1.25,+ N: int = 10,+) -> float:+ """Calculate Scale-Invariant Boundary F1 Score for depth-based ground-truth.++ Args:+ ----+ predicted_depth (np.ndarray): Predicted depth matrix.+ target_depth (np.ndarray): Ground truth depth matrix.+ t_min (float, optional): Minimum threshold. Defaults to 1.05.+ t_max (float, optional): Maximum threshold. Defaults to 1.25.+ N (int, optional): Number of thresholds. Defaults to 10.++ Returns:+ -------+ float: Scale-Invariant Boundary F1 Score.++ """+ assert predicted_depth.ndim == target_depth.ndim == 2+ thresholds, weights = get_thresholds_and_weights(t_min, t_max, N)+ f1_scores = np.array(+ [+ boundary_f1(invert_depth(predicted_depth), invert_depth(target_depth), t)+ for t in thresholds+ ]+ )+ return np.sum(f1_scores * weights)+++def SI_boundary_Recall(+ predicted_depth: np.ndarray,+ target_mask: np.ndarray,+ t_min: float = 1.05,+ t_max: float = 1.25,+ N: int = 10,+ alpha_threshold: float = 0.1,+) -> float:+ """Calculate Scale-Invariant Boundary Recall Score for mask-based ground-truth.++ Args:+ ----+ predicted_depth (np.ndarray): Predicted depth matrix.+ target_mask (np.ndarray): Ground truth binary mask.+ t_min (float, optional): Minimum threshold. Defaults to 1.05.+ t_max (float, optional): Maximum threshold. Defaults to 1.25.+ N (int, optional): Number of thresholds. Defaults to 10.+ alpha_threshold (float, optional): Threshold for alpha masking. Defaults to 0.1.++ Returns:+ -------+ float: Scale-Invariant Boundary Recall Score.++ """+ assert predicted_depth.ndim == target_mask.ndim == 2+ thresholds, weights = get_thresholds_and_weights(t_min, t_max, N)+ thresholded_target = target_mask > alpha_threshold++ recall_scores = np.array(+ [+ edge_recall_matting(+ invert_depth(predicted_depth), thresholded_target, t=float(t)+ )+ for t in thresholds+ ]+ )+ weighted_recall = np.sum(recall_scores * weights)+ return weighted_recalldiff --git a/metrics/compute_metrics.py b/metrics/compute_metrics.pynew file mode 100644index 0000000..ffe49f1--- /dev/null+++ b/metrics/compute_metrics.py@@ -0,0 +1,394 @@+# coding=utf-8++# The evaluation metric suite (affine-invariant point-map and depth metrics).+# Adapted from MoGe (https://github.com/microsoft/MoGe), MIT License.+from typing import *+from numbers import Number++import torch+import torch.nn.functional as F+import numpy as np+++from metrics.alignment import (+ align_points_scale_z_shift,+ align_points_scale_xyz_shift,+ align_points_xyz_shift,+ align_affine_lstsq,+ align_depth_scale,+ align_depth_affine,+ align_points_scale,+)+++from metrics.masked_resize import masked_nearest_resize++from metrics.metrics import (+ rel_depth,+ delta1_depth,+ rel_point,+ delta1_point,+ rel_point_local,+ delta1_point_local,+ boundary_f1,+)++from metrics.boundary_metrics import SI_boundary_F1+++DEPTH_RANGE_BINS = {'near': (0.0, 1/3), 'medium': (1/3, 2/3), 'far': (2/3, 1.0)}+++def compute_depth_range_metrics(pred_depth, gt_depth, pred_points, gt_points, mask):+ """Compute metrics stratified by GT depth percentile ranges (near/mid/far)."""+ gt_depth_valid = gt_depth[mask]+ if gt_depth_valid.numel() < 30:+ return {}++ sorted_depths = gt_depth_valid.sort().values+ n = sorted_depths.shape[0]++ range_metrics = {}+ for bin_name, (lo_pct, hi_pct) in DEPTH_RANGE_BINS.items():+ lo_val = sorted_depths[int(lo_pct * (n - 1))]+ hi_val = sorted_depths[min(int(hi_pct * (n - 1)), n - 1)]+ if hi_pct >= 1.0:+ hi_val = sorted_depths[-1] + 1e-6++ bin_mask = mask & (gt_depth >= lo_val) & (gt_depth < hi_val)+ if bin_mask.sum() < 10:+ continue++ bin_metrics = {+ 'rel_depth': rel_depth(pred_depth[bin_mask], gt_depth[bin_mask]),+ 'delta1_depth': delta1_depth(pred_depth[bin_mask], gt_depth[bin_mask]),+ }+ if pred_points is not None and gt_points is not None:+ bin_metrics['rel_point'] = rel_point(pred_points[bin_mask], gt_points[bin_mask])+ bin_metrics['delta1_point'] = delta1_point(pred_points[bin_mask], gt_points[bin_mask])+ range_metrics[bin_name] = bin_metrics++ return range_metrics+++def compute_metrics(+ pred: Dict[str, torch.Tensor],+ gt: Dict[str, torch.Tensor],+ vis: bool = False,+ compute_si_boundary: bool = False,+ compute_depth_range: bool = False,+) -> Tuple[Dict[str, Dict[str, Number]], Dict[str, torch.Tensor]]:+ """+ A unified function to compute metrics for different types of predictions and ground truths.++ #### Supported keys in pred:+ - `disparity_affine_invariant`: disparity map predicted by a depth estimator with scale and shift invariant.+ - `depth_scale_invariant`: depth map predicted by a depth estimator with scale invariant.+ - `depth_affine_invariant`: depth map predicted by a depth estimator with scale and shift invariant.+ - `depth_metric`: depth map predicted by a depth estimator with no scale or shift.+ - `points_scale_invariant`: point map predicted by a point estimator with scale invariant.+ - `points_affine_invariant`: point map predicted by a point estimator with scale and xyz shift invariant.+ - `points_metric`: point map predicted by a point estimator with no scale or shift.+ - `intrinsics`: normalized camera intrinsics matrix.++ #### Required keys in gt:+ - `depth`: depth map ground truth (in metric units if `depth_metric` is used)+ - `points`: point map ground truth in camera coordinates.+ - `mask`: mask indicating valid pixels in the ground truth.+ - `intrinsics`: normalized ground-truth camera intrinsics matrix.+ - `is_metric`: whether the depth is in metric units.+ """+ metrics = {}+ misc = {}++ mask = gt['depth_mask']+ gt_depth = gt['depth']+ gt_points = gt['points']++ height, width = mask.shape[-2:]+ lr_mask, lr_index = masked_nearest_resize(mask=mask, size=(64, 64), return_index=True)++ only_depth = not any('point' in k for k in pred)+ pred_depth_aligned, pred_points_aligned = None, None+ affine_points_scale, affine_points_shift = None, None++ # Metric depth+ if 'depth_metric' in pred and 'is_metric' in gt and gt['is_metric']:+ pred_depth, gt_depth = pred['depth_metric'], gt['depth']+ metrics['depth_metric'] = {+ 'rel': rel_depth(pred_depth[mask], gt_depth[mask]),+ 'delta1': delta1_depth(pred_depth[mask], gt_depth[mask])+ }++ if pred_depth_aligned is None:+ pred_depth_aligned = pred_depth++ # Scale-invariant depth+ if 'depth_scale_invariant' in pred:+ pred_depth_scale_invariant = pred['depth_scale_invariant']+ elif 'depth_metric' in pred:+ pred_depth_scale_invariant = pred['depth_metric']+ else:+ pred_depth_scale_invariant = None++ if pred_depth_scale_invariant is not None:+ pred_depth = pred_depth_scale_invariant++ pred_depth_lr_masked, gt_depth_lr_masked = pred_depth[lr_index][lr_mask], gt_depth[lr_index][lr_mask]+ scale = align_depth_scale(pred_depth_lr_masked, gt_depth_lr_masked, 1 / gt_depth_lr_masked)+ pred_depth = pred_depth * scale++ metrics['depth_scale_invariant'] = {+ 'rel': rel_depth(pred_depth[mask], gt_depth[mask]),+ 'delta1': delta1_depth(pred_depth[mask], gt_depth[mask])+ }++ if pred_depth_aligned is None:+ pred_depth_aligned = pred_depth++ # Affine-invariant depth+ if 'depth_affine_invariant' in pred:+ pred_depth_affine_invariant = pred['depth_affine_invariant']+ elif 'depth_scale_invariant' in pred:+ pred_depth_affine_invariant = pred['depth_scale_invariant']+ elif 'depth_metric' in pred:+ pred_depth_affine_invariant = pred['depth_metric']+ else:+ pred_depth_affine_invariant = None++ if pred_depth_affine_invariant is not None:+ pred_depth = pred_depth_affine_invariant++ pred_depth_lr_masked, gt_depth_lr_masked = pred_depth[lr_index][lr_mask], gt_depth[lr_index][lr_mask]+ scale, shift = align_depth_affine(pred_depth_lr_masked, gt_depth_lr_masked, 1 / gt_depth_lr_masked)+ pred_depth = pred_depth * scale + shift++ metrics['depth_affine_invariant'] = {+ 'rel': rel_depth(pred_depth[mask], gt_depth[mask]),+ 'delta1': delta1_depth(pred_depth[mask], gt_depth[mask])+ }++ if pred_depth_aligned is None:+ pred_depth_aligned = pred_depth++ # Affine-invariant LOG-depth (e.g. PPD, whose raw output is normalized log(d+1)).+ # Align in log space then exponentiate, matching the model's native parameterization+ # and PPD's official recover_metric_depth_ransac. Metrics are still computed/reported+ # in linear depth under the standard 'depth_affine_invariant' key.+ if 'depth_logaffine_invariant' in pred:+ pred_log = pred['depth_logaffine_invariant']+ gt_log = torch.log(gt_depth + 1.0)++ pred_log_lr_masked, gt_log_lr_masked = pred_log[lr_index][lr_mask], gt_log[lr_index][lr_mask]+ scale, shift = align_depth_affine(pred_log_lr_masked, gt_log_lr_masked, 1 / gt_depth[lr_index][lr_mask])+ pred_depth = torch.exp(pred_log * scale + shift) - 1.0++ metrics['depth_affine_invariant'] = {+ 'rel': rel_depth(pred_depth[mask], gt_depth[mask]),+ 'delta1': delta1_depth(pred_depth[mask], gt_depth[mask])+ }++ if pred_depth_aligned is None:+ pred_depth_aligned = pred_depth++ # Affine-invariant disparity+ if 'disparity_affine_invariant' in pred:+ pred_disparity_affine_invariant = pred['disparity_affine_invariant']+ elif 'depth_scale_invariant' in pred:+ pred_disparity_affine_invariant = 1 / pred['depth_scale_invariant']+ elif 'depth_metric' in pred:+ pred_disparity_affine_invariant = 1 / pred['depth_metric']+ else:+ pred_disparity_affine_invariant = None++ if pred_disparity_affine_invariant is not None:+ pred_disp = pred_disparity_affine_invariant++ scale, shift = align_affine_lstsq(pred_disp[mask], 1 / gt_depth[mask])+ pred_disp = pred_disp * scale + shift++ # NOTE: The alignment is done on the disparity map could introduce extreme outliers at disparities close to 0.+ # Therefore we clamp the disparities by minimum ground truth disparity.+ pred_depth = 1 / pred_disp.clamp_min(1 / gt_depth[mask].max().item())++ metrics['disparity_affine_invariant'] = {+ 'rel': rel_depth(pred_depth[mask], gt_depth[mask]),+ 'delta1': delta1_depth(pred_depth[mask], gt_depth[mask])+ }++ if pred_depth_aligned is None:+ pred_depth_aligned = 1 / pred_disp.clamp_min(1e-6)++ # Metric points+ if 'points_metric' in pred and gt['is_metric']:+ pred_points = pred['points_metric']++ pred_points_lr_masked, gt_points_lr_masked = pred_points[lr_index][lr_mask], gt_points[lr_index][lr_mask]+ shift = align_points_xyz_shift(pred_points_lr_masked, gt_points_lr_masked, 1 / gt_points_lr_masked.norm(dim=-1))+ pred_points = pred_points + shift++ metrics['points_metric'] = {+ 'rel': rel_point(pred_points[mask], gt_points[mask]),+ 'delta1': delta1_point(pred_points[mask], gt_points[mask])+ }++ if pred_points_aligned is None:+ pred_points_aligned = pred['points_metric']++ # Scale-invariant points (in camera space)+ if 'points_scale_invariant' in pred:+ pred_points_scale_invariant = pred['points_scale_invariant']+ elif 'points_metric' in pred:+ pred_points_scale_invariant = pred['points_metric']+ else:+ pred_points_scale_invariant = None++ if pred_points_scale_invariant is not None:+ pred_points = pred_points_scale_invariant++ pred_points_lr_masked, gt_points_lr_masked = pred_points_scale_invariant[lr_index][lr_mask], gt_points[lr_index][lr_mask]+ scale = align_points_scale(pred_points_lr_masked, gt_points_lr_masked, 1 / gt_points_lr_masked.norm(dim=-1))+ pred_points = pred_points * scale++ metrics['points_scale_invariant'] = {+ 'rel': rel_point(pred_points[mask], gt_points[mask]),+ 'delta1': delta1_point(pred_points[mask], gt_points[mask])+ }++ if vis and pred_points_aligned is None:+ pred_points_aligned = pred['points_scale_invariant'] * scale++ # Affine-invariant points+ if 'points_affine_invariant' in pred:+ pred_points_affine_invariant = pred['points_affine_invariant']+ elif 'points_scale_invariant' in pred:+ pred_points_affine_invariant = pred['points_scale_invariant']+ elif 'points_metric' in pred:+ pred_points_affine_invariant = pred['points_metric']+ else:+ pred_points_affine_invariant = None++ if pred_points_affine_invariant is not None:+ pred_points = pred_points_affine_invariant++ pred_points_lr_masked, gt_points_lr_masked = pred_points[lr_index][lr_mask], gt_points[lr_index][lr_mask]+ scale, shift = align_points_scale_xyz_shift(pred_points_lr_masked, gt_points_lr_masked, 1 / gt_points_lr_masked.norm(dim=-1))+ pred_points = pred_points * scale + shift++ metrics['points_affine_invariant'] = {+ 'rel': rel_point(pred_points[mask], gt_points[mask]),+ 'delta1': delta1_point(pred_points[mask], gt_points[mask])+ }++ if vis and pred_points_aligned is None:+ pred_points_aligned = pred['points_affine_invariant'] * scale + shift+ affine_points_scale = scale+ affine_points_shift = shift++ # Local points+ if 'segmentation_mask' in gt and 'points' in gt and any('points' in k for k in pred.keys()):+ pred_points = next(pred[k] for k in pred.keys() if 'points' in k)+ gt_points = gt['points']+ segmentation_mask = gt['segmentation_mask']+ segmentation_labels = gt['segmentation_labels']+ segmentation_mask_lr = segmentation_mask[lr_index]+ local_points_metrics = []+ for _, seg_id in segmentation_labels.items():+ valid_mask = (segmentation_mask == seg_id) & mask++ pred_points_masked = pred_points[valid_mask]+ gt_points_masked = gt_points[valid_mask]++ valid_mask_lr = (segmentation_mask_lr == seg_id) & lr_mask+ if valid_mask_lr.sum().item() < 10:+ continue+ pred_points_masked_lr = pred_points[lr_index][valid_mask_lr]+ gt_points_masked_lr = gt_points[lr_index][valid_mask_lr]+ diameter = (gt_points_masked.max(dim=0).values - gt_points_masked.min(dim=0).values).max()+ scale, shift = align_points_scale_xyz_shift(pred_points_masked_lr, gt_points_masked_lr, 1 / diameter.expand(gt_points_masked_lr.shape[0]))+ pred_points_masked = pred_points_masked * scale + shift++ local_points_metrics.append({+ 'rel': rel_point_local(pred_points_masked, gt_points_masked, diameter),+ 'delta1': delta1_point_local(pred_points_masked, gt_points_masked, diameter),+ })++ metrics['local_points'] = key_average(local_points_metrics)++ # FOV. NOTE: If there is no random augmentation applied to the input images, all GT FOV are generallly the same.+ # Fair evaluation of FOV requires random augmentation.+ if 'intrinsics' in pred and 'intrinsics' in gt:+ pred_intrinsics = pred['intrinsics']+ gt_intrinsics = gt['intrinsics']+ pred_fov_x, pred_fov_y = intrinsics_to_fov(pred_intrinsics)+ gt_fov_x, gt_fov_y = intrinsics_to_fov(gt_intrinsics)+ metrics['fov_x'] = {+ 'mae': torch.rad2deg(pred_fov_x - gt_fov_x).abs().mean().item(),+ 'deviation': torch.rad2deg(pred_fov_x - gt_fov_x).item(),+ }++ # Depth-range stratified metrics+ if compute_depth_range and pred_depth_aligned is not None:+ range_metrics = compute_depth_range_metrics(+ pred_depth_aligned, gt_depth,+ pred_points_aligned, gt_points,+ mask,+ )+ if range_metrics:+ metrics['depth_range'] = range_metrics++ # Boundary F1+ if pred_depth_aligned is not None and 'has_sharp_boundary' in gt and gt['has_sharp_boundary']:+ metrics['boundary'] = {+ 'radius1_f1': boundary_f1(pred_depth_aligned, gt_depth, mask, radius=1),+ 'radius2_f1': boundary_f1(pred_depth_aligned, gt_depth, mask, radius=2),+ 'radius3_f1': boundary_f1(pred_depth_aligned, gt_depth, mask, radius=3),+ }++ # SI Boundary F1 (computed for specified datasets via CLI)+ if compute_si_boundary and pred_depth_aligned is not None:+ pred_np = pred_depth_aligned.squeeze().cpu().numpy()+ gt_np = gt_depth.squeeze().cpu().numpy()+ metrics['si_boundary_f1'] = SI_boundary_F1(pred_np, gt_np)++ # Add boundary visualization+ if vis:+ # Imported lazily: util.viz_boundary imports+ # metrics.boundary_metrics, so a module-level import here+ # would be a circular import.+ from util.viz_boundary import viz_boundary_comparison+ misc['boundary_viz'] = viz_boundary_comparison(pred_np, gt_np, threshold=1.10)++ if vis:+ if pred_points_aligned is not None:+ misc['pred_points'] = pred_points_aligned+ if pred_depth_aligned is not None:+ misc['pred_depth'] = pred_depth_aligned+ if affine_points_scale is not None:+ misc['affine_points_scale'] = affine_points_scale+ if affine_points_shift is not None:+ misc['affine_points_shift'] = affine_points_shift++ return metrics, misc+++def _test():+ pred = {+ 'depth_affine_invariant': torch.rand(1, 256, 256),+ 'points_affine_invariant': torch.rand(1, 256, 256, 3),+ }+ gt = {+ 'depth': torch.rand(1, 256, 256) * 10 + 0.1,+ 'points': torch.rand(1, 256, 256, 3) * 10,+ 'depth_mask': torch.rand(1, 256, 256) > 0.2,+ }+ metrics, misc = compute_metrics(pred, gt, vis=False)++ print(metrics)+++if __name__ == "__main__":+ _test()+++diff --git a/metrics/helpers.py b/metrics/helpers.pynew file mode 100644index 0000000..0cdbab7--- /dev/null+++ b/metrics/helpers.py@@ -0,0 +1,146 @@+# coding=utf-8++# Decorators used by the metric suite.+# Adapted from utils3d (https://github.com/EasternJournalist/utils3d), MIT License.+import torch+from torch import Tensor+from numbers import Number+import inspect+from typing import *+from functools import wraps+++__all__ = [+ 'toarray',+ 'batched',+]++P = ParamSpec("P")+R = TypeVar("R")+++def suppress_traceback(fn):+ @wraps(fn)+ def wrapper(*args, **kwargs):+ try:+ return fn(*args, **kwargs)+ except Exception as e:+ e.__traceback__ = e.__traceback__.tb_next.tb_next+ raise+ return wrapper+++class no_warnings:+ def __init__(self, action: str = 'ignore', **kwargs):+ self.action = action+ self.filter_kwargs = kwargs++ def __call__(self, fn: Callable[[P], R]) -> Callable[[P], R]:+ @wraps(fn)+ def wrapper(*args, **kwargs):+ with warnings.catch_warnings():+ warnings.simplefilter(self.action, **self.filter_kwargs)+ return fn(*args, **kwargs)+ return wrapper++ def __enter__(self):+ self.warnings_manager = warnings.catch_warnings()+ self.warnings_manager.__enter__()+ warnings.simplefilter(self.action, **self.filter_kwargs)++ def __exit__(self, exc_type, exc_val, exc_tb):+ self.warnings_manager.__exit__(exc_type, exc_val, exc_tb)++++def totensor(+ *args_dtypes: Union[torch.dtype, Tuple[torch.dtype, torch.device], str, None],+ _others: Union[torch.dtype, str] = None,+ **kwargs_dtypes: Union[torch.dtype, Tuple[torch.dtype, torch.device], str]+) -> Callable[[Callable[P, R]], Callable[P, R]]:+ """+ Decorator generator that converts non-array arguments to array of specified default dtype.+ """+ def decorator(func: Callable[P, R]) -> Callable[P, R]:+ argnames = list(inspect.signature(func).parameters.keys())+ dtypes_dict = {+ **dict(zip(argnames, args_dtypes)),+ **kwargs_dtypes+ }+ @wraps(func)+ @suppress_traceback+ def wrapper(*args, **kwargs):+ inputs = {+ **{argnames[i]: x for i, x in enumerate(args)},+ **kwargs+ }+ if len(input_devices := tuple(x.device for x in inputs.values() if isinstance(x, Tensor))) > 0:+ device = input_devices[0]+ else:+ device = None+ args = tuple(+ torch.tensor(x).to(device, getattr(inputs[dtype], 'dtype', None) if isinstance(dtype, str) else dtype)+ if isinstance(x, (Number, list, tuple)) \+ and (dtype := dtypes_dict.get(argnames[i], _others)) is not None \+ else x+ for i, x in enumerate(args)+ )+ kwargs = {+ k: torch.tensor(x).to(device, getattr(inputs[dtype], 'dtype', None) if isinstance(dtype, str) else dtype)+ if isinstance(x, (Number, list, tuple)) \+ and (dtype := dtypes_dict.get(k, _others)) is not None \+ else x+ for k, x in kwargs.items()+ }+ return func(*args, **kwargs)+ return wrapper+ return decorator+++def batched(*args_dims: Union[int, None], _others: Union[int, None] = None, **kwargs_dims: Union[int, None]) -> Callable[[Callable[P, R]], Callable[P, R]]:+ """+ Decorator generator that extends a function's input and out batch dimensions.+ """+ def decorator(func: Callable[P, R]) -> Callable[P, R]:+ argnames = list(inspect.signature(func).parameters.keys())+ dims_dict = {+ **dict(zip(argnames, args_dims)),+ **kwargs_dims+ }+ @wraps(func)+ @suppress_traceback+ def wrapper(*args, **kwargs):+ args = list(args)+ # Get arguments non-batch dimensions+ args_dim = tuple(dims_dict.get(argname, _others) for argname in argnames[:len(args)])+ kwargs_dim = {k: dims_dict.get(k, _others) for k in kwargs}+ # Find the common batch shape+ batch_shape = torch.broadcast_shapes(*(+ x.shape[:x.ndim - dim]+ for x, dim in zip((*args, *kwargs.values()), (*args_dim, *kwargs_dim.values()))+ if isinstance(x, Tensor) and dim is not None+ ))+ # Broadcast and flatten batch dimensions+ args = tuple(+ torch.broadcast_to(x, (*batch_shape, *x.shape[x.ndim - dim:])).reshape((-1, *x.shape[x.ndim - dim:]))+ if isinstance(x, Tensor) and dim is not None else x+ for x, dim in zip(args, args_dim)+ )+ kwargs = {+ k: torch.broadcast_to(x, (*batch_shape, *x.shape[x.ndim - dim:])).reshape((-1, *x.shape[x.ndim - dim:]))+ if isinstance(x, Tensor) and (dim := kwargs_dim[k]) is not None else x+ for k, x in kwargs.items()+ }+ # Call function+ result = func(*args, **kwargs)+ # Restore batch shape+ if isinstance(result, tuple):+ result = tuple(+ x.reshape((*batch_shape, *x.shape[1:])) if isinstance(x, Tensor) else x+ for x in result+ )+ elif isinstance(result, Tensor):+ result = result.reshape((*batch_shape, *result.shape[1:]))+ return result+ return wrapper+ return decoratordiff --git a/metrics/masked_resize.py b/metrics/masked_resize.pynew file mode 100644index 0000000..2691482--- /dev/null+++ b/metrics/masked_resize.py@@ -0,0 +1,203 @@+# coding=utf-8++# Mask-aware tensor resizing.+# Adapted from utils3d (https://github.com/EasternJournalist/utils3d), MIT License.+import torch+from torch import Tensor+++from typing import *+from typing_extensions import Unpack+import math++from metrics.utils import masked_max, masked_min, sliding_window++++def masked_nearest_resize(+ *image: Tensor,+ mask: Tensor,+ size: Tuple[int, int],+ return_index: bool = False+) -> Tuple[Unpack[Tuple[Tensor, ...]], Tensor, Tuple[Tensor, ...]]:+ """+ Resize image(s) by nearest sampling with mask awareness. Suitable for sparse maps. + - Downsampling: Assign the nearest valid pixel within the target pixel's receptive field.+ - Upsampling: Assign the valid pixel to only the nearest pixel in the resized map.+++ ### Parameters+ - `*image`: Itorchut image(s) of shape `(..., H, W, C)` or `(... , H, W)`+ - You can pass multiple images to be resized at the same time for efficiency.+ - `mask`: itorchut mask of shape `(..., H, W)`, dtype=bool+ - `size`: target size `(H', W')`+ - `return_index`: whether to return the nearest neighbor indices in the original map for each pixel in the resized map.+ Defaults to False.++ ### Returns+ - `*resized_image`: resized image(s) of shape `(..., H', W', C)`. or `(..., H', W')`+ - `resized_mask`: mask of the resized map of shape `(..., H', W')`+ - `nearest_indices`: tuple of shape `(..., H', W')`. The nearest neighbor indices of the resized map of each dimension.+ """+ device = mask.device+ height, width = mask.shape[-2:]+ target_height, target_width = size+ filter_h_f, filter_w_f = height / target_height, width / target_width+ filter_h_i, filter_w_i = math.ceil(filter_h_f), math.ceil(filter_w_f)+ filter_size = filter_h_i * filter_w_i+ filter_shape = (filter_h_i, filter_w_i)+ padding_h, padding_w = filter_h_i // 2 + 1, filter_w_i // 2 + 1+ padding_shape = ((padding_h, padding_h), (padding_w, padding_w))++ # Window the original mask and uv+ pixels = pixel_coord_map(height, width, convention='integer-corner', dtype=torch.float32, device=device)+ indices = torch.arange(height * width, dtype=torch.long, device=device).reshape(height, width)+ window_pixels = sliding_window(pixels, window_size=filter_shape, pad_size=padding_shape, dim=(0, 1))+ window_indices = sliding_window(indices, window_size=filter_shape, pad_size=padding_shape, dim=(0, 1))+ window_mask = sliding_window(mask, window_size=filter_shape, pad_size=padding_shape, dim=(-2, -1))++ # Gather the target pixels's local window+ target_centers = uv_map(target_height, target_width, dtype=torch.float32, device=device) * torch.tensor([width, height], dtype=torch.float32, device=device)+ target_lefttop = target_centers - torch.tensor((filter_w_f / 2, filter_h_f / 2), dtype=torch.float32, device=device)+ target_window = torch.round(target_lefttop).to(torch.long) + torch.tensor((padding_w, padding_h), dtype=torch.long, device=device)++ target_window_pixels = window_pixels[target_window[..., 1], target_window[..., 0], :, :, :].reshape(target_height, target_width, 2, filter_size) # (target_height, tgt_width, 2, filter_size)+ target_window_mask = window_mask[..., target_window[..., 1], target_window[..., 0], :, :].reshape(*mask.shape[:-2], target_height, target_width, filter_size) # (..., target_height, tgt_width, filter_size)+ target_window_indices = window_indices[target_window[..., 1], target_window[..., 0], :, :].reshape(target_height, target_width, filter_size) # (target_height, tgt_width, filter_size)++ # Compute nearest neighbor in the local window for each pixel+ delta = target_window_pixels - target_centers[..., None]+ eps = torch.finfo(torch.float32).eps * max(height, width) # Shift a small epsilon to avoid numerical issues when the pixel is exactly on the border+ target_window_mask &= (-filter_w_f / 2 + eps < delta[..., 0, :]) & (delta[..., 0, :] <= filter_w_f / 2 + eps) & (-filter_h_f / 2 + eps < delta[..., 1, :]) & (delta[..., 1, :] <= filter_h_f / 2 + eps)+ dist = torch.where(target_window_mask, torch.square(delta[..., 0, :]) + torch.square(delta[..., 1, :]), torch.inf) # (..., target_height, tgt_width, filter_size)+ nearest_in_window = torch.argmin(dist, dim=-1, keepdim=True) # (..., target_height, tgt_width, 1)+ nearest_idx = torch.gather(+ target_window_indices.expand(dist.shape),+ dim=-1,+ index=nearest_in_window,+ ).squeeze(-1) # (..., target_height, tgt_width)+ nearest_i, nearest_j = nearest_idx // width, nearest_idx % width+ target_mask = torch.any(target_window_mask, dim=-1)+ batch_indices = [torch.arange(n, device=device).reshape([1] * i + [n] + [1] * (mask.ndim - i - 1)) for i, n in enumerate(mask.shape[:-2])]++ nearest_indices = (*batch_indices, nearest_i, nearest_j)+ outputs = tuple(x[nearest_indices] for x in image)++ if return_index:+ ret = (*outputs, target_mask, nearest_indices)+ else:+ ret = (*outputs, target_mask)++ if len(ret) == 1:+ return ret[0]+ else:+ return ret+++def pixel_coord_map(+ *size: Union[int, Tuple[int, int]],+ top: int = 0,+ left: int = 0,+ convention: Literal['integer-center', 'integer-corner'] = 'integer-center',+ dtype: torch.dtype = torch.float32,+ device: torch.device = None+) -> Tensor:+ """+ Get image pixel coordinates map. Support two conventions: `'integer-center'` and `'integer-corner'`.++ ## Parameters+ - `*size`: `Tuple[int, int]` or two integers of map size `(height, width)`+ - `top`: `int`, optional top boundary of the pixel coord map. Defaults to 0.+ - `left`: `int`, optional left boundary of the pixel coord map. Defaults to 0.+ - `convention`: `str`, optional `'integer-center'` or `'integer-corner'`, whether integer coordinates correspond to pixel centers or corners. Defaults to 'integer-center'.+ - `'integer-center'`: `pixel[i][j]` has integer coordinates `(j, i)` as its center, and occupies square area `[j - 0.5, j + 0.5) × [i - 0.5, i + 0.5)`.+ The top-left corner of the top-left pixel is `(-0.5, -0.5)`, and the bottom-right corner of the bottom-right pixel is `(width - 0.5, height - 0.5)`.+ - `'integer-corner'`: `pixel[i][j]` has coordinates `(j + 0.5, i + 0.5)` as its center, and occupies square area `[j, j + 1) × [i, i + 1)`.+ The top-left corner of the top-left pixel is `(0, 0)`, and the bottom-right corner of the bottom-right pixel is `(width, height)`.+ - `dtype`: `torch.dtype`, optional data type of the output pixel coord map. Defaults to torch.float32.++ ## Returns+ Tensor: shape (height, width, 2)++ >>> pixel_coord_map(10, 10, convention='integer-center', dtype=torch.long):+ [[[0, 0], [1, 0], ..., [9, 0]],+ [[0, 1], [1, 1], ..., [9, 1]],+ ... ... ...+ [[0, 9], [1, 9], ..., [9, 9]]]++ >>> pixel_coord_map(10, 10, convention='integer-corner', dtype=torch.float32):+ [[[0.5, 0.5], [1.5, 0.5], ..., [9.5, 0.5]],+ [[0.5, 1.5], [1.5, 1.5], ..., [9.5, 1.5]],+ ... ... ...+ [[0.5, 9.5], [1.5, 9.5], ..., [9.5, 9.5]]]+ """+ if len(size) == 1 and isinstance(size[0], tuple):+ height, width = size[0]+ else:+ height, width = size+ u = torch.arange(left, left + width, dtype=dtype, device=device)+ v = torch.arange(top, top + height, dtype=dtype, device=device)+ if convention == 'integer-corner':+ assert torch.is_floating_point(u), "dtype should be a floating point type when convention is 'integer-corner'"+ u = u + 0.5+ v = v + 0.5+ u, v = torch.meshgrid(u, v, indexing='xy')+ return torch.stack([u, v], dim=2)+++def uv_map(+ *size: Union[int, Tuple[int, int]],+ top: float = 0.,+ left: float = 0.,+ bottom: float = 1.,+ right: float = 1.,+ dtype: torch.dtype = torch.float32,+ device: torch.device = None+) -> Tensor:+ """+ Get image UV coordinate map. By default, (0., 0.) is the top-left corner of the image, and (1., 1.) is the bottom-right corner of the image.++ ## Parameters+ - `*size`: `Tuple[int, int]` or two integers of map size `(height, width)`+ - `top`: `float` defaults to 0.+ - `left`: `float` defaults to 0.+ - `bottom`: `float` defaults to 1.+ - `right`: `float` defaults to 1.+ - `dtype`: `torch.dtype` data type of the output uv map. Defaults to torch.float32.+ - `device`: `torch.device`, device of the output uv map. Defaults to None.++ ## Returns+ - `uv (Tensor)`: shape `(height, width, 2)`++ ## Example Usage++ >>> uv_map(10, 10):+ [[[0.05, 0.05], [0.15, 0.05], ..., [0.95, 0.05]],+ [[0.05, 0.15], [0.15, 0.15], ..., [0.95, 0.15]],+ ... ... ...+ [[0.05, 0.95], [0.15, 0.95], ..., [0.95, 0.95]]]+ """+ if len(size) == 1 and isinstance(size[0], tuple):+ height, width = size[0]+ else:+ height, width = size+ u = torch.linspace(left + 0.5 / width * (right - left), right - 0.5 / width * (right - left), width, dtype=dtype, device=device)+ v = torch.linspace(top + 0.5 / height * (bottom - top), bottom - 0.5 / height * (bottom - top), height, dtype=dtype, device=device)+ uv = torch.stack(torch.meshgrid(u, v, indexing='xy'), dim=-1)+ return uv++++def _test():+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')+ x = torch.rand(1, 256, 256).to(device)+ mask = x > 0.5+ height, width = mask.shape[-2:]+ lr_mask, lr_index = masked_nearest_resize(mask=mask, size=(64, 64), return_index=True)++ print(lr_mask.shape)+++if __name__ == "__main__":+ _test()+diff --git a/metrics/metrics.py b/metrics/metrics.pynew file mode 100644index 0000000..7c00920--- /dev/null+++ b/metrics/metrics.py@@ -0,0 +1,77 @@+# coding=utf-8++# Simple unaligned depth/point metrics, kept for reference.+# The reported numbers come from metrics/compute_metrics.py.+import torch+++def rel_depth(pred: torch.Tensor, gt: torch.Tensor, eps: float = 1e-6):+ rel = (torch.abs(pred - gt) / (gt + eps)).mean()+ return rel.item()+++def delta1_depth(pred: torch.Tensor, gt: torch.Tensor, eps: float = 1e-6):+ delta1 = (torch.maximum(gt / pred, pred / gt) < 1.25).float().mean()+ return delta1.item()+++def rel_point(pred: torch.Tensor, gt: torch.Tensor, eps: float = 1e-6):+ dist_gt = torch.norm(gt, dim=-1)+ dist_err = torch.norm(pred - gt, dim=-1)+ rel = (dist_err / (dist_gt + eps)).mean()+ return rel.item()+++def delta1_point(pred: torch.Tensor, gt: torch.Tensor, eps: float = 1e-6):+ dist_pred = torch.norm(pred, dim=-1)+ dist_gt = torch.norm(gt, dim=-1)+ dist_err = torch.norm(pred - gt, dim=-1)++ delta1 = (dist_err < 0.25 * torch.minimum(dist_gt, dist_pred)).float().mean()+ return delta1.item()+++def rel_point_local(pred: torch.Tensor, gt: torch.Tensor, diameter: torch.Tensor):+ dist_err = torch.norm(pred - gt, dim=-1)+ rel = (dist_err / diameter).mean()+ return rel.item()+++def delta1_point_local(pred: torch.Tensor, gt: torch.Tensor, diameter: torch.Tensor):+ dist_err = torch.norm(pred - gt, dim=-1)+ delta1 = (dist_err < 0.25 * diameter).float().mean()+ return delta1.item()+++def boundary_f1(pred: torch.Tensor, gt: torch.Tensor, mask: torch.Tensor, radius: int = 1):+ neighbor_x, neight_y = torch.meshgrid(+ torch.linspace(-radius, radius, 2 * radius + 1, device=pred.device),+ torch.linspace(-radius, radius, 2 * radius + 1, device=pred.device),+ indexing='xy'+ )+ neighbor_mask = (neighbor_x ** 2 + neight_y ** 2) <= radius ** 2 + 1e-5++ pred_window = utils3d.pt.sliding_window_2d(pred, window_size=2 * radius + 1, stride=1, dim=(-2, -1)) # [H, W, 2*R+1, 2*R+1]+ gt_window = utils3d.pt.sliding_window_2d(gt, window_size=2 * radius + 1, stride=1, dim=(-2, -1)) # [H, W, 2*R+1, 2*R+1]+ mask_window = neighbor_mask & utils3d.pt.sliding_window_2d(mask, window_size=2 * radius + 1, stride=1, dim=(-2, -1)) # [H, W, 2*R+1, 2*R+1]++ pred_rel = pred_window / pred[radius:-radius, radius:-radius, None, None]+ gt_rel = gt_window / gt[radius:-radius, radius:-radius, None, None]+ valid = mask[radius:-radius, radius:-radius, None, None] & mask_window++ f1_list = []+ w_list = t_list = torch.linspace(0.05, 0.25, 10).tolist()++ for t in t_list:+ pred_label = pred_rel > 1 + t+ gt_label = gt_rel > 1 + t+ TP = (pred_label & gt_label & valid).float().sum()+ precision = TP / (gt_label & valid).float().sum().clamp_min(1e-12)+ recall = TP / (pred_label & valid).float().sum().clamp_min(1e-12)+ f1 = 2 * precision * recall / (precision + recall).clamp_min(1e-12)+ f1_list.append(f1.item())++ f1_avg = sum(w * f1 for w, f1 in zip(w_list, f1_list)) / sum(w_list)+ return f1_avg++diff --git a/metrics/utils.py b/metrics/utils.pynew file mode 100644index 0000000..3914702--- /dev/null+++ b/metrics/utils.py@@ -0,0 +1,463 @@+# coding=utf-8++# Tensor helpers used by the metric suite.+# Adapted from utils3d (https://github.com/EasternJournalist/utils3d), MIT License.+from typing import *+from numbers import Number+from itertools import chain+from numbers import Integral++import torch+from torch import Tensor+import torch.nn.functional as F++from metrics.helpers import batched, no_warnings+++__all__ = [+ 'sliding_window',+ 'masked_min',+ 'masked_max',+ 'lookup',+ 'lookup_get',+ 'lookup_set',+ 'csr_matrix_from_dense_indices',+ 'csr_eliminate_zeros',+ 'group',+ 'lexsort',+ 'index_reduce',+ 'index_reduce_',+ 'scatter_argmax',+ 'scatter_argmin',+ 'reverse_permutation',+ 'large_multinomial'+]+++def sliding_window(+ x: Tensor,+ window_size: Union[int, Tuple[int, ...]],+ stride: Optional[Union[int, Tuple[int, ...]]] = None,+ dilation: Optional[Union[int, Tuple[int, ...]]] = None,+ pad_size: Optional[Union[int, Tuple[int, int], Tuple[Tuple[int, int]]]] = None,+ pad_mode: str = 'constant',+ pad_value: Number = 0,+ dim: Tuple[int, ...] = None+) -> Tensor:+ """+ Get a sliding window of the input array.+ This function is a wrapper of `torch.nn.functional.unfold` with additional support for padding and stride.++ ## Parameters+ - `x` (Tensor): Input tensor.+ - `window_size` (int or Tuple[int,...]): Size of the sliding window. If int+ is provided, the same size is used for all specified axes.+ - `stride` (Optional[Tuple[int,...]]): Stride between the sliding windows. If None,+ no stride is applied. If int is provided, the same stride is used for all specified axes.+ - `dilation` (Optional[Tuple[int,...]]): Dilation in each sliding window. If None,+ no dilation is applied. If int is provided, the same dilation is used for all specified axes.+ - `pad_size` (Optional[Union[int, Tuple[int, int], Tuple[Tuple[int, int]]]]): Size of padding to apply before sliding window.+ Corresponding to `axis`.+ - General format is `((before_1, after_1), (before_2, after_2), ...)`.+ - Shortcut formats:+ - `int` -> same padding before and after for all axes;+ - `(int, int)` -> same padding before and after for each axis;+ - `((int,), (int,) ...)` -> specify padding for each axis, same before and after.+ - `pad_mode` (str): Padding mode to use. Refer to `numpy.pad` for more details.+ - `pad_value` (Union[int, float]): Value to use for constant padding. Only used+ when `pad_mode` is 'constant'.+ - `axis` (Optional[Tuple[int,...]]): Axes to apply the sliding window. If None, all axes are used.++ ## Returns+ - (Tensor): Sliding window of the input array.+ - If no padding, the output is a view of the input array with zero copy.+ - Otherwise, the output is no longer a view but a copy of the padded array.+ """+ if dim is None:+ dim = tuple(range(x.ndim))+ if isinstance(dim, Integral):+ dim = (dim,)+ dim = [dim[i] % x.ndim for i in range(len(dim))]+ if isinstance(window_size, Integral):+ window_size = (window_size,) * len(dim)+ if stride is None:+ stride = (1,) * len(dim)+ elif isinstance(stride, Integral):+ stride = (stride,) * len(dim)+ if dilation is None:+ dilation = (1,) * len(dim)+ elif isinstance(dilation, Integral):+ dilation = (dilation,) * len(dim)+ assert len(window_size) == len(stride) == len(dim)++ # Pad the input array if needed+ if pad_size is not None:+ if isinstance(pad_size, Integral):+ pad_size = ((pad_size, pad_size),) * len(dim)+ elif isinstance(pad_size, tuple) and len(pad_size) == 2 and all(isinstance(p, Integral) for p in pad_size):+ pad_size = (pad_size,) * len(dim)+ elif isinstance(pad_size, tuple) and all(isinstance(p, tuple) and 1 <= len(p) <= 2 for p in pad_size):+ if len(pad_size) == 1:+ pad_size = pad_size * len(dim)+ else:+ assert len(pad_size) == len(dim), f"pad_size {pad_size} must match the number of axes {len(dim)}"+ pad_size = tuple(p * 2 if len(p) == 1 else p for p in pad_size)+ else:+ raise ValueError(f"Invalid pad_size {pad_size}")+ full_pad = [(0, 0) if i not in dim else pad_size[dim.index(i)] for i in range(x.ndim)]+ full_pad = tuple(chain(*reversed(full_pad)))+ x = F.pad(x, full_pad, mode=pad_mode, value=pad_value)++ for i in range(len(window_size)):+ x = x.unfold(dim[i], (window_size[i] - 1) * dilation[i] + 1, stride[i])[..., ::dilation[i]]+ return x+++def masked_min(input: Tensor, mask: torch.BoolTensor, dim: int = None, keepdim: bool = False) -> Union[Tensor, Tuple[Tensor, Tensor]]:+ """Similar to torch.min, but with mask+ """+ if dim is None:+ return torch.where(mask, input, torch.tensor(torch.inf, dtype=input.dtype, device=input.device)).min()+ else:+ return torch.where(mask, input, torch.tensor(torch.inf, dtype=input.dtype, device=input.device)).min(dim=dim, keepdim=keepdim)+++def masked_max(input: Tensor, mask: torch.BoolTensor, dim: int = None, keepdim: bool = False) -> Union[Tensor, Tuple[Tensor, Tensor]]:+ """Similar to torch.max, but with mask+ """+ if dim is None:+ return torch.where(mask, input, torch.tensor(-torch.inf, dtype=input.dtype, device=input.device)).max()+ else:+ return torch.where(mask, input, torch.tensor(-torch.inf, dtype=input.dtype, device=input.device)).max(dim=dim, keepdim=keepdim)+++def lookup(key: Tensor, query: Tensor) -> torch.LongTensor:+ """Look up `query` in `key` like a dictionary. Useful for COO indexing.++ Parameters+ ----+ - `key` (Tensor): shape `(K, *key_shape)`, the array to search in+ - `query` (Tensor): shape `(..., *key_shape)`, the array to search for. `...` represents any number of batch dimensions.++ Returns+ ----+ - `indices` (Tensor): shape `(...,)` shape `(...,)` indices in `key` for each `query`. If a query is not found in key, the corresponding index will be -1.++ Notes+ ----+ `O((Q + K) * log(Q + K))` complexity, where `Q` is the number of queries and `K` is the number of keys.+ """+ num_keys, *key_shape = key.shape+ query_batch_shape = query.shape[:query.ndim - key.ndim + 1]++ unique, inverse = torch.unique(+ torch.cat([key, query.reshape(-1, *key_shape)], dim=0),+ dim=0,+ return_inverse=True+ )+ index = torch.full((unique.shape[0],), -1, dtype=torch.long, device=key.device)+ index.scatter_(0, inverse[:num_keys], torch.arange(num_keys, device=key.device))+ result = index.index_select(0, inverse[num_keys:]).reshape(query_batch_shape)+ return torch.where(result < num_keys, result, -1)+++def lookup_get(key: Tensor, value: Tensor, get_key: Tensor, default_value: Union[Number, Tensor] = 0) -> Tensor:+ """Dictionary-like get for arrays++ ## Parameters+ - `key` (Tensor): shape `(N, *key_shape)`, the key array of the dictionary to get from+ - `value` (Tensor): shape `(N, *value_shape)`, the value array of the dictionary to get from+ - `get_key` (Tensor): shape `(M, *key_shape)`, the key array to get for+ - `default_value` (Union[Number, Tensor]): value to return if a key in `get_key` is not found in `key`. A scalar or tensor broadcastable to shape `(..., *value_shape)`++ ## Returns+ `get_value` (Tensor): shape `(M, *value_shape)`, result values corresponding to `get_key`+ """+ indices = lookup(key, get_key)+ if key.shape[0] == 0:+ return torch.broadcast_to(+ torch.as_tensor(default_value, dtype=value.dtype, device=value.device),+ get_key.shape[:get_key.ndim - key.ndim + 1] + value.shape[1:]+ )+ return torch.where(+ (indices >= 0)[(slice(None), *((None,) * (value.ndim - 1)))],+ value[indices.clip(0, key.shape[0] - 1)],+ default_value+ )+++def lookup_set(key: Tensor, value: Tensor, set_key: Tensor, set_value: Tensor, append: bool = False, inplace: bool = False) -> Tuple[Tensor, Tensor]:+ """Dictionary-like set for arrays.++ ## Parameters+ - `key` (Tensor): shape `(N, *key_shape)`, the key array of the dictionary to set+ - `value` (Tensor): shape `(N, *value_shape)`, the value array of the dictionary to set+ - `set_key` (Tensor): shape `(M, *key_shape)`, the key array to set for+ - `set_value` (Tensor): shape `(M, *value_shape)`, the value array to set as+ - `append` (bool): If True, append the (key, value) pairs in (set_key, set_value) that are not in (key, value) to the result.+ - `inplace` (bool): If True, modify the input `value` array++ ## Returns+ - `result_key` (Tensor): shape `(N_new, *value_shape)`. N_new = N + number of new keys added if append is True, else N.+ - `result_value (Tensor): shape `(N_new, *value_shape)`+ """+ set_indices = lookup(key, set_key)+ if inplace:+ assert append is False, "Cannot append when inplace is True"+ else:+ value = value.clone()+ hit = torch.where(set_indices >= 0)+ value[set_indices[hit]] = set_value[hit]+ if append:+ missing = torch.where(set_indices < 0)+ key = torch.cat([key, set_key[missing]], axis=0)+ value = torch.cat([value, set_value[missing]], axis=0)+ return key, value+++def csr_matrix_from_dense_indices(indices: Tensor, n_cols: int) -> Tensor:+ """Convert a regular indices array to a sparse CSR adjacency matrix format++ ## Parameters+ - `indices` (Tensor): shape (N, M) dense tensor. Each one in `N` has `M` connections.+ - `values` (Tensor): shape (N, M) values of the connections+ - `n_cols` (int): total number of columns in the adjacency matrix++ ## Returns+ Tensor: shape `(N, n_cols)` sparse CSR adjacency matrix+ """+ return torch.sparse_csr_tensor(+ crow_indices=torch.arange(0, indices.numel() + 1, indices.shape[1], device=indices.device),+ col_indices=indices.view(-1),+ values=torch.ones_like(indices, dtype=torch.bool).view(-1),+ size=(indices.shape[0], n_cols)+ )+++def csr_eliminate_zeros(input: Tensor):+ """Remove zero elements from a sparse CSR tensor.+ """+ nonzero = input.values() != 0+ nonzero_element_indices = nonzero.nonzero(as_tuple=False).flatten()+ row_nonzero_count = torch.sparse_csr_tensor(+ input.crow_indices(),+ input.col_indices(),+ nonzero,+ input.size()+ ).long().sum(dim=-1, keepdim=True).to_dense().flatten()+ crow_indices = torch.cat([torch.tensor([0], device=input.device), torch.cumsum(row_nonzero_count, dim=0)])+ col_indices = input.col_indices()[nonzero_element_indices]+ values = input.values()[nonzero_element_indices]+ return torch.sparse_csr_tensor(crow_indices, col_indices, values, input.size())++def csr_roll_col_indices(input: Tensor, shift: int):+ """Roll the order of column indices of a sparse CSR tensor.+ The result is mathematically equivalent to the original matrix, but with a different column order.++ ## Parameters+ - `input` (Tensor): shape `(N, M)`, sparse CSR tensor+ - `shift` (int): number of positions to shift the column indices++ ## Returns+ Tensor: shape `(N, M)` sparse CSR tensor with rolled column indices+ """+ lengths = input.crow_indices()[1:] - input.crow_indices()[:-1]+ start = input.crow_indices()[:-1].repeat_interleave(lengths)+ elem_indices = start + (torch.arange(input.col_indices().shape[0], dtype=input.col_indices().dtype) - start - shift) % lengths.repeat_interleave(lengths)+ col_indices = input.col_indices().gather(0, elem_indices)+ values = input.values().gather(0, elem_indices)+ return torch.sparse_csr_tensor(input.crow_indices(), col_indices, values, input.size())+++def group(labels: Tensor, data: Optional[Tensor] = None) -> List[Tuple[Tensor, Tensor]]:+ """+ Split the data into groups based on the provided labels.++ ## Parameters+ - `labels` (Tensor): shape `(N, *label_dims)` array of labels for each data point. Labels can be multi-dimensional.+ - `data` (Tensor, optional): shape `(N, *data_dims)` dense tensor. Each one in `N` has `D` features.+ If None, return the indices in each group instead.++ ## Returns+ - `groups` (List[Tuple[Tensor, Tensor]]): List of each group, a tuple of `(label, data_in_group)`.+ - `label` (Tensor): shape (*label_dims,) the label of the group.+ - `data_in_group` (Tensor): shape (M, *data_dims) the data points in the group.+ If `data` is None, `data_in_group` will be the indices of the data points in the original array.+ """+ group_labels, inv, counts = torch.unique(labels, return_inverse=True, return_counts=True, dim=0)+ if data is None:+ data = torch.arange(labels.shape[0], device=labels.device)+ data_groups = torch.split(data[torch.argsort(inv)], counts.tolist())+ return list(zip(group_labels, data_groups))+++def lexsort(keys: Union[Sequence[Tensor], Tensor], dim: int = -1) -> Tensor:+ """Perform lexicographical sort on multiple keys. Like `numpy.lexsort`.++ Given multiple sorting keys, lexsort returns an array of integer indices that describes the sort order by multiple keys.+ The last key in the sequence is used for the primary sort order, ties are broken by the second-to-last key, and so on.++ Parameters+ ----+ - `keys`: (Sequence[Tensor]) sequence of Tensors to sort by, or a single Tensor with shape `(num_keys, ...)`.+ - `dim`: (int) the dimension to sort along. Note that if `keys` is a single Tensor, `dim=0` refers to the second dimension of `keys`.++ Returns+ ----+ - `indices`: (Tensor) the indices that would sort the keys lexicographically along the specified dimension.++ Notes+ -----+ Sorting is always stable.+ """+ if isinstance(keys, Tensor):+ keys = torch.unbind(keys, dim=0)+ else:+ torch.broadcast_shapes(*[key.shape for key in keys])++ assert len(keys) > 0, "At least one key is required for lexsort"++ dim = dim % keys[0].ndim+ for i, key in enumerate(keys):+ if i == 0:+ sorted_indices = torch.argsort(key, dim=dim, stable=True)+ else:+ key = torch.take_along_dim(key, sorted_indices, dim=dim)+ sorted_indices = torch.take_along_dim(sorted_indices, torch.argsort(key, dim=dim, stable=True), dim=dim)++ return sorted_indices+++def index_reduce(input: Tensor, indices: Union[Tuple[Tensor], List[Tensor]], values: Tensor, reduce: Literal['amin', 'amax', 'sum', 'prod', 'mean'], include_self: bool = True) -> Tensor:+ """Put values into the input tensor at the specified indices (like `index_put`), with reduction support.+ Behaves like `numpy.ufunc.at`.++ Parameters+ ----+ - `input`: (Tensor) the input tensor to modify.+ - `indices`: (Tensor) the indices at which to put the values.+ - `values`: (Tensor) the values to put into the input tensor.+ - `reduce`: (str) the reduction method to use when multiple values are put at the same index. Options are 'amin', 'amax', 'sum', 'prod', and 'mean'.++ Returns+ ----+ - (Tensor) the modified tensor after putting the values.+ """+ flat_idx = (torch.stack(indices, dim=1) * torch.tensor(input.stride(), dtype=torch.long, device=input.device)).sum(dim=1)+ output = input.reshape(-1).scatter_reduce(0, flat_idx, values.view(-1), reduce=reduce, include_self=include_self)+ output = output.reshape(input.shape)+ return output+++def index_reduce_(input: Tensor, indices: Union[Tuple[Tensor], List[Tensor]], values: Tensor, reduce: Literal['amin', 'amax', 'sum', 'prod', 'mean'], include_self: bool = True) -> Tensor:+ """In-place put values into the input tensor at the specified indices (like `index_put_`), with reduction support.+ Behaves like `numpy.ufunc.at`.++ Parameters+ ----+ - `input`: (Tensor) the input tensor to modify.+ - `indices`: (Tensor) the indices at which to put the values.+ - `values`: (Tensor) the values to put into the input tensor.+ - `reduce`: (str) the reduction method to use when multiple values are put at the same index. Options are 'amin', 'amax', 'sum', 'prod', and 'mean'.++ Returns+ ----+ - (Tensor) the modified tensor after putting the values.+ """+ assert input.is_contiguous(), "Input tensor must be contiguous for in-place index_reduce_"+ flat_idx = (torch.stack(indices, dim=1) * torch.tensor(input.stride(), dtype=torch.long, device=input.device)).sum(dim=1)+ input.view(-1).scatter_reduce_(0, flat_idx, values.view(-1), reduce=reduce, include_self=include_self)+ return input+++def scatter_argmin(input: Tensor, dim: int, index: Tensor, src: Tensor, include_self: bool = True) -> Tensor:+ """Scatter src into input at index along dim with min reduction. Return the indices of the winners in src.++ Parameters+ ----+ - `input`: (Tensor) the input tensor to scatter into.+ - `dim`: (int) the dimension along which to index.+ - `index`: (LongTensor) the indices at which to scatter.+ - `src`: (Tensor) the source tensor to scatter from.+ - `include_self`: (bool) whether to include the original values in `input` when computing the min.++ Returns+ ----+ - `argmin`: (LongTensor) shape same as `input`, the indices of the min values in `src`.++ Notes+ ----+ - If multiple values in `src` are equal to the min value at a position, the one with the smallest index in `src` will be chosen.+ - If none of src was scattered to a position (i.e., not presented, or the min value is from the original input), the index will be -1.+ """+ dim = dim % input.ndim+ min_values = input.scatter_reduce(dim=dim, index=index, src=src, reduce='amin', include_self=include_self)+ min_where_in_src = torch.where(src == torch.gather(min_values, dim=dim, index=index))+ min_indices = torch.full_like(min_values, -1, dtype=torch.long)+ index_reduce_(min_indices, (*min_where_in_src[:dim], index[min_where_in_src[dim]], *min_where_in_src[dim + 1:]), include_self=False)+ return min_indices+++def scatter_argmax(input: Tensor, dim: int, index: Tensor, src: Tensor, include_self: bool = True) -> Tensor:+ """Scatter src into input at index along dim with min reduction. Return the indices of the winners in src.++ Parameters+ ----+ - `input`: (Tensor) the input tensor to scatter into.+ - `dim`: (int) the dimension along which to index.+ - `index`: (LongTensor) the indices at which to scatter.+ - `src`: (Tensor) the source tensor to scatter from.+ - `include_self`: (bool) whether to include the original values in `input` when computing the min.++ Returns+ ----+ - `argmin`: (LongTensor) shape same as `input`, the indices of the min values in `src`.++ Notes+ ----+ - If multiple values in `src` are equal to the min value at a position, the one with the smallest index in `src` will be chosen.+ - If none of src was scattered to a position (i.e., not presented, or the min value is from the original input), the index will be -1.+ """+ dim = dim % input.ndim+ max_values = input.scatter_reduce(dim=dim, index=index, src=src, reduce='amax', include_self=include_self)+ max_where_in_src = torch.where(src == torch.gather(max_values, dim=dim, index=index))+ max_indices = torch.full_like(max_values, -1, dtype=torch.long)+ index_reduce_(max_indices, (*max_where_in_src[:dim], index[max_where_in_src[dim]], *max_where_in_src[dim + 1:]), include_self=False)+ return max_indices+++def reverse_permutation(perm: Tensor, dim: int = 0) -> Tensor:+ """Reverse a permutation tensor along a specified dimension.+ Parameters+ ----+ - `perm`: (LongTensor) the permutation tensor to reverse.+ - `dim`: (int) the dimension of permutation indices. Other dimensions are treated as batch dimensions.++ Returns+ ----+ - (LongTensor) the reversed permutation tensor, such that `reversed_perm[perm] == torch.arange(perm.shape[dim])`++ Notes+ -----+ Equivalent to `torch.argsort(perm, dim=dim)`, but more efficient.+ """+ dim = dim % perm.ndim+ reversed_perm = torch.empty_like(perm)+ indices = torch.arange(perm.shape[dim], device=perm.device)[(None,) * dim + (slice(None),) + (None,) * (perm.ndim - dim - 1)]+ reversed_perm.scatter_(dim, perm, indices.expand_as(perm))+ return reversed_perm++[email protected]_grad()+def large_multinomial(weights: Tensor, num_samples: int, replacement: bool = False) -> Tensor:+ weights = weights.double()+ weights = weights / weights.sum()++ if replacement:+ cum_weights = torch.cumsum(weights, dim=0)+ rand = torch.rand(num_samples, dtype=torch.float64, device=weights.device)+ indices = torch.searchsorted(cum_weights, rand)+ else:+ scores = weights.log() - torch.empty_like(weights).exponential_().log()+ indices = torch.topk(scores, num_samples).indices+ return indicesdiff --git a/model.py b/model.pynew file mode 100644index 0000000..a6021b5--- /dev/null+++ b/model.py@@ -0,0 +1,683 @@+# coding=utf-8++# --------------------------------------------------------+# References:+# SiT: https://github.com/willisma/SiT+# Lightning-DiT: https://github.com/hustvl/LightningDiT+# --------------------------------------------------------+import os+import torch+import torch.nn as nn+import math+import torch.nn.functional as F+from util.model_util import get_2d_sincos_pos_embed, RMSNorm, rotate_half+from util.paths import repo_path++try:+ from flash_attn_interface import flash_attn_func+ FA3_AVAILABLE = True+except ImportError:+ FA3_AVAILABLE = False+++def modulate(x, shift, scale):+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)+++class DynamicRoPE:+ """Applies precomputed 2-D rotary position embeddings to q/k."""+ def __init__(self, cos, sin):+ self.cos = cos+ self.sin = sin++ def __call__(self, t):+ return t * self.cos + rotate_half(t) * self.sin+++class BottleneckPatchEmbed(nn.Module):+ """ Image to Patch Embedding+ """+ def __init__(self, img_size=224, patch_size=16, in_chans=3, pca_dim=768, embed_dim=768, bias=True):+ super().__init__()+ img_size = (img_size, img_size)+ patch_size = (patch_size, patch_size)+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])+ self.img_size = img_size+ self.patch_size = patch_size+ self.num_patches = num_patches++ self.proj1 = nn.Conv2d(in_chans, pca_dim, kernel_size=patch_size, stride=patch_size, bias=False)+ self.proj2 = nn.Conv2d(pca_dim, embed_dim, kernel_size=1, stride=1, bias=bias)++ def forward(self, x):+ B, C, H, W = x.shape+ # Allow any size divisible by patch_size (support rectangular inputs)+ assert H % self.patch_size[0] == 0 and W % self.patch_size[1] == 0, \+ f"Input size ({H}x{W}) must be divisible by patch size ({self.patch_size[0]}x{self.patch_size[1]})"+ x = self.proj2(self.proj1(x)).flatten(2).transpose(1, 2)+ return x+++class TimestepEmbedder(nn.Module):+ """+ Embeds scalar timesteps into vector representations.+ """+ def __init__(self, hidden_size, frequency_embedding_size=256):+ super().__init__()+ self.mlp = nn.Sequential(+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),+ nn.SiLU(),+ nn.Linear(hidden_size, hidden_size, bias=True),+ )+ self.frequency_embedding_size = frequency_embedding_size++ @staticmethod+ def timestep_embedding(t, dim, max_period=10000):+ """+ Create sinusoidal timestep embeddings.+ :param t: a 1-D Tensor of N indices, one per batch element.+ These may be fractional.+ :param dim: the dimension of the output.+ :param max_period: controls the minimum frequency of the embeddings.+ :return: an (N, D) Tensor of positional embeddings.+ """+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py+ half = dim // 2+ freqs = torch.exp(+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half+ ).to(device=t.device)+ args = t[:, None].float() * freqs[None]+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)+ if dim % 2:+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)+ return embedding++ def forward(self, t):+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)+ t_emb = self.mlp(t_freq)+ return t_emb+++def scaled_dot_product_attention_flash3(query, key, value, dropout_p=0.0) -> torch.Tensor:+ """+ Computes scaled dot product attention using the flash_attn library (FA3).++ Args:+ query: Shape (Batch, NumHeads, SeqLen_Q, HeadDim)+ key: Shape (Batch, NumHeads, SeqLen_K, HeadDim)+ value: Shape (Batch, NumHeads, SeqLen_K, HeadDim)++ Returns:+ output: Shape (Batch, NumHeads, SeqLen_Q, HeadDim)+ """+ assert FA3_AVAILABLE, "flash_attn_func is not available. Please install flash attention library."++ # 1. Permute dimensions from (B, H, S, D) to (B, S, H, D)+ # Flash Attention requires the 'Heads' dimension to be 3rd, not 2nd.+ # Mannually cast to bfloat16 for better performance and compatibility.+ q = query.transpose(1, 2).to(torch.bfloat16)+ k = key.transpose(1, 2).to(torch.bfloat16)+ v = value.transpose(1, 2).to(torch.bfloat16)++ # 2. Run Flash Attention+ # Note: softmax_scale defaults to 1/sqrt(d) if not provided.+ assert dropout_p == 0.0, "Flash Attention 3 currently does not support dropout."+ # https://github.com/Dao-AILab/flash-attention/issues/1377+ output = flash_attn_func(+ q, k, v,+ # dropout_p=dropout_p,+ )[0]++ # 3. Permute back to (B, H, S, D)+ return output.transpose(1, 2)+++class Attention(nn.Module):+ def __init__(self, dim, num_heads=8, qkv_bias=True, qk_norm=True, attn_drop=0., proj_drop=0.,+ attention_type='torch'):+ super().__init__()+ self.num_heads = num_heads+ head_dim = dim // num_heads+ self.attention_type = attention_type++ self.q_norm = RMSNorm(head_dim) if qk_norm else nn.Identity()+ self.k_norm = RMSNorm(head_dim) if qk_norm else nn.Identity()++ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)+ self.attn_drop = nn.Dropout(attn_drop)+ self.proj = nn.Linear(dim, dim)+ self.proj_drop = nn.Dropout(proj_drop)++ def forward(self, x, rope):+ B, N, C = x.shape+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)++ q = self.q_norm(q)+ k = self.k_norm(k)++ q = rope(q)+ k = rope(k)++ if self.attention_type == 'torch':+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.attn_drop.p if self.training else 0.,)+ elif self.attention_type == 'flash3':+ x = scaled_dot_product_attention_flash3(q, k, v, dropout_p=self.attn_drop.p if self.training else 0.)+ else:+ raise NotImplementedError(f'Attention type {self.attention_type} not implemented')++ x = x.transpose(1, 2).reshape(B, N, C)++ x = self.proj(x)+ x = self.proj_drop(x)+ return x+++class SwiGLUFFN(nn.Module):+ def __init__(+ self,+ dim: int,+ hidden_dim: int,+ drop=0.0,+ bias=True+ ) -> None:+ super().__init__()+ hidden_dim = int(hidden_dim * 2 / 3)+ self.w12 = nn.Linear(dim, 2 * hidden_dim, bias=bias)+ self.w3 = nn.Linear(hidden_dim, dim, bias=bias)+ self.ffn_dropout = nn.Dropout(drop)++ def forward(self, x):+ x12 = self.w12(x)+ x1, x2 = x12.chunk(2, dim=-1)+ hidden = F.silu(x1) * x2+ return self.w3(self.ffn_dropout(hidden))+++class FinalLayer(nn.Module):+ """+ The final layer of PointDiT.+ """+ def __init__(self, hidden_size, patch_size, out_channels):+ super().__init__()+ self.norm_final = RMSNorm(hidden_size)+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)+ self.adaLN_modulation = nn.Sequential(+ nn.SiLU(),+ nn.Linear(hidden_size, 2 * hidden_size, bias=True)+ )++ def forward(self, x, c):+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)+ x = modulate(self.norm_final(x), shift, scale)+ return self.linear(x)+++class PointDiTBlock(nn.Module):+ def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0,+ attention_type='torch'):+ super().__init__()+ self.norm1 = RMSNorm(hidden_size, eps=1e-6)+ self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, qk_norm=True,+ attn_drop=attn_drop, proj_drop=proj_drop,+ attention_type=attention_type)+ self.norm2 = RMSNorm(hidden_size, eps=1e-6)+ mlp_hidden_dim = int(hidden_size * mlp_ratio)+ self.mlp = SwiGLUFFN(hidden_size, mlp_hidden_dim, drop=proj_drop)++ self.adaLN_modulation = nn.Sequential(+ nn.SiLU(),+ nn.Linear(hidden_size, 6 * hidden_size, bias=True)+ )++ def forward(self, x, c, feat_rope):+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=-1)+ x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope)+ x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))+ return x+++class PointDiT(nn.Module):+ """+ Pixel-space diffusion transformer that denoises a point map, conditioned on+ frozen DINOv3 features of the input image.+ """+ def __init__(+ self,+ input_size=256,+ patch_size=16,+ in_channels=3,+ hidden_size=1024,+ depth=24,+ num_heads=16,+ mlp_ratio=4.0,+ attn_drop=0.0,+ proj_drop=0.0,+ bottleneck_dim=128,+ attention_type='torch',+ feature_embedding_type='dinov3_vitb16',+ dinov3_use_intermediate_layers=True,+ dinov3_num_intermediate_layers=4,+ finetune_feature_embedding=False,+ ):+ super().__init__()+ self.in_channels = in_channels+ self.out_channels = in_channels+ self.patch_size = patch_size+ self.num_heads = num_heads+ self.hidden_size = hidden_size+ self.input_size = input_size+ self.attention_type = attention_type+ self.feature_embedding_type = feature_embedding_type+ self.dinov3_use_intermediate_layers = dinov3_use_intermediate_layers+ self.dinov3_num_intermediate_layers = dinov3_num_intermediate_layers+ self.finetune_feature_embedding = finetune_feature_embedding++ # time and class embed+ self.t_embedder = TimestepEmbedder(hidden_size)++ # frozen pre-trained image encoder producing the conditioning tokens+ if self.feature_embedding_type.startswith('dinov3'):+ vit_type = self.feature_embedding_type.split('_')[-1]+ assert vit_type in ['vits16', 'vits16plus', 'vitb16', 'vitl16', 'vith16plus', 'vit7b16'], f'ViT type {vit_type} not supported for DINOv3 feature embedding'+ sha_dict = {+ 'vits16': '08c60483',+ 'vits16plus': '4057cbaa',+ 'vitb16': '73cec8be',+ 'vitl16': '8aa4cbdd',+ 'vith16plus': '7c1da9a5',+ 'vit7b16': 'a955f4ea',+ }+ sha = sha_dict[vit_type]+ # Configurable so the model can be built on any machine. Defaults assume the+ # DINOv3 checkout in third_party/ and the gated weights in pretrained/dinov3/,+ # both resolved inside the repository rather than against the cwd.+ dinov3_repo = os.environ.get(+ 'DINOV3_REPO', repo_path('third_party/dinov3'))+ dinov3_weights_dir = os.environ.get(+ 'DINOV3_WEIGHTS_DIR', repo_path('pretrained/dinov3'))+ local_weights_path = os.path.join(+ dinov3_weights_dir, f'dinov3_{vit_type}_pretrain_lvd1689m-{sha}.pth')+ if not os.path.isdir(dinov3_repo):+ raise FileNotFoundError(+ f'DINOv3 repository not found at "{dinov3_repo}". Clone it with\n'+ f' git clone https://github.com/facebookresearch/dinov3.git third_party/dinov3\n'+ f'or set DINOV3_REPO to an existing checkout.')+ # NOTE: need to load the weights in the main function due to the random init of the __init__+ if os.path.isfile(local_weights_path):+ self.y_embedder = torch.hub.load(+ dinov3_repo, f'dinov3_{vit_type}', source='local', weights=local_weights_path)+ else:+ # Every PointDiT checkpoint already stores the DINOv3 encoder weights under+ # net.y_embedder.*, so evaluation/inference only needs the architecture here.+ # The gated LVD-1689M weights are required only to train from scratch, and+ # main.py warns about that case (it can see whether a checkpoint is coming).+ self.y_embedder = torch.hub.load(+ dinov3_repo, f'dinov3_{vit_type}', source='local', pretrained=False)+ # freeze DINOv3 parameters+ if not self.finetune_feature_embedding:+ for param in self.y_embedder.parameters():+ param.requires_grad = False++ self.y_embedder.num_patches = self.y_embedder.patch_embed.num_patches++ # compute equally-spaced layer indices for intermediate feature extraction+ if self.dinov3_use_intermediate_layers:+ dinov3_depth = len(self.y_embedder.blocks)+ n = self.dinov3_num_intermediate_layers+ # n equally-spaced layers+ self.dinov3_intermediate_layer_indices = [+ int((i + 1) * dinov3_depth / n) - 1 for i in range(n)+ ]+ self.y_embedder.num_features = self.y_embedder.num_features * n++ else:+ raise NotImplementedError(f'Feature embedding type {self.feature_embedding_type} not implemented')++ # linear embed+ self.x_embedder = BottleneckPatchEmbed(input_size, patch_size, in_channels, bottleneck_dim, hidden_size, bias=True)++ # use fixed sin-cos embedding+ num_patches = self.x_embedder.num_patches+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)++ # position embedding for the conditioning image tokens (frozen sin-cos, added in+ # forward); only needed when the encoder's feature dim differs from the model dim.+ y_feat_dim = self.y_embedder.num_features+ if y_feat_dim != hidden_size:+ self.pos_embed_y = nn.Parameter(torch.zeros(1, num_patches, y_feat_dim), requires_grad=False)+ else:+ self.pos_embed_y = None++ # Image and point tokens are concatenated along the channel dim, then projected+ # back to the model dim (this is PointDiT's conditioning mechanism).+ self.concat_proj = nn.Linear(y_feat_dim + hidden_size, hidden_size, bias=True)++ # transformer+ self.blocks = nn.ModuleList([+ PointDiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio,+ attn_drop=attn_drop if (depth // 4 * 3 > i >= depth // 4) else 0.0,+ proj_drop=proj_drop if (depth // 4 * 3 > i >= depth // 4) else 0.0,+ attention_type=attention_type,+ )+ for i in range(depth)+ ])++ # output head: linear D -> patch_size^2 * 3, unpatchified back to H x W x 3+ self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels)++ self.initialize_weights()++ def initialize_weights(self):+ # Initialize transformer layers:+ def _basic_init(module):+ if isinstance(module, nn.Linear):+ torch.nn.init.xavier_uniform_(module.weight)+ if module.bias is not None:+ nn.init.constant_(module.bias, 0)+ self.apply(_basic_init)++ # Initialize (and freeze) pos_embed by sin-cos embedding:+ pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))++ if hasattr(self, 'pos_embed_y') and self.pos_embed_y is not None:+ # Initialize (and freeze) pos_embed_y by sin-cos embedding:+ # TODO: assuming same number of patches as pointmap+ pos_embed_y = get_2d_sincos_pos_embed(self.pos_embed_y.shape[-1], int(self.x_embedder.num_patches ** 0.5))+ self.pos_embed_y.data.copy_(torch.from_numpy(pos_embed_y).float().unsqueeze(0))++ # Initialize patch_embed like nn.Linear (instead of nn.Conv2d):+ w1 = self.x_embedder.proj1.weight.data+ nn.init.xavier_uniform_(w1.view([w1.shape[0], -1]))+ w2 = self.x_embedder.proj2.weight.data+ nn.init.xavier_uniform_(w2.view([w2.shape[0], -1]))+ nn.init.constant_(self.x_embedder.proj2.bias, 0)++ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)++ # Zero-out adaLN modulation layers:+ for block in self.blocks:+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)++ # Zero-out output layers:+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)++ nn.init.constant_(self.final_layer.linear.weight, 0)+ nn.init.constant_(self.final_layer.linear.bias, 0)++ def interpolate_pos_encoding(self, h, w):+ """+ Interpolate position embeddings to handle variable input sizes.+ h, w: number of patches in height and width+ Returns: pos_embed [1, h*w, C]+ """+ N = h * w+ if N == self.pos_embed.shape[1]:+ # Check if it's the same square size+ orig_size = int(self.pos_embed.shape[1] ** 0.5)+ if h == orig_size and w == orig_size:+ return self.pos_embed++ # Check cache+ cache_key = (h, w)+ if not hasattr(self, '_pos_embed_cache'):+ self._pos_embed_cache = {}+ if cache_key in self._pos_embed_cache:+ return self._pos_embed_cache[cache_key]++ # Get original grid size (square)+ orig_size = int(self.pos_embed.shape[1] ** 0.5)++ # Reshape to 2D grid+ pos_embed = self.pos_embed.reshape(1, orig_size, orig_size, -1).permute(0, 3, 1, 2)++ # Interpolate to new size+ pos_embed = F.interpolate(pos_embed, size=(h, w), mode='bicubic', align_corners=False)++ # Reshape back+ pos_embed = pos_embed.permute(0, 2, 3, 1).reshape(1, h * w, -1)++ if len(self._pos_embed_cache) > 64:+ self._pos_embed_cache.clear()+ self._pos_embed_cache[cache_key] = pos_embed+ return pos_embed++ def interpolate_pos_encoding_y(self, h, w):+ """+ Interpolate y position embeddings (for image features) to handle variable input sizes.+ h, w: number of patches in height and width+ Returns: pos_embed_y [1, h*w, C]+ """+ if self.pos_embed_y is None:+ return self.interpolate_pos_encoding(h, w)++ N = h * w+ if N == self.pos_embed_y.shape[1]:+ orig_size = int(self.pos_embed_y.shape[1] ** 0.5)+ if h == orig_size and w == orig_size:+ return self.pos_embed_y++ # Check cache+ cache_key = (h, w)+ if not hasattr(self, '_pos_embed_y_cache'):+ self._pos_embed_y_cache = {}+ if cache_key in self._pos_embed_y_cache:+ return self._pos_embed_y_cache[cache_key]++ orig_size = int(self.pos_embed_y.shape[1] ** 0.5)+ pos_embed = self.pos_embed_y.reshape(1, orig_size, orig_size, -1).permute(0, 3, 1, 2)+ pos_embed = F.interpolate(pos_embed, size=(h, w), mode='bicubic', align_corners=False)+ pos_embed = pos_embed.permute(0, 2, 3, 1).reshape(1, h * w, -1)++ if len(self._pos_embed_y_cache) > 64:+ self._pos_embed_y_cache.clear()+ self._pos_embed_y_cache[cache_key] = pos_embed+ return pos_embed++ def get_rope_for_size(self, h, w, device):+ """+ Generate rotary position embeddings for given grid size (cached).+ h, w: number of patches in height and width+ Returns: (cos, sin) each of shape [h*w, D]+ """+ cache_key = (h, w, device)+ if not hasattr(self, '_rope_cache'):+ self._rope_cache = {}+ if cache_key in self._rope_cache:+ return self._rope_cache[cache_key]++ half_head_dim = self.hidden_size // self.num_heads // 2+ theta = 10000+ dim = half_head_dim+ freqs = 1. / (theta ** (torch.arange(0, dim, 2, device=device)[:(dim // 2)].float() / dim))++ # Create position indices for h and w+ t_h = torch.arange(h, device=device).float()+ t_w = torch.arange(w, device=device).float()++ # Compute frequencies for each dimension+ freqs_h = torch.einsum('i,j->ij', t_h, freqs) # [h, D/4]+ freqs_w = torch.einsum('i,j->ij', t_w, freqs) # [w, D/4]++ # Repeat for complex representation (interleave)+ freqs_h = freqs_h.repeat_interleave(2, dim=-1) # [h, D/2]+ freqs_w = freqs_w.repeat_interleave(2, dim=-1) # [w, D/2]++ # Create 2D grid: [h, w, D]+ freqs_grid = torch.cat([+ freqs_h[:, None, :].expand(-1, w, -1),+ freqs_w[None, :, :].expand(h, -1, -1)+ ], dim=-1)++ # Flatten to [h*w, D]+ freqs_flat = freqs_grid.reshape(h * w, -1)++ result = (freqs_flat.cos(), freqs_flat.sin())+ if len(self._rope_cache) > 64:+ self._rope_cache.clear()+ self._rope_cache[cache_key] = result+ return result++ def unpatchify(self, x, p, h=None, w=None):+ """+ x: (N, T, patch_size**2 * C)+ h, w: number of patches (if None, assumes square)+ imgs: (N, C, H*p, W*p)+ """+ c = self.out_channels+ if h is None or w is None:+ h = w = int(x.shape[1] ** 0.5)+ assert h * w == x.shape[1], f"h*w ({h}*{w}={h*w}) != num_patches ({x.shape[1]})"++ x = x.reshape(shape=(x.shape[0], h, w, p, p, c))+ x = torch.einsum('nhwpqc->nchpwq', x)+ imgs = x.reshape(shape=(x.shape[0], c, h * p, w * p))+ return imgs++ def forward(self, x, t, y, cached_y_emb=None):+ """+ x: (N, C, H, W)+ t: (N,)+ y: (N,) or (N, C, H, W)+ cached_y_emb: Optional pre-computed y embedding [N, L, C] for sampling efficiency+ """+ B, C, H, W = x.shape+ h_patches = H // self.patch_size+ w_patches = W // self.patch_size++ # Interpolate position embeddings for current size+ pos_embed = self.interpolate_pos_encoding(h_patches, w_patches)++ # Generate RoPE for current size+ rope_cos, rope_sin = self.get_rope_for_size(h_patches, w_patches, x.device)++ # class and time embeddings+ t_emb = self.t_embedder(t)++ # Use cached y_emb if provided (for sampling efficiency), otherwise compute fresh+ if cached_y_emb is not None:+ y_emb = cached_y_emb+ else:+ if self.feature_embedding_type.startswith('dinov3'):+ # DINOv3 image normalization+ y = (y + 1) / 2. # to [0, 1]+ mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(y.device)+ std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(y.device)+ y = (y - mean) / std++ # downsample input when necessary+ if self.patch_size != 16:+ downsample_factor = self.patch_size // 16+ y = F.interpolate(y, scale_factor=1.0 / downsample_factor, mode='bilinear', align_corners=False)++ # DINOv3 feature embedding+ # patch size 16+ if self.dinov3_use_intermediate_layers:+ # Extract features from n equally-spaced layers and concatenate+ intermediate_features = self.y_embedder.get_intermediate_layers(+ y, n=self.dinov3_intermediate_layer_indices, norm=True+ )+ # intermediate_features is a tuple of n tensors, each [B, num_patches, embed_dim]+ y_emb = torch.cat(intermediate_features, dim=-1) # [B, num_patches, n * embed_dim]+ else:+ # Use only final layer features+ y_emb = self.y_embedder.forward_features(y)['x_norm_patchtokens']++ else:+ raise NotImplementedError(f'Feature embedding type {self.feature_embedding_type} not implemented')++ c = t_emb+ # add pos embedding (interpolated for current size) - skip if using cached (already included)+ if cached_y_emb is None:+ pos_embed_y = self.interpolate_pos_encoding_y(h_patches, w_patches)+ y_emb = y_emb + pos_embed_y++ # forward PointDiT+ x = self.x_embedder(x)+ x = x + pos_embed++ # Create dynamic RoPE for current size+ feat_rope = DynamicRoPE(rope_cos, rope_sin)++ # concat image and point tokens along the channel dim, then project to the model dim+ x = torch.cat([y_emb, x], dim=-1) # [N, L, y_feat_dim + C]+ x = self.concat_proj(x) # [N, L, C]++ for block in self.blocks:+ x = block(x, c, feat_rope)++ x = self.final_layer(x, c)++ return self.unpatchify(x, self.patch_size, h_patches, w_patches)++ def extract_y_embedding(self, y, h_patches, w_patches):+ """+ Extract DINOv3 feature embeddings from conditioning image.+ Used for caching during sampling to avoid redundant feature extraction.++ Args:+ y: Conditioning image tensor [B, 3, H, W] in range [-1, 1]+ h_patches: Number of patches in height (for position embedding)+ w_patches: Number of patches in width (for position embedding)++ Returns:+ y_emb: Feature embeddings [B, num_patches, feature_dim]+ """+ if self.feature_embedding_type.startswith('dinov3'):+ # DINOv3 image normalization+ y = (y + 1) / 2. # to [0, 1]+ mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(y.device)+ std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(y.device)+ y = (y - mean) / std++ if self.patch_size != 16:+ downsample_factor = self.patch_size // 16+ y = F.interpolate(y, scale_factor=1.0 / downsample_factor, mode='bilinear', align_corners=False)++ if self.dinov3_use_intermediate_layers:+ intermediate_features = self.y_embedder.get_intermediate_layers(+ y, n=self.dinov3_intermediate_layer_indices, norm=True+ )+ y_emb = torch.cat(intermediate_features, dim=-1)+ else:+ y_emb = self.y_embedder.forward_features(y)['x_norm_patchtokens']++ else:+ raise NotImplementedError(f'Feature embedding type {self.feature_embedding_type} not implemented')++ # For img2point task, add position embedding+ pos_embed_y = self.interpolate_pos_encoding_y(h_patches, w_patches)+ y_emb = y_emb + pos_embed_y++ return y_emb+++def PointDiT_B_16(**kwargs):+ return PointDiT(depth=12, hidden_size=768, num_heads=12, bottleneck_dim=128, patch_size=16, **kwargs)+++def PointDiT_L_16(**kwargs):+ return PointDiT(depth=24, hidden_size=1024, num_heads=16, bottleneck_dim=128, patch_size=16, **kwargs)+++def PointDiT_H_16(**kwargs):+ return PointDiT(depth=32, hidden_size=1280, num_heads=16, bottleneck_dim=256, patch_size=16, **kwargs)+++# The /16 suffix is the patch size; main.py parses it back out of --model.+PointDiT_models = {+ 'PointDiT-B/16': PointDiT_B_16,+ 'PointDiT-L/16': PointDiT_L_16,+ 'PointDiT-H/16': PointDiT_H_16,+}++# Legacy aliases. This repository began as a fork of JiT (see THIRD_PARTY_NOTICES),+# whose architecture names it used until the public release. Accepted so older+# --model strings keep working; prefer the PointDiT-* names above.+PointDiT_models['JiT-B/16'] = PointDiT_B_16+PointDiT_models['JiT-L/16'] = PointDiT_L_16+PointDiT_models['JiT-H/16'] = PointDiT_H_16diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..6b3d280--- /dev/null+++ b/requirements.txt@@ -0,0 +1,17 @@+accelerate>=1.0.0+einops>=0.8.0+imageio>=2.31.0+matplotlib>=3.9.0+numpy>=1.26.0+opencv-python>=4.11.0.86+Pillow>=10.0.0+pyyaml>=6.0+scipy>=1.11.0+tensorboard>=2.15.0+termcolor>=2.4.0+torch>=2.7.0+torchmetrics>=1.4.0+torchvision>=0.22.0+tqdm>=4.66.0+trimesh>=4.0.0+wandb>=0.17.0diff --git a/run.sh b/run.shnew file mode 100644index 0000000..068dbc3--- /dev/null+++ b/run.sh@@ -0,0 +1,99 @@+#!/bin/bash++#+# Minimal end-to-end smoke test for PointDiT: CPU-only, no GPU, no dataset+# download and no pre-trained checkpoint. It trains a randomly initialised model+# for two steps on synthetic data, then samples from the resulting checkpoint.+#+# Run it from the repository root:+#+# bash run.sh+#+# The virtualenv it builds is deleted again on exit, so a full run leaves nothing+# behind. Set POINTDIT_SKIP_VENV=1 to reuse the active interpreter instead of+# building one (much faster when iterating locally, since the wheels below are+# reinstalled from scratch every time otherwise).+#+set -e+set -x++cd "$(dirname "$0")"++# Everything this script creates is torn down here, on failure as well as on+# success. Both paths are guarded so the trap can be installed up front, before+# either exists, and a single handler keeps one trap from replacing the other.+SMOKE_DIR=""+CLEAN_VENV=""+cleanup() {+ if [ -n "${SMOKE_DIR}" ]; then rm -rf "${SMOKE_DIR}"; fi+ if [ -n "${CLEAN_VENV}" ]; then rm -rf "${CLEAN_VENV}"; fi+}+trap cleanup EXIT++if [ -z "${POINTDIT_SKIP_VENV}" ]; then+ # Only remove a virtualenv we built ourselves: a pointdit_env that was already+ # there belongs to the user, and is theirs to keep.+ if [ ! -d pointdit_env ]; then+ CLEAN_VENV="${PWD}/pointdit_env"+ fi+ python3 -m venv pointdit_env+ source ./pointdit_env/bin/activate+ # CPU wheels keep this test small; see README.md for CUDA builds.+ pip install --index-url https://download.pytorch.org/whl/cpu torch torchvision+ pip install -r requirements.txt+fi++# The DINOv3 encoder code is not vendored: torch.hub builds it from a local+# checkout. Only the architecture is needed here, not the gated weights.+if [ ! -d third_party/dinov3 ]; then+ git clone --depth 1 https://github.com/facebookresearch/dinov3.git third_party/dinov3+fi++# Keep the test single-machine and CPU-only regardless of the host.+export CUDA_VISIBLE_DEVICES=""+export OMP_NUM_THREADS=2+export MKL_NUM_THREADS=2++SMOKE_DIR=$(mktemp -d)++# Self-tests of the evaluation metrics (random tensors, CPU, no data needed).+python -m metrics.compute_metrics+python -m metrics.masked_resize++# A few synthetic frames in the layout the Hypersim loader expects.+python tools/make_smoke_data.py --out "${SMOKE_DIR}"++# Stage 1: two training steps from scratch, at a tiny resolution.+# --warmup_epochs 0 is required, else the LR schedule yields 0 for step 0-1.+python main.py \+ --model PointDiT-B/16 --feature_embedding_type dinov3_vits16 --proj_dropout 0.0 \+ --device cpu --img_size 64 --batch_size 2 --num_workers 0 --no_pin_mem \+ --dataset_name hypersim --data_path "${SMOKE_DIR}/data" \+ --depth_intrinsics_resize_height 64 \+ --epochs 1 --warmup_epochs 0 --lr 1e-4 --debug_train_steps 2 \+ --output_dir "${SMOKE_DIR}/out"++# Stage 2: sample from the checkpoint Stage 1 just wrote, on the wild-image path+# (no ground truth and no intrinsics required).+python main.py \+ --model PointDiT-B/16 --feature_embedding_type dinov3_vits16 --proj_dropout 0.0 \+ --device cpu --img_size 64 --num_sampling_steps 2 --gen_bsz 1 \+ --num_workers 0 --no_pin_mem \+ --evaluate_gen --eval_wild_images \+ --eval_wild_images_dir "${SMOKE_DIR}/wild" \+ --pretrained "${SMOKE_DIR}/out/checkpoint-last.pth" \+ --gen_output_root "${SMOKE_DIR}/generation" \+ --output_dir "${SMOKE_DIR}/out"++# The run is only a success if it actually wrote predictions.+OUT_DIR="${SMOKE_DIR}/generation"+test -n "$(find "${OUT_DIR}" -name '*_depth.png' -print -quit)"+test -n "$(find "${OUT_DIR}" -name '*_pointcloud.ply' -print -quit)"+# Wild-image outputs are named after the input, with no index prefix, no doubled extension,+# and no sky-mask panels.+test -n "$(find "${OUT_DIR}" -name 'wild_01_depth.png' -print -quit)"+test -n "$(find "${OUT_DIR}" -name 'wild_01_pointcloud.ply' -print -quit)"+test -z "$(find "${OUT_DIR}" -name '*skymask*' -print -quit)"++# We won't land here if there are errors due to set -e.+echo "*** Success!"diff --git a/scripts/demo_b_512.sh b/scripts/demo_b_512.shnew file mode 100755index 0000000..89ed8f1--- /dev/null+++ b/scripts/demo_b_512.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash++# PointDiT-B (512x512) on your own images. Set IMAGE_DIR below; .jpg/.png, nested dirs are fine.+# Results go to generation/pretrained-pointditb-512/<IMAGE_DIR folder name>/, so+# IMAGE_DIR=assets/demo writes to .../demo/. Each output is named after its input:+# sample0.png -> sample0_depth.png and sample0_pointcloud.ply.++# Any input resolution works: the full frame is resized (aspect ratio kept) to the+# resolution closest to the 32x32 tokens the model was trained on, the prediction runs+# there, then it is resized back to the input resolution for saving. Retarget the token+# budget with --eval_wild_target_tokens, or pass --eval_depth_resize_height 512 to go+# back to resizing the shortest side and center-cropping (which discards the edges).++cd "$(dirname "$0")/.."++IMAGE_DIR=assets/demo+CHECKPOINT=pretrained/pointditb-512.pth++python main.py \+--model PointDiT-B/16 --feature_embedding_type dinov3_vitb16 --proj_dropout 0.0 \+--evaluate_gen --eval_wild_images \+--eval_wild_images_dir ${IMAGE_DIR} \+--img_size 512 --num_sampling_steps 3 \+--pretrained ${CHECKPOINT}diff --git a/scripts/demo_h_512.sh b/scripts/demo_h_512.shnew file mode 100755index 0000000..c7d8954--- /dev/null+++ b/scripts/demo_h_512.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash++# PointDiT-H (512x512) on your own images. Set IMAGE_DIR below; .jpg/.png, nested dirs are fine.+# Results go to generation/pretrained-pointdith-512/<IMAGE_DIR folder name>/, so+# IMAGE_DIR=assets/demo writes to .../demo/. Each output is named after its input:+# sample0.png -> sample0_depth.png and sample0_pointcloud.ply.++# Any input resolution works: the full frame is resized (aspect ratio kept) to the+# resolution closest to the 32x32 tokens the model was trained on, the prediction runs+# there, then it is resized back to the input resolution for saving. Retarget the token+# budget with --eval_wild_target_tokens, or pass --eval_depth_resize_height 512 to go+# back to resizing the shortest side and center-cropping (which discards the edges).++cd "$(dirname "$0")/.."++IMAGE_DIR=assets/demo+CHECKPOINT=pretrained/pointdith-512.pth++python main.py \+--model PointDiT-H/16 --feature_embedding_type dinov3_vith16plus --proj_dropout 0.2 \+--evaluate_gen --eval_wild_images \+--eval_wild_images_dir ${IMAGE_DIR} \+--img_size 512 --num_sampling_steps 3 \+--pretrained ${CHECKPOINT}diff --git a/scripts/demo_l_512.sh b/scripts/demo_l_512.shnew file mode 100755index 0000000..7df8e74--- /dev/null+++ b/scripts/demo_l_512.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash++# PointDiT-L (512x512) on your own images. Set IMAGE_DIR below; .jpg/.png, nested dirs are fine.+# Results go to generation/pretrained-pointditl-512/<IMAGE_DIR folder name>/, so+# IMAGE_DIR=assets/demo writes to .../demo/. Each output is named after its input:+# sample0.png -> sample0_depth.png and sample0_pointcloud.ply.++# Any input resolution works: the full frame is resized (aspect ratio kept) to the+# resolution closest to the 32x32 tokens the model was trained on, the prediction runs+# there, then it is resized back to the input resolution for saving. Retarget the token+# budget with --eval_wild_target_tokens, or pass --eval_depth_resize_height 512 to go+# back to resizing the shortest side and center-cropping (which discards the edges).++cd "$(dirname "$0")/.."++IMAGE_DIR=assets/demo+CHECKPOINT=pretrained/pointditl-512.pth++python main.py \+--model PointDiT-L/16 --feature_embedding_type dinov3_vitl16 --proj_dropout 0.0 \+--evaluate_gen --eval_wild_images \+--eval_wild_images_dir ${IMAGE_DIR} \+--img_size 512 --num_sampling_steps 3 \+--pretrained ${CHECKPOINT}diff --git a/scripts/eval_b_256.sh b/scripts/eval_b_256.shnew file mode 100755index 0000000..9bf5c88--- /dev/null+++ b/scripts/eval_b_256.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash++# Zero-shot benchmark: PointDiT-B at 256x256, 1-step sampling, 7 datasets (3,444 samples).+# Drop --eval_no_save_gen to also write depth panels and point clouds+# --no_remove_sky is needed here: Stage 1 trains on SceneNet with handle_sky: false,+# so sky is never placed at the far plane the default threshold looks for.++cd "$(dirname "$0")/.."++CHECKPOINT=pretrained/pointditb-256-scenenet.pth+EVAL_DATA=datasets/eval++python main.py \+--model PointDiT-B/16 --feature_embedding_type dinov3_vitb16 --proj_dropout 0.0 \+--evaluate_gen --eval_no_save_gen \+--img_size 256 --eval_depth_resize_height 256 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_boundary_datasets HAMMER,iBims-1,Booster \+--no_remove_sky \+--pretrained ${CHECKPOINT}diff --git a/scripts/eval_b_512.sh b/scripts/eval_b_512.shnew file mode 100755index 0000000..50e3e8c--- /dev/null+++ b/scripts/eval_b_512.sh@@ -0,0 +1,18 @@+#!/usr/bin/env bash++# Zero-shot benchmark: PointDiT-B at 512x512, 1-step sampling, 7 datasets (3,444 samples).+# Drop --eval_no_save_gen to also write depth panels and point clouds++cd "$(dirname "$0")/.."++CHECKPOINT=pretrained/pointditb-512.pth+EVAL_DATA=datasets/eval++python main.py \+--model PointDiT-B/16 --feature_embedding_type dinov3_vitb16 --proj_dropout 0.0 \+--evaluate_gen --eval_no_save_gen \+--img_size 512 --eval_depth_resize_height 512 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_boundary_datasets HAMMER,iBims-1,Booster \+--pretrained ${CHECKPOINT}diff --git a/scripts/eval_h_256.sh b/scripts/eval_h_256.shnew file mode 100755index 0000000..1b8903f--- /dev/null+++ b/scripts/eval_h_256.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash++# Zero-shot benchmark: PointDiT-H at 256x256, 1-step sampling, 7 datasets (3,444 samples).+# Drop --eval_no_save_gen to also write depth panels and point clouds+# --no_remove_sky is needed here: Stage 1 trains on SceneNet with handle_sky: false,+# so sky is never placed at the far plane the default threshold looks for.++cd "$(dirname "$0")/.."++CHECKPOINT=pretrained/pointdith-256-scenenet.pth+EVAL_DATA=datasets/eval++python main.py \+--model PointDiT-H/16 --feature_embedding_type dinov3_vith16plus --proj_dropout 0.2 \+--evaluate_gen --eval_no_save_gen \+--img_size 256 --eval_depth_resize_height 256 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_boundary_datasets HAMMER,iBims-1,Booster \+--no_remove_sky \+--pretrained ${CHECKPOINT}diff --git a/scripts/eval_h_512.sh b/scripts/eval_h_512.shnew file mode 100755index 0000000..60bf881--- /dev/null+++ b/scripts/eval_h_512.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash++# Zero-shot benchmark: PointDiT-H at 512x512, 3-step sampling, 7 datasets (3,444 samples).+# Expected (7 datasets, x100): Rel_p 4.39 d1_p 98.01 Rel_d 2.75 d1_d 98.54 BF1 10.44+# Drop --eval_no_save_gen to also write depth panels and point clouds++cd "$(dirname "$0")/.."++CHECKPOINT=pretrained/pointdith-512.pth+EVAL_DATA=datasets/eval++python main.py \+--model PointDiT-H/16 --feature_embedding_type dinov3_vith16plus --proj_dropout 0.2 \+--evaluate_gen --eval_no_save_gen \+--img_size 512 --eval_depth_resize_height 512 --num_sampling_steps 3 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_boundary_datasets HAMMER,iBims-1,Booster \+--pretrained ${CHECKPOINT}diff --git a/scripts/eval_l_256.sh b/scripts/eval_l_256.shnew file mode 100755index 0000000..756413b--- /dev/null+++ b/scripts/eval_l_256.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash++# Zero-shot benchmark: PointDiT-L at 256x256, 1-step sampling, 7 datasets (3,444 samples).+# Drop --eval_no_save_gen to also write depth panels and point clouds+# --no_remove_sky is needed here: Stage 1 trains on SceneNet with handle_sky: false,+# so sky is never placed at the far plane the default threshold looks for.++cd "$(dirname "$0")/.."++CHECKPOINT=pretrained/pointditl-256-scenenet.pth+EVAL_DATA=datasets/eval++python main.py \+--model PointDiT-L/16 --feature_embedding_type dinov3_vitl16 --proj_dropout 0.0 \+--evaluate_gen --eval_no_save_gen \+--img_size 256 --eval_depth_resize_height 256 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_boundary_datasets HAMMER,iBims-1,Booster \+--no_remove_sky \+--pretrained ${CHECKPOINT}diff --git a/scripts/eval_l_512.sh b/scripts/eval_l_512.shnew file mode 100755index 0000000..a509308--- /dev/null+++ b/scripts/eval_l_512.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash++# Zero-shot benchmark: PointDiT-L at 512x512, 3-step sampling, 7 datasets (3,444 samples).+# Expected (7 datasets, x100): Rel_p 4.85 d1_p 97.54 Rel_d 3.09 d1_d 98.25 BF1 10.36+# Drop --eval_no_save_gen to also write depth panels and point clouds++cd "$(dirname "$0")/.."++CHECKPOINT=pretrained/pointditl-512.pth+EVAL_DATA=datasets/eval++python main.py \+--model PointDiT-L/16 --feature_embedding_type dinov3_vitl16 --proj_dropout 0.0 \+--evaluate_gen --eval_no_save_gen \+--img_size 512 --eval_depth_resize_height 512 --num_sampling_steps 3 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_boundary_datasets HAMMER,iBims-1,Booster \+--pretrained ${CHECKPOINT}diff --git a/scripts/train_stage1_256_b.sh b/scripts/train_stage1_256_b.shnew file mode 100755index 0000000..5c4eb03--- /dev/null+++ b/scripts/train_stage1_256_b.sh@@ -0,0 +1,36 @@+#!/usr/bin/env bash++# Stage 1: PointDiT-B pre-training at 256x256 on SceneNet-RGBD.+# Original run: 16 GPUs x batch 256 (effective batch 4096, lr 8e-4), 30 epochs.+# lr = blr * batch_size * num_gpus / 256, so keep that product at 4096 or pass --lr.+# --eval_depth_max_samples 64 keeps the interleaved --online_eval fast: 64 samples per+# dataset (evenly strided, not the first 64) instead of all 3,444. Drop it to score every+# sample, which is what the eval_*.sh scripts do.++cd "$(dirname "$0")/.."++# Multi-node: raise --num_machines, set --machine_rank per node, and add+# --main_process_ip <rank-0 host> --main_process_port 29500 to the launcher.++SCENENET_PATH=datasets/train/scenenet-rgbd+EVAL_DATA=datasets/eval+OUTPUT_DIR=checkpoints/pointdit-b-256+mkdir -p ${OUTPUT_DIR}++accelerate launch --num_processes 8 --num_machines 1 --machine_rank 0 \+--mixed_precision bf16 --dynamo_backend no \+main.py \+--model PointDiT-B/16 --feature_embedding_type dinov3_vitb16 --proj_dropout 0.0 \+--split all \+--img_size 256 --noise_scale 1.0 \+--dataset_name scenenet --data_path ${SCENENET_PATH} \+--depth_intrinsics_resize_height 256 \+--batch_size 256 --blr 5e-5 \+--epochs 30 --warmup_epochs 5 \+--save_ckpt_freq 5 --save_last_freq 1 \+--online_eval --eval_freq 1 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_depth_resize_height 256 --eval_depth_max_samples 64 \+--output_dir ${OUTPUT_DIR} --resume \+2>&1 | tee -a ${OUTPUT_DIR}/train.logdiff --git a/scripts/train_stage1_256_h.sh b/scripts/train_stage1_256_h.shnew file mode 100755index 0000000..36be968--- /dev/null+++ b/scripts/train_stage1_256_h.sh@@ -0,0 +1,37 @@+#!/usr/bin/env bash++# Stage 1: PointDiT-H pre-training at 256x256 on SceneNet-RGBD.+# Original run: 64 GPUs x batch 16 (effective batch 1024, lr 2e-4), 30 epochs.+# lr = blr * batch_size * num_gpus / 256, so keep that product at 1024 or pass --lr.+# The original run used --attention_type flash3; torch is the portable default.+# --eval_depth_max_samples 64 keeps the interleaved --online_eval fast: 64 samples per+# dataset (evenly strided, not the first 64) instead of all 3,444. Drop it to score every+# sample, which is what the eval_*.sh scripts do.++cd "$(dirname "$0")/.."++# Multi-node: raise --num_machines, set --machine_rank per node, and add+# --main_process_ip <rank-0 host> --main_process_port 29500 to the launcher.++SCENENET_PATH=datasets/train/scenenet-rgbd+EVAL_DATA=datasets/eval+OUTPUT_DIR=checkpoints/pointdit-h-256+mkdir -p ${OUTPUT_DIR}++accelerate launch --num_processes 8 --num_machines 1 --machine_rank 0 \+--mixed_precision bf16 --dynamo_backend no \+main.py \+--model PointDiT-H/16 --feature_embedding_type dinov3_vith16plus --proj_dropout 0.2 \+--split all \+--img_size 256 --noise_scale 1.0 \+--dataset_name scenenet --data_path ${SCENENET_PATH} \+--depth_intrinsics_resize_height 256 \+--batch_size 16 --blr 5e-5 \+--epochs 30 --warmup_epochs 5 \+--save_ckpt_freq 5 --save_last_freq 1 \+--online_eval --eval_freq 1 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_depth_resize_height 256 --eval_depth_max_samples 64 \+--output_dir ${OUTPUT_DIR} --resume \+2>&1 | tee -a ${OUTPUT_DIR}/train.logdiff --git a/scripts/train_stage1_256_l.sh b/scripts/train_stage1_256_l.shnew file mode 100755index 0000000..1d7a8e8--- /dev/null+++ b/scripts/train_stage1_256_l.sh@@ -0,0 +1,37 @@+#!/usr/bin/env bash++# Stage 1: PointDiT-L pre-training at 256x256 on SceneNet-RGBD.+# Original run: 16 GPUs x batch 64 (effective batch 1024, lr 2e-4), 30 epochs.+# lr = blr * batch_size * num_gpus / 256, so keep that product at 1024 or pass --lr.+# The original run used --attention_type flash3; torch is the portable default.+# --eval_depth_max_samples 64 keeps the interleaved --online_eval fast: 64 samples per+# dataset (evenly strided, not the first 64) instead of all 3,444. Drop it to score every+# sample, which is what the eval_*.sh scripts do.++cd "$(dirname "$0")/.."++# Multi-node: raise --num_machines, set --machine_rank per node, and add+# --main_process_ip <rank-0 host> --main_process_port 29500 to the launcher.++SCENENET_PATH=datasets/train/scenenet-rgbd+EVAL_DATA=datasets/eval+OUTPUT_DIR=checkpoints/pointdit-l-256+mkdir -p ${OUTPUT_DIR}++accelerate launch --num_processes 8 --num_machines 1 --machine_rank 0 \+--mixed_precision bf16 --dynamo_backend no \+main.py \+--model PointDiT-L/16 --feature_embedding_type dinov3_vitl16 --proj_dropout 0.0 \+--split all \+--img_size 256 --noise_scale 1.0 \+--dataset_name scenenet --data_path ${SCENENET_PATH} \+--depth_intrinsics_resize_height 256 \+--batch_size 64 --blr 5e-5 \+--epochs 30 --warmup_epochs 5 \+--save_ckpt_freq 5 --save_last_freq 1 \+--online_eval --eval_freq 1 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER,iBims-1,Booster \+--eval_depth_resize_height 256 --eval_depth_max_samples 64 \+--output_dir ${OUTPUT_DIR} --resume \+2>&1 | tee -a ${OUTPUT_DIR}/train.logdiff --git a/scripts/train_stage2_512_b.sh b/scripts/train_stage2_512_b.shnew file mode 100755index 0000000..b9f530d--- /dev/null+++ b/scripts/train_stage2_512_b.sh@@ -0,0 +1,39 @@+#!/usr/bin/env bash++# Stage 2: PointDiT-B fine-tuning at 512x512 on the 11-dataset mixture.+# Original run: 64 GPUs x batch 32 (effective batch 2048, lr 8e-4); released at epoch 7.+# lr = blr * batch_size * num_gpus / 256, so keep that product at 2048 or pass --lr.+# --noise_scale 2.0 is the Simple-Diffusion rule vs the 256 base: 1.0 * sqrt(512^2/256^2).+# --eval_depth_max_samples 256 keeps the interleaved --online_eval fast: 256 samples per+# dataset (evenly strided, not the first 256) instead of every sample. Drop it to score+# the full sets, which is what the eval_*.sh scripts do.++cd "$(dirname "$0")/.."++# Multi-node: raise --num_machines, set --machine_rank per node, and add+# --main_process_ip <rank-0 host> --main_process_port 29500 to the launcher.++DATASET_CONFIG=dataloader/configs/res512mix.yaml+EVAL_DATA=datasets/eval+STAGE1_CKPT=checkpoints/pointdit-b-256/checkpoint-last.pth+OUTPUT_DIR=checkpoints/pointdit-b-512+mkdir -p ${OUTPUT_DIR}++accelerate launch --num_processes 8 --num_machines 1 --machine_rank 0 \+--mixed_precision bf16 --dynamo_backend no \+main.py \+--model PointDiT-B/16 --feature_embedding_type dinov3_vitb16 --proj_dropout 0.0 \+--split all \+--img_size 512 --noise_scale 2.0 \+--dataset_config ${DATASET_CONFIG} \+--sky_loss_weight 0.01 --noise_fill_invalid \+--batch_size 32 --blr 1e-4 \+--epochs 8 --warmup_epochs 0 \+--save_ckpt_freq 1 --save_last_freq 1 \+--online_eval --eval_freq 1 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER \+--eval_depth_resize_height 512 --eval_depth_max_samples 256 \+--pretrained ${STAGE1_CKPT} --resize_posemb \+--output_dir ${OUTPUT_DIR} --resume \+2>&1 | tee -a ${OUTPUT_DIR}/train.logdiff --git a/scripts/train_stage2_512_h.sh b/scripts/train_stage2_512_h.shnew file mode 100755index 0000000..c38b885--- /dev/null+++ b/scripts/train_stage2_512_h.sh@@ -0,0 +1,39 @@+#!/usr/bin/env bash++# Stage 2: PointDiT-H fine-tuning at 512x512 on the 11-dataset mixture.+# Original run: 128 GPUs x batch 4 (effective batch 512, lr 2e-4); released at epoch 2.+# lr = blr * batch_size * num_gpus / 256, so keep that product at 512 or pass --lr.+# --noise_scale 2.0 is the Simple-Diffusion rule vs the 256 base: 1.0 * sqrt(512^2/256^2).+# --eval_depth_max_samples 256 keeps the interleaved --online_eval fast: 256 samples per+# dataset (evenly strided, not the first 256) instead of every sample. Drop it to score+# the full sets, which is what the eval_*.sh scripts do.++cd "$(dirname "$0")/.."++# Multi-node: raise --num_machines, set --machine_rank per node, and add+# --main_process_ip <rank-0 host> --main_process_port 29500 to the launcher.++DATASET_CONFIG=dataloader/configs/res512mix.yaml+EVAL_DATA=datasets/eval+STAGE1_CKPT=checkpoints/pointdit-h-256/checkpoint-last.pth+OUTPUT_DIR=checkpoints/pointdit-h-512+mkdir -p ${OUTPUT_DIR}++accelerate launch --num_processes 8 --num_machines 1 --machine_rank 0 \+--mixed_precision bf16 --dynamo_backend no \+main.py \+--model PointDiT-H/16 --feature_embedding_type dinov3_vith16plus --proj_dropout 0.2 \+--split all \+--img_size 512 --noise_scale 2.0 \+--dataset_config ${DATASET_CONFIG} \+--sky_loss_weight 0.01 --noise_fill_invalid \+--batch_size 4 --blr 1e-4 \+--epochs 3 --warmup_epochs 0 \+--save_ckpt_freq 2 --save_last_freq 1 \+--online_eval --eval_freq 1 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER \+--eval_depth_resize_height 512 --eval_depth_max_samples 256 \+--pretrained ${STAGE1_CKPT} --resize_posemb \+--output_dir ${OUTPUT_DIR} --resume \+2>&1 | tee -a ${OUTPUT_DIR}/train.logdiff --git a/scripts/train_stage2_512_l.sh b/scripts/train_stage2_512_l.shnew file mode 100755index 0000000..12ce827--- /dev/null+++ b/scripts/train_stage2_512_l.sh@@ -0,0 +1,39 @@+#!/usr/bin/env bash++# Stage 2: PointDiT-L fine-tuning at 512x512 on the 11-dataset mixture.+# Original run: 64 GPUs x batch 16 (effective batch 1024, lr 4e-4); released at epoch 4.+# lr = blr * batch_size * num_gpus / 256, so keep that product at 1024 or pass --lr.+# --noise_scale 2.0 is the Simple-Diffusion rule vs the 256 base: 1.0 * sqrt(512^2/256^2).+# --eval_depth_max_samples 256 keeps the interleaved --online_eval fast: 256 samples per+# dataset (evenly strided, not the first 256) instead of every sample. Drop it to score+# the full sets, which is what the eval_*.sh scripts do.++cd "$(dirname "$0")/.."++# Multi-node: raise --num_machines, set --machine_rank per node, and add+# --main_process_ip <rank-0 host> --main_process_port 29500 to the launcher.++DATASET_CONFIG=dataloader/configs/res512mix.yaml+EVAL_DATA=datasets/eval+STAGE1_CKPT=checkpoints/pointdit-l-256/checkpoint-last.pth+OUTPUT_DIR=checkpoints/pointdit-l-512+mkdir -p ${OUTPUT_DIR}++accelerate launch --num_processes 8 --num_machines 1 --machine_rank 0 \+--mixed_precision bf16 --dynamo_backend no \+main.py \+--model PointDiT-L/16 --feature_embedding_type dinov3_vitl16 --proj_dropout 0.0 \+--split all \+--img_size 512 --noise_scale 2.0 \+--dataset_config ${DATASET_CONFIG} \+--sky_loss_weight 0.01 --noise_fill_invalid \+--batch_size 16 --blr 1e-4 \+--epochs 5 --warmup_epochs 0 \+--save_ckpt_freq 1 --save_last_freq 1 \+--online_eval --eval_freq 1 --num_sampling_steps 1 \+--eval_depth_dataset --eval_depth_data_root ${EVAL_DATA} \+--eval_depth_dataset_name DIODE,KITTI,NYUv2,ETH3D,HAMMER \+--eval_depth_resize_height 512 --eval_depth_max_samples 256 \+--pretrained ${STAGE1_CKPT} --resize_posemb \+--output_dir ${OUTPUT_DIR} --resume \+2>&1 | tee -a ${OUTPUT_DIR}/train.logdiff --git a/tools/make_smoke_data.py b/tools/make_smoke_data.pynew file mode 100644index 0000000..69ff36a--- /dev/null+++ b/tools/make_smoke_data.py@@ -0,0 +1,105 @@+# coding=utf-8++"""Generate a tiny synthetic dataset so run.sh can exercise PointDiT offline.++This writes a handful of frames in the on-disk layout the Hypersim loader+expects (see ImageDepthIntrinsicsDataset._find_and_split_data_hypersim), plus a+couple of loose images for the wild-image inference path:++ <out>/data/<scene>/<subscene>/<frame:06d>_rgb.png uint8 RGB+ /<frame:06d>_depth.npy float32 z-depth, metres+ /<frame:06d>_cam.npz key 'intrinsics', [3, 3]+ <out>/wild/<name>.png uint8 RGB++The content is a smooth synthetic scene (a tilted ground plane with a box),+not random noise, so the depth is geometrically plausible and the point-map+conversion produces something meaningful to look at. Nothing here is training+data -- it exists purely so the smoke test needs no download.++Usage (from the repository root):+ python tools/make_smoke_data.py --out /tmp/pointdit_smoke+"""++import argparse+import os++import numpy as np+from PIL import Image+++def _scene(height, width, seed):+ """Return (rgb uint8 [H, W, 3], depth float32 [H, W]) for one frame."""+ rng = np.random.RandomState(seed)+ yy, xx = np.meshgrid(np.arange(height), np.arange(width), indexing='ij')+ v = yy / max(height - 1, 1)+ u = xx / max(width - 1, 1)++ # A ground plane receding from the camera: depth grows towards the horizon.+ depth = 2.0 + 6.0 * (1.0 - v)+ # A nearer box occupying a rectangle in the middle of the frame.+ box = (v > 0.45) & (v < 0.8) & (u > 0.3) & (u < 0.7)+ depth[box] = 1.5 + 0.4 * u[box]+ # Mild per-frame variation so frames are not identical.+ depth = depth * (1.0 + 0.05 * rng.randn())+ depth = depth.astype(np.float32)++ # Shade the image from the depth so RGB and geometry are correlated.+ shade = (depth - depth.min()) / max(float(np.ptp(depth)), 1e-6)+ rgb = np.stack([1.0 - shade, 0.35 + 0.4 * u, shade], axis=-1)+ rgb = (np.clip(rgb, 0.0, 1.0) * 255).astype(np.uint8)+ return rgb, depth+++def _intrinsics(height, width):+ """A plausible pinhole K for a ~60 degree horizontal field of view."""+ focal = 0.5 * width / np.tan(np.deg2rad(60.0) / 2.0)+ return np.array([+ [focal, 0.0, width / 2.0],+ [0.0, focal, height / 2.0],+ [0.0, 0.0, 1.0],+ ], dtype=np.float32)+++def main():+ parser = argparse.ArgumentParser(+ description='Write a tiny synthetic dataset for the PointDiT smoke test')+ parser.add_argument('--out', required=True, help='Output directory')+ parser.add_argument('--size', type=int, default=96,+ help='Square image side in pixels')+ parser.add_argument('--scenes', type=int, default=2)+ parser.add_argument('--frames', type=int, default=2,+ help='Frames per scene')+ parser.add_argument('--wild', type=int, default=2,+ help='Loose images for the --eval_wild_images path')+ args = parser.parse_args()++ size = args.size+ K = _intrinsics(size, size)++ seed = 0+ for scene in range(args.scenes):+ subscene_dir = os.path.join(+ args.out, 'data', f'ai_{scene:03d}_001', 'cam_00')+ os.makedirs(subscene_dir, exist_ok=True)+ for frame in range(args.frames):+ rgb, depth = _scene(size, size, seed)+ seed += 1+ stem = os.path.join(subscene_dir, f'{frame:06d}')+ Image.fromarray(rgb).save(f'{stem}_rgb.png')+ np.save(f'{stem}_depth.npy', depth)+ np.savez(f'{stem}_cam.npz', intrinsics=K)++ wild_dir = os.path.join(args.out, 'wild')+ os.makedirs(wild_dir, exist_ok=True)+ for i in range(args.wild):+ rgb, _ = _scene(size, size, 1000 + i)+ Image.fromarray(rgb).save(os.path.join(wild_dir, f'wild_{i:02d}.png'))++ n_train = args.scenes * args.frames+ print(f'Wrote {n_train} training frame(s) under {args.out}/data '+ f'and {args.wild} image(s) under {args.out}/wild '+ f'({size}x{size}).')+++if __name__ == '__main__':+ main()diff --git a/util/log_tb.py b/util/log_tb.pynew file mode 100644index 0000000..f9c83e5--- /dev/null+++ b/util/log_tb.py@@ -0,0 +1,38 @@+# coding=utf-8++import torch+from PIL import Image, ImageDraw+import numpy as np+++def add_text_border(image_tensor, text, border_height=20):+ """+ Args:+ image_tensor: (C, H, W) tensor, normalized 0-1+ text: string to draw+ border_height: height of the text area in pixels+ """+ # 1. Convert Tensor to PIL+ img_np = image_tensor.cpu().detach().numpy().transpose(1, 2, 0)+ img_np = (img_np * 255).astype(np.uint8)+ old_img = Image.fromarray(img_np)+ w, h = old_img.size++ # 2. Create Canvas+ new_img = Image.new(old_img.mode, (w, h + border_height), (255, 255, 255))+ new_img.paste(old_img, (0, border_height))++ # 3. Draw Text Centered+ draw = ImageDraw.Draw(new_img)++ # Define the center point of the border area+ center_x = w / 2+ center_y = border_height / 2++ # anchor="mm" stands for "Middle-Middle" (horizontal & vertical centering)+ # This centers the text exactly at the coordinates provided+ draw.text((center_x, center_y), text, fill=(0, 0, 0), anchor="mm")++ # 4. Return Tensor+ result_np = np.array(new_img)+ return torch.from_numpy(result_np).permute(2, 0, 1).float() / 255.0diff --git a/util/lr_sched.py b/util/lr_sched.pynew file mode 100644index 0000000..75aa95b--- /dev/null+++ b/util/lr_sched.py@@ -0,0 +1,25 @@+# coding=utf-8++# Derived from JiT (https://github.com/LTH14/JiT), MIT License,+# Copyright (c) 2025 Tianhong Li. See THIRD_PARTY_NOTICES.+import math+++def adjust_learning_rate(optimizer, epoch, args):+ """Decay the learning rate with half-cycle cosine after warmup"""+ if epoch < args.warmup_epochs:+ lr = args.lr * epoch / args.warmup_epochs+ else:+ if args.lr_schedule == "constant":+ lr = args.lr+ elif args.lr_schedule == "cosine":+ lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * \+ (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs)))+ else:+ raise NotImplementedError+ for param_group in optimizer.param_groups:+ if "lr_scale" in param_group:+ param_group["lr"] = lr * param_group["lr_scale"]+ else:+ param_group["lr"] = lr+ return lrdiff --git a/util/misc.py b/util/misc.pynew file mode 100644index 0000000..a985bcf--- /dev/null+++ b/util/misc.py@@ -0,0 +1,322 @@+# coding=utf-8++# Derived from JiT (https://github.com/LTH14/JiT), MIT License,+# Copyright (c) 2025 Tianhong Li. MetricLogger/SmoothedValue trace further+# back to DeiT and Detectron2 (Apache-2.0).+# See THIRD_PARTY_NOTICES.+import builtins+import datetime+import os+import time+from collections import defaultdict, deque+from pathlib import Path+import copy++import torch+import torch.distributed as dist+++class SmoothedValue(object):+ """Track a series of values and provide access to smoothed values over a+ window or the global series average.+ """++ def __init__(self, window_size=20, fmt=None):+ if fmt is None:+ fmt = "{median:.4f} ({global_avg:.4f})"+ self.deque = deque(maxlen=window_size)+ self.total = 0.0+ self.count = 0+ self.fmt = fmt++ def update(self, value, n=1):+ self.deque.append(value)+ self.count += n+ self.total += value * n++ def synchronize_between_processes(self):+ """+ Warning: does not synchronize the deque!+ """+ if not is_dist_avail_and_initialized():+ return+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')+ dist.barrier()+ dist.all_reduce(t)+ t = t.tolist()+ self.count = int(t[0])+ self.total = t[1]++ @property+ def median(self):+ d = torch.tensor(list(self.deque))+ return d.median().item()++ @property+ def avg(self):+ d = torch.tensor(list(self.deque), dtype=torch.float32)+ return d.mean().item()++ @property+ def global_avg(self):+ return self.total / self.count++ @property+ def max(self):+ return max(self.deque)++ @property+ def value(self):+ return self.deque[-1]++ def __str__(self):+ return self.fmt.format(+ median=self.median,+ avg=self.avg,+ global_avg=self.global_avg,+ max=self.max,+ value=self.value)+++class MetricLogger(object):+ def __init__(self, delimiter="\t", print_func=print):+ self.meters = defaultdict(SmoothedValue)+ self.delimiter = delimiter+ self.print = print_func++ def update(self, **kwargs):+ for k, v in kwargs.items():+ if v is None:+ continue+ if isinstance(v, torch.Tensor):+ v = v.item()+ assert isinstance(v, (float, int))+ self.meters[k].update(v)++ def __getattr__(self, attr):+ if attr in self.meters:+ return self.meters[attr]+ if attr in self.__dict__:+ return self.__dict__[attr]+ raise AttributeError("'{}' object has no attribute '{}'".format(+ type(self).__name__, attr))++ def __str__(self):+ loss_str = []+ for name, meter in self.meters.items():+ loss_str.append(+ "{}: {}".format(name, str(meter))+ )+ return self.delimiter.join(loss_str)++ def synchronize_between_processes(self):+ for meter in self.meters.values():+ meter.synchronize_between_processes()++ def add_meter(self, name, meter):+ self.meters[name] = meter++ def log_every(self, iterable, print_freq, header=None):+ i = 0+ if not header:+ header = ''+ start_time = time.time()+ end = time.time()+ iter_time = SmoothedValue(fmt='{avg:.4f}')+ data_time = SmoothedValue(fmt='{avg:.4f}')+ space_fmt = ':' + str(len(str(len(iterable)))) + 'd'+ log_msg = [+ header,+ '[{0' + space_fmt + '}/{1}]',+ 'eta: {eta}',+ '{meters}',+ 'time: {time}',+ 'data: {data}'+ ]+ if torch.cuda.is_available():+ log_msg.append('max mem: {memory:.0f}')+ log_msg = self.delimiter.join(log_msg)+ MB = 1024.0 * 1024.0+ for obj in iterable:+ data_time.update(time.time() - end)+ yield obj+ iter_time.update(time.time() - end)+ if i % print_freq == 0 or i == len(iterable) - 1:+ eta_seconds = iter_time.global_avg * (len(iterable) - i)+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))+ if torch.cuda.is_available():+ self.print(log_msg.format(+ i, len(iterable), eta=eta_string,+ meters=str(self),+ time=str(iter_time), data=str(data_time),+ memory=torch.cuda.max_memory_allocated() / MB))+ else:+ self.print(log_msg.format(+ i, len(iterable), eta=eta_string,+ meters=str(self),+ time=str(iter_time), data=str(data_time)))+ i += 1+ end = time.time()+ total_time = time.time() - start_time+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))+ self.print('{} Total time: {} ({:.4f} s / it)'.format(+ header, total_time_str, total_time / len(iterable)))+++def setup_for_distributed(is_master):+ """+ This function disables printing when not in master process+ """+ builtin_print = builtins.print++ def print(*args, **kwargs):+ force = kwargs.pop('force', False)+ force = force or (get_world_size() > 8)+ if is_master or force:+ now = datetime.datetime.now().time()+ builtin_print('[{}] '.format(now), end='') # print with time stamp+ builtin_print(*args, **kwargs)++ builtins.print = print+++def is_dist_avail_and_initialized():+ if not dist.is_available():+ return False+ if not dist.is_initialized():+ return False+ return True+++def get_world_size():+ if not is_dist_avail_and_initialized():+ return 1+ return dist.get_world_size()+++def get_rank():+ if not is_dist_avail_and_initialized():+ return 0+ return dist.get_rank()+++def is_main_process():+ return get_rank() == 0++++def init_distributed_mode(args):+ if args.dist_on_itp:+ args.rank = int(os.environ['OMPI_COMM_WORLD_RANK'])+ args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE'])+ args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])+ args.dist_url = "tcp://%s:%s" % (os.environ['MASTER_ADDR'], os.environ['MASTER_PORT'])+ os.environ['LOCAL_RANK'] = str(args.gpu)+ os.environ['RANK'] = str(args.rank)+ os.environ['WORLD_SIZE'] = str(args.world_size)+ # ["RANK", "WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT", "LOCAL_RANK"]+ elif 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:+ args.rank = int(os.environ["RANK"])+ args.world_size = int(os.environ['WORLD_SIZE'])+ args.gpu = int(os.environ['LOCAL_RANK'])+ elif 'SLURM_PROCID' in os.environ:+ args.rank = int(os.environ['SLURM_PROCID'])+ args.gpu = args.rank % torch.cuda.device_count()+ else:+ print('Not using distributed mode')+ setup_for_distributed(is_master=True) # hack+ args.distributed = False+ return++ args.distributed = True++ torch.cuda.set_device(args.gpu)+ args.dist_backend = 'nccl'+ print('| distributed init (rank {}): {}, gpu {}'.format(+ args.rank, args.dist_url, args.gpu), flush=True)+ torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,+ world_size=args.world_size, rank=args.rank)+ torch.distributed.barrier()+ setup_for_distributed(args.rank == 0)+++def add_weight_decay(model, weight_decay=0, skip_list=(), feature_embedding_lr_scale=0.0):+ decay = []+ no_decay = []+ fe_decay = []+ fe_no_decay = []+ for name, param in model.named_parameters():+ if not param.requires_grad:+ continue # frozen weights+ is_fe = 'y_embedder' in name and feature_embedding_lr_scale > 0+ if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list or 'diffloss' in name:+ if is_fe:+ fe_no_decay.append(param)+ else:+ no_decay.append(param) # no weight decay on bias, norm and diffloss+ else:+ if is_fe:+ fe_decay.append(param)+ else:+ decay.append(param)+ groups = [+ {'params': no_decay, 'weight_decay': 0.},+ {'params': decay, 'weight_decay': weight_decay}]+ if fe_no_decay:+ groups.append({'params': fe_no_decay, 'weight_decay': 0., 'lr_scale': feature_embedding_lr_scale})+ if fe_decay:+ groups.append({'params': fe_decay, 'weight_decay': weight_decay, 'lr_scale': feature_embedding_lr_scale})+ return groups+++def save_model(args, model_without_ddp, optimizer, epoch, epoch_name=None, global_step=None, resume_epoch=None):+ if epoch_name is None:+ epoch_name = str(epoch)+ output_dir = Path(args.output_dir)+ checkpoint_path = output_dir / ('checkpoint-%s.pth' % epoch_name)++ to_save = {+ 'model': model_without_ddp.state_dict(),+ 'optimizer': optimizer.state_dict(),+ 'epoch': epoch,+ 'global_step': global_step,+ # Epoch to resume INTO. Sub-epoch checkpoints set this to the in-progress+ # epoch (re-run it); end-of-epoch saves leave it None -> resume at epoch+1.+ 'resume_epoch': resume_epoch,+ 'args': args,+ }++ # ema+ ema_state_dict1 = copy.deepcopy(model_without_ddp.state_dict())+ ema_state_dict2 = copy.deepcopy(model_without_ddp.state_dict())+ for i, (name, _value) in enumerate(model_without_ddp.named_parameters()):+ assert name in ema_state_dict1 and name in ema_state_dict2+ ema_state_dict1[name] = model_without_ddp.ema_params1[i]+ ema_state_dict2[name] = model_without_ddp.ema_params2[i]+ to_save['model_ema1'] = ema_state_dict1+ to_save['model_ema2'] = ema_state_dict2++ # Atomic save with a rolling backup so a job killed mid-write (e.g. on a+ # preemptible cluster) can never leave a truncated checkpoint-last.pth.+ if is_main_process():+ checkpoint_path = Path(checkpoint_path)+ tmp_path = checkpoint_path.with_suffix(checkpoint_path.suffix + '.tmp')+ prev_path = output_dir / ('checkpoint-%s-prev.pth' % epoch_name)+ torch.save(to_save, tmp_path) # fully write new ckpt to a temp file+ if checkpoint_path.exists():+ os.replace(checkpoint_path, prev_path) # rotate last-good -> prev (instant, same FS)+ os.replace(tmp_path, checkpoint_path) # atomic publish of the new checkpoint+++def all_reduce_mean(x):+ world_size = get_world_size()+ if world_size > 1:+ # NCCL needs the tensor on the GPU; gloo (CPU-only training) needs it on+ # the host, so follow whatever this process actually has.+ x_reduce = torch.tensor(+ x, device='cuda' if torch.cuda.is_available() else 'cpu')+ dist.all_reduce(x_reduce)+ x_reduce /= world_size+ return x_reduce.item()+ else:+ return x\ No newline at end of filediff --git a/util/model_util.py b/util/model_util.pynew file mode 100644index 0000000..4ef4857--- /dev/null+++ b/util/model_util.py@@ -0,0 +1,88 @@+# coding=utf-8++# Derived from JiT (https://github.com/LTH14/JiT), MIT License,+# Copyright (c) 2025 Tianhong Li. See THIRD_PARTY_NOTICES.+# --------------------------------------------------------+# References:+# Lightning-DiT: https://github.com/hustvl/LightningDiT+# --------------------------------------------------------++import torch+from torch import nn+import numpy as np++from einops import rearrange+++def rotate_half(x):+ x = rearrange(x, '... (d r) -> ... d r', r = 2)+ x1, x2 = x.unbind(dim = -1)+ x = torch.stack((-x2, x1), dim = -1)+ return rearrange(x, '... d r -> ... (d r)')+++class RMSNorm(nn.Module):+ def __init__(self, hidden_size, eps=1e-6):+ """+ LlamaRMSNorm is equivalent to T5LayerNorm+ """+ super().__init__()+ self.weight = nn.Parameter(torch.ones(hidden_size))+ self.variance_epsilon = eps++ def forward(self, hidden_states):+ input_dtype = hidden_states.dtype+ hidden_states = hidden_states.to(torch.float32)+ variance = hidden_states.pow(2).mean(-1, keepdim=True)+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)+ return (self.weight * hidden_states).to(input_dtype)+++def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):+ """+ grid_size: int of the grid height and width+ return:+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)+ """+ grid_h = np.arange(grid_size, dtype=np.float32)+ grid_w = np.arange(grid_size, dtype=np.float32)+ grid = np.meshgrid(grid_w, grid_h) # here w goes first+ grid = np.stack(grid, axis=0)++ grid = grid.reshape([2, 1, grid_size, grid_size])+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)+ if cls_token and extra_tokens > 0:+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)+ return pos_embed+++def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):+ assert embed_dim % 2 == 0++ # use half of dimensions to encode grid_h+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)++ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)+ return emb+++def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):+ """+ embed_dim: output dimension for each position+ pos: a list of positions to be encoded: size (M,)+ out: (M, D)+ """+ assert embed_dim % 2 == 0+ omega = np.arange(embed_dim // 2, dtype=np.float64)+ omega /= embed_dim / 2.+ omega = 1. / 10000**omega # (D/2,)++ pos = pos.reshape(-1) # (M,)+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product++ emb_sin = np.sin(out) # (M, D/2)+ emb_cos = np.cos(out) # (M, D/2)++ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)+ return emb\ No newline at end of filediff --git a/util/paths.py b/util/paths.pynew file mode 100644index 0000000..f8c264b--- /dev/null+++ b/util/paths.py@@ -0,0 +1,19 @@+# coding=utf-8++"""Paths that resolve against the repository, not the current directory.++Constants the code hardcodes -- ``pretrained/dinov3``, ``generation`` -- go+through :func:`repo_path` instead of being used as bare relative strings, so a+command launched from somewhere other than the repository root still finds the+``pretrained`` and ``datasets`` symlinks that live next to this package.+"""++import os++# The repository root: this file is <repo>/util/paths.py, so go up two levels.+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++def repo_path(*parts):+ """Join `parts` onto the repository root and return an absolute path."""+ return os.path.join(REPO_ROOT, *parts)diff --git a/util/resize_posemb.py b/util/resize_posemb.pynew file mode 100644index 0000000..a22ebd1--- /dev/null+++ b/util/resize_posemb.py@@ -0,0 +1,114 @@+# coding=utf-8++import torch+import torch.nn.functional as F+import math+++def resize_vit_pos_embed(checkpoint_model, new_num_patches=64, key='net.pos_embed'):+ """+ Resizes the positional embedding in a checkpoint dictionary.++ Args:+ checkpoint_model: The dict from torch.load+ new_num_patches: Target number of patches (e.g., 64 for 256x256 image with 32x32 patches)+ key: The key in the dict pointing to the pos_embed+ """+ if key not in checkpoint_model:+ print(f"Key {key} not found in checkpoint.")+ return checkpoint_model++ pos_embed_checkpoint = checkpoint_model[key] # Shape: [1, Old_N, Dim]+ embedding_size = pos_embed_checkpoint.shape[-1]++ # Calculate grid sizes+ # We check if there's an extra token (CLS token)+ # Standard ViT: num_patches = grid_size * grid_size+ # If Old_N is not a perfect square, we assume 1 extra token (CLS)+ old_num_tokens = pos_embed_checkpoint.shape[1]+ # TODO: here we assume square images and patches+ new_grid_size = int(math.sqrt(new_num_patches))++ assert new_grid_size * new_grid_size == new_num_patches, "new_num_patches must be a perfect square."++ # Determine if there is a CLS token by checking if old_num_tokens is a perfect square+ old_grid_size = int(math.sqrt(old_num_tokens))+ assert old_grid_size * old_grid_size == old_num_tokens, "Old number of tokens must be a perfect square or have one extra token."+ if old_grid_size * old_grid_size == old_num_tokens:+ num_extra_tokens = 0+ else:+ num_extra_tokens = old_num_tokens - (int(math.sqrt(old_num_tokens - 1))**2)+ old_grid_size = int(math.sqrt(old_num_tokens - num_extra_tokens))++ print(f"Resizing {key}: {old_grid_size}x{old_grid_size} -> {new_grid_size}x{new_grid_size} "+ f"({num_extra_tokens} extra tokens)")++ # 1. Separate extra tokens and patch tokens+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]+ patch_tokens = pos_embed_checkpoint[:, num_extra_tokens:]++ # 2. Reshape to [1, C, H, W] for interpolation+ patch_tokens = patch_tokens.reshape(1, old_grid_size, old_grid_size, embedding_size).permute(0, 3, 1, 2)++ # 3. Interpolate+ patch_tokens = F.interpolate(+ patch_tokens,+ size=(new_grid_size, new_grid_size),+ mode='bicubic',+ align_corners=False+ )++ # 4. Reshape back to [1, New_N, C]+ patch_tokens = patch_tokens.permute(0, 2, 3, 1).flatten(1, 2)++ # 5. Concatenate and update+ checkpoint_model[key] = torch.cat((extra_tokens, patch_tokens), dim=1)++ return checkpoint_model+++def resize_patch_embed_and_final_layer(checkpoint_model, old_patch_size, new_patch_size, out_channels=3):+ """+ Resize patch embedding kernel and final layer when changing patch sizes.++ Args:+ checkpoint_model: checkpoint state dict+ old_patch_size: original patch size (e.g., 16)+ new_patch_size: target patch size (e.g., 32)+ out_channels: number of output channels (default 3 for RGB)+ """+ # Resize x_embedder.proj1.weight: [C_out, C_in, old_ps, old_ps] -> [C_out, C_in, new_ps, new_ps]+ key = 'net.x_embedder.proj1.weight'+ if key in checkpoint_model:+ old_weight = checkpoint_model[key]+ new_weight = F.interpolate(old_weight, size=(new_patch_size, new_patch_size),+ mode='bicubic', align_corners=False)+ checkpoint_model[key] = new_weight+ print(f"Resized {key}: {old_weight.shape} -> {new_weight.shape}")++ # Resize final_layer.linear.weight: [old_ps*old_ps*C, hidden] -> [new_ps*new_ps*C, hidden]+ key = 'net.final_layer.linear.weight'+ if key in checkpoint_model:+ old_weight = checkpoint_model[key]+ hidden_size = old_weight.shape[1]+ old_weight_4d = old_weight.view(old_patch_size, old_patch_size, out_channels, hidden_size)+ old_weight_4d = old_weight_4d.permute(2, 3, 0, 1)+ new_weight = F.interpolate(old_weight_4d, size=(new_patch_size, new_patch_size),+ mode='bicubic', align_corners=False)+ new_weight = new_weight.permute(2, 3, 0, 1).reshape(-1, hidden_size)+ checkpoint_model[key] = new_weight+ print(f"Resized {key}: {old_weight.shape} -> {new_weight.shape}")++ # Resize final_layer.linear.bias: [old_ps*old_ps*C] -> [new_ps*new_ps*C]+ key = 'net.final_layer.linear.bias'+ if key in checkpoint_model:+ old_bias = checkpoint_model[key]+ old_bias_4d = old_bias.view(old_patch_size, old_patch_size, out_channels).permute(2, 0, 1).unsqueeze(0)+ new_bias = F.interpolate(old_bias_4d, size=(new_patch_size, new_patch_size),+ mode='bicubic', align_corners=False)+ new_bias = new_bias.squeeze(0).permute(1, 2, 0).reshape(-1)+ checkpoint_model[key] = new_bias+ print(f"Resized {key}: {old_bias.shape} -> {new_bias.shape}")++ return checkpoint_model+diff --git a/util/viz_boundary.py b/util/viz_boundary.pynew file mode 100644index 0000000..01a8df9--- /dev/null+++ b/util/viz_boundary.py@@ -0,0 +1,61 @@+# coding=utf-8++import numpy as np++from metrics.boundary_metrics import fgbg_depth_thinned, invert_depth+++def viz_boundary_comparison(+ pred_depth: np.ndarray,+ gt_depth: np.ndarray,+ threshold: float = 1.10,+) -> np.ndarray:+ """Visualize predicted vs GT boundary edges.++ Args:+ pred_depth: Predicted depth map [H, W]+ gt_depth: Ground truth depth map [H, W]+ threshold: Depth ratio threshold for boundary detection (default 1.10)++ Returns:+ RGB image [H, W, 3] with:+ - Red: predicted boundaries only (false positives)+ - Green: GT boundaries only (false negatives)+ - Yellow: matched boundaries (true positives)+ """+ h, w = pred_depth.shape++ # Get boundary masks (4 directions)+ # left/right have shape (H, W-1), top/bottom have shape (H-1, W)+ pred_l, pred_t, pred_r, pred_b = fgbg_depth_thinned(invert_depth(pred_depth), threshold)+ gt_l, gt_t, gt_r, gt_b = fgbg_depth_thinned(invert_depth(gt_depth), threshold)++ # Pad each direction to full size (H, W)+ # Left/right: pad 1 column on right+ # Top/bottom: pad 1 row on bottom+ pred_l = np.pad(pred_l, ((0, 0), (0, 1)), mode='constant')+ pred_r = np.pad(pred_r, ((0, 0), (0, 1)), mode='constant')+ pred_t = np.pad(pred_t, ((0, 1), (0, 0)), mode='constant')+ pred_b = np.pad(pred_b, ((0, 1), (0, 0)), mode='constant')++ gt_l = np.pad(gt_l, ((0, 0), (0, 1)), mode='constant')+ gt_r = np.pad(gt_r, ((0, 0), (0, 1)), mode='constant')+ gt_t = np.pad(gt_t, ((0, 1), (0, 0)), mode='constant')+ gt_b = np.pad(gt_b, ((0, 1), (0, 0)), mode='constant')++ # Combine all directions+ pred_boundary = pred_l | pred_t | pred_r | pred_b+ gt_boundary = gt_l | gt_t | gt_r | gt_b++ # Create RGB visualization+ viz = np.zeros((h, w, 3), dtype=np.uint8)++ matched = pred_boundary & gt_boundary # True positives+ pred_only = pred_boundary & ~gt_boundary # False positives+ gt_only = gt_boundary & ~pred_boundary # False negatives++ viz[matched] = [255, 255, 0] # Yellow - correct+ viz[pred_only] = [255, 0, 0] # Red - false positive+ viz[gt_only] = [0, 255, 0] # Green - false negative++ return vizdiff --git a/util/viz_depth.py b/util/viz_depth.pynew file mode 100644index 0000000..2d0b11f--- /dev/null+++ b/util/viz_depth.py@@ -0,0 +1,116 @@+# coding=utf-8++import torch+import numpy as np+import matplotlib as mpl+import matplotlib.cm as cm+++def viz_depth_tensor(disp, return_numpy=True, colormap="plasma", viz_inverse_depth=True, shifted_depth=False):+ # Convert input to a NumPy array+ if isinstance(disp, torch.Tensor):+ disp_np = disp.detach().cpu().numpy()+ elif isinstance(disp, np.ndarray):+ disp_np = disp+ else:+ raise TypeError(+ "Input must be a torch.Tensor or a numpy.ndarray, "+ f"but got {type(disp)}"+ )++ # Ensure the input is 2D+ if disp_np.ndim == 3:+ disp_np = disp_np.squeeze()+ if disp_np.ndim != 2:+ raise ValueError("Depth/Disparity array must be 2-dimensional.")++ # in the dataloader, the point is shift to have zero center+ # normalize when visualizing+ if shifted_depth:+ # For zero-centered model output (unknown scale/shift):+ #+ # Step 1 – shift raw depth to positive by subtracting p_low, preserving scale ratios.+ # We do NOT normalize to [0,1] here because that destroys scale: inverting values+ # already compressed into [1e-3, 1.001] produces a heavily skewed distribution+ # where 75%+ of pixels collapse into the bottom 2% of the colormap.+ finite_vals = disp_np[np.isfinite(disp_np)]+ if finite_vals.size == 0:+ H, W = disp_np.shape+ black = np.zeros((H, W, 3), dtype=np.uint8)+ if return_numpy:+ return black+ return torch.from_numpy(black).permute(2, 0, 1)+ p_low = np.percentile(finite_vals, 0.1)+ p_high = np.percentile(finite_vals, 99.9)+ # Shift so the 2nd-percentile depth becomes 1e-3 (all values positive, scale preserved)+ disp_shifted = np.clip(disp_np, p_low, p_high) - p_low + 1e-3++ # Step 2 – take inverse depth (near=small depth → large inverse → bright)+ inv_disp = 1.0 / disp_shifted # all positive since disp_shifted >= 1e-3++ # Step 3 – normalize by percentile, same as the non-shifted path.+ # Two degenerate cases have to be handled or this writes NaNs into the+ # PNG: np.clip above preserves NaN (hence the nan-aware statistics), and+ # a constant prediction gives vmin == vmax. Note that nudging by a fixed+ # 1e-6 is not enough to fix the latter -- float32 spacing near the+ # typical inverse-depth magnitude of 1e3 is ~6e-5, so the nudge rounds+ # away and leaves a 0/0. Compute the span in float64 instead.+ vmin = float(np.nanmin(inv_disp))+ vmax = float(np.nanpercentile(inv_disp, 95))+ if not np.isfinite(vmin):+ vmin = 0.0+ span = vmax - vmin+ if not np.isfinite(span) or span <= 1e-12:+ span = 1.0 # constant depth -> flat image rather than NaNs+ normalized = np.nan_to_num(+ (inv_disp.astype(np.float64) - vmin) / span, nan=0.0).clip(0, 1)++ # Step 4 – apply colormap and return early+ cmap_fn = mpl.colormaps[colormap]+ colormapped_im = (cmap_fn(normalized)[:, :, :3] * 255).astype(np.uint8)+ if return_numpy:+ return colormapped_im+ return torch.from_numpy(colormapped_im).permute(2, 0, 1)++ # --- KEY CHANGE: INVERSE DEPTH VISUALIZATION ---+ if viz_inverse_depth:+ # Create a mask for valid (positive) depth values+ valid_mask = disp_np > 0++ # Calculate inverse depth only for valid pixels+ disp_viz = np.zeros_like(disp_np, dtype=np.float32)+ disp_viz[valid_mask] = 1.0 / disp_np[valid_mask]+ else:+ disp_viz = disp_np+ # -----------------------------------------------++ # Handle NaNs and Infs for normalization (now on the inverse depth data)+ final_valid_mask = np.isfinite(disp_viz) & (disp_viz > 0)++ if not np.any(final_valid_mask):+ H, W = disp_np.shape[:2]+ black = np.zeros((H, W, 3), dtype=np.uint8)+ if return_numpy:+ return black+ return torch.from_numpy(black).permute(2, 0, 1)++ disp_valid = disp_viz[final_valid_mask]++ vmin = disp_valid.min()+ vmax = np.percentile(disp_valid, 95)++ if vmax <= vmin + 1e-6:+ vmax = vmin + 1e-6++ # Normalization and Colormapping+ normalizer = mpl.colors.Normalize(vmin=vmin, vmax=vmax)+ mapper = cm.ScalarMappable(norm=normalizer, cmap=colormap)++ # Map values to RGB [H, W, 3]+ # Use the disp_viz array (inverse depth) for colormapping+ colormapped_im = (mapper.to_rgba(disp_viz)[:, :, :3] * 255).astype(np.uint8)++ if return_numpy:+ return colormapped_im++ return torch.from_numpy(colormapped_im).permute(2, 0, 1)diff --git a/util/viz_pointcloud.py b/util/viz_pointcloud.pynew file mode 100644index 0000000..7fbe75a--- /dev/null+++ b/util/viz_pointcloud.py@@ -0,0 +1,210 @@+# coding=utf-8++import numpy as np+import trimesh+++def save_generated_gt_point_cloud(gen_cloud, gen_color, gt_cloud, gt_color, filename="comparison.ply", spacing=None, scale_factor=0.2, axis=0, mask=None, gt_mask=None):+ """+ Combines exactly two HxWx3 point clouds (Generated + GT) into a single PLY file.+ Applies offset based on center-to-center distance.++ Args:+ gen_cloud (np.array): Generated cloud, shape (H, W, 3).+ gen_color (np.array): Generated colors, shape (H, W, 3).+ gt_cloud (np.array): Ground Truth cloud, shape (H, W, 3).+ gt_color (np.array): Ground Truth colors, shape (H, W, 3).+ filename (str): Output file path.+ spacing (float or None):+ If Float: Target DISTANCE between centers.+ If None: Auto-calculated to ensure no overlap with padding.+ scale_factor (float or None):+ Relative padding size (gap = average_width * scale_factor).+ If None, auto-selects based on object size.+ axis (int): Axis to apply offset (0=X, 1=Y, 2=Z).+ mask (np.array or None): Optional (H, W) bool array for gen cloud — True = keep.+ gt_mask (np.array or None): Optional (H, W) bool array for gt cloud — True = keep.+ """++ # 1. Flatten Data+ gen_pts = gen_cloud.reshape(-1, 3)+ gen_rgb = gen_color.reshape(-1, 3)+ gt_pts = gt_cloud.reshape(-1, 3)+ gt_rgb = gt_color.reshape(-1, 3)++ if mask is not None:+ flat_mask = mask.reshape(-1)+ gen_pts = gen_pts[flat_mask]+ gen_rgb = gen_rgb[flat_mask]+ if gt_mask is not None:+ flat_gt_mask = gt_mask.reshape(-1)+ gt_pts = gt_pts[flat_gt_mask]+ gt_rgb = gt_rgb[flat_gt_mask]++ if len(gen_pts) == 0 or len(gt_pts) == 0:+ print("Error: One of the point clouds is empty.")+ return++ # 2. Calculate Dimensions & Centers+ # We need min/max and center on the specific axis we are stacking along+ gen_min, gen_max = gen_pts[:, axis].min(), gen_pts[:, axis].max()+ gt_min, gt_max = gt_pts[:, axis].min(), gt_pts[:, axis].max()++ gen_width = gen_max - gen_min+ gt_width = gt_max - gt_min+ avg_width = (gen_width + gt_width) / 2.0++ gen_center = (gen_min + gen_max) / 2.0+ gt_center = (gt_min + gt_max) / 2.0++ # 3. Determine Target Center Distance+ dist_between_centers = 0.0++ if spacing is not None:+ # User specified fixed distance between centers+ dist_between_centers = spacing+ else:+ # Auto-calculate based on size+ if scale_factor is None:+ # If objects are small (e.g. normalized coords < 5.0), use bigger relative gap+ scale_factor = 0.5 if avg_width < 5.0 else 0.2++ # We want: Center_Dist = Half_W_Gen + Half_W_GT + Gap+ gap = avg_width * scale_factor+ dist_between_centers = (gen_width / 2.0) + (gt_width / 2.0) + gap++ # 4. Apply Offsets+ # Target GT Center = Gen Center + Distance+ target_gt_center = gen_center + dist_between_centers+ offset_val = target_gt_center - gt_center++ translation = np.zeros(3)+ translation[axis] = offset_val++ translated_gt_pts = gt_pts + translation++ # 5. Combine+ combined_pts = np.vstack([gen_pts, translated_gt_pts])++ # Handle Colors (Ensure uint8)+ def to_uint8(c):+ if c.dtype.kind == 'f':+ return (c * 255).astype(np.uint8)+ return c.astype(np.uint8)++ combined_colors = np.vstack([to_uint8(gen_rgb), to_uint8(gt_rgb)])++ # 6. Save+ pcd = trimesh.PointCloud(vertices=combined_pts, colors=combined_colors)++ # 2. Define a "flip" matrix (OpenCV -> OpenGL/Standard 3D)+ # This flips Y and Z to make Y-up and Z-out+ flip_transform = np.array([+ [1, 0, 0, 0],+ [0, -1, 0, 0],+ [0, 0, -1, 0],+ [0, 0, 0, 1]+ ])++ # 3. Apply the transform+ pcd.apply_transform(flip_transform)++ pcd.export(filename)+++def depth_flying_points(depth, rtol=0.04, kernel_size=3, mid_threshold=0.5):+ """+ Flags "flying point" pixels — those whose depth is intermediate between the+ local foreground and background depth.++ Pixels at true depth discontinuities (fine-grained edges) whose depth is+ close to either the local min or max are NOT flagged, since they represent+ real foreground/background boundaries predicted by the model.++ Args:+ depth: (H, W) numpy array+ rtol: Relative tolerance for depth edge detection (default 0.04)+ kernel_size: Neighborhood size (default 3)+ mid_threshold: Normalized distance from midpoint below which a pixel+ is considered intermediate (flying point). Default 0.5+ means: depth within [min + 0.25*range, max - 0.25*range]+ is a flying point. Depth close to min or max is a real edge.++ Returns:+ (H, W) bool array — True only for flying points (not fine-grained edges)+ """+ from scipy.ndimage import maximum_filter, minimum_filter++ depth_clean = np.where(np.isfinite(depth), depth, 0.0)+ local_max = maximum_filter(depth_clean, size=kernel_size)+ local_min = minimum_filter(depth_clean, size=kernel_size)++ # Step 1: detect all depth discontinuities (same as depth_edge)+ rel_range = np.zeros_like(depth)+ valid = local_max > 0+ np.divide(local_max - local_min, local_max, out=rel_range, where=valid)+ is_edge = rel_range > rtol++ # Step 2: among edge pixels, check if depth is intermediate (flying point)+ # or close to one extreme (fine-grained edge).+ # Normalize distance from midpoint: 0 = at midpoint, 1 = at an extreme.+ local_range = local_max - local_min+ mid_depth = (local_max + local_min) / 2.0+ dist_from_mid = np.abs(depth_clean - mid_depth)+ normalized_dist = np.ones_like(dist_from_mid)+ valid_range = local_range > 0+ np.divide(dist_from_mid, local_range / 2.0, out=normalized_dist, where=valid_range)++ # Flying point: depth closer to midpoint than to either extreme+ is_flying_point = normalized_dist < mid_threshold++ return is_edge & is_flying_point+++def save_single_point_cloud(points, colors, filename, transform_to_gl=True, mask=None):+ """+ Save a single point cloud as PLY file.++ Args:+ points: (H, W, 3) or (3, H, W) NumPy array of 3D points+ colors: (H, W, 3) NumPy array of RGB colors in [0, 1] range+ filename: Output .ply file path+ transform_to_gl: If True, apply OpenGL coordinate transform (flip Y and Z)+ mask: Optional (H, W) bool array — True = keep pixel, False = discard+ """+ # Handle both (H, W, 3) and (3, H, W) input formats+ if points.shape[0] == 3 and len(points.shape) == 3:+ # Input is (3, H, W), transpose to (H, W, 3)+ points = points.transpose(1, 2, 0)++ # Flatten to (N, 3)+ flat_points = points.reshape(-1, 3)+ flat_colors = colors.reshape(-1, 3)++ # Apply spatial mask (e.g. to remove depth-edge flying points)+ if mask is not None:+ flat_mask = mask.reshape(-1)+ flat_points = flat_points[flat_mask]+ flat_colors = flat_colors[flat_mask]++ if len(flat_points) == 0:+ print(f"Warning: No points to save to {filename}")+ return++ # Ensure colors are uint8 0-255 for trimesh+ if flat_colors.dtype.kind == 'f':+ if flat_colors.max() <= 1.0 + 1e-5:+ flat_colors = (flat_colors * 255).astype(np.uint8)+ else:+ flat_colors = flat_colors.astype(np.uint8)++ # Apply coordinate system transformation if requested+ if transform_to_gl:+ flat_points = flat_points.copy()+ flat_points[:, 1] = -flat_points[:, 1] # Flip Y+ flat_points[:, 2] = -flat_points[:, 2] # Flip Z++ # Create and export point cloud+ pcd = trimesh.PointCloud(flat_points, colors=flat_colors)+ pcd.export(filename)+